blob: d3b9258f3822d5ebf85afc9516c006d8b0d01d0d [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.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
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010033#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080035#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "pc/channel_manager.h"
37#include "pc/dtmf_sender.h"
38#include "pc/media_stream.h"
39#include "pc/media_stream_observer.h"
40#include "pc/remote_audio_source.h"
41#include "pc/rtp_media_utils.h"
42#include "pc/rtp_receiver.h"
43#include "pc/rtp_sender.h"
44#include "pc/sctp_utils.h"
45#include "pc/sdp_utils.h"
46#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010047#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/bind.h"
50#include "rtc_base/checks.h"
51#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010052#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020054#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "rtc_base/trace_event.h"
56#include "system_wrappers/include/clock.h"
57#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070058#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::ContentInfo;
61using cricket::ContentInfos;
62using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080063using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080064using cricket::RidDescription;
65using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080066using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080067using cricket::SimulcastDescription;
68using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080069using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080070using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080071using cricket::TransportInfo;
72
73using cricket::LOCAL_PORT_TYPE;
74using cricket::STUN_PORT_TYPE;
75using cricket::RELAY_PORT_TYPE;
76using cricket::PRFLX_PORT_TYPE;
77
Steve Antonba818672017-11-06 10:21:57 -080078namespace webrtc {
79
Steve Anton75737c02017-11-06 10:37:17 -080080// Error messages
81const char kBundleWithoutRtcpMux[] =
82 "rtcp-mux must be enabled when BUNDLE "
83 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kInvalidCandidates[] = "Description contains invalid candidates.";
85const char kInvalidSdp[] = "Invalid session description.";
86const char kMlineMismatchInAnswer[] =
87 "The order of m-lines in answer doesn't match order in offer. Rejecting "
88 "answer.";
89const char kMlineMismatchInSubsequentOffer[] =
90 "The order of m-lines in subsequent offer doesn't match order from "
91 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080092const char kSdpWithoutDtlsFingerprint[] =
93 "Called with SDP without DTLS fingerprint.";
94const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
95const char kSdpWithoutIceUfragPwd[] =
96 "Called with SDP without ice-ufrag and ice-pwd.";
97const char kSessionError[] = "Session error code: ";
98const char kSessionErrorDesc[] = "Session error description: ";
99const char kDtlsSrtpSetupFailureRtp[] =
100 "Couldn't set up DTLS-SRTP on RTP channel.";
101const char kDtlsSrtpSetupFailureRtcp[] =
102 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103
Steve Anton75737c02017-11-06 10:37:17 -0800104namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105
Seth Hampson845e8782018-03-02 11:34:10 -0800106static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800107static const char kDefaultAudioSenderId[] = "defaulta0";
108static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700109
zhihuang8f65cdf2016-05-06 18:40:30 -0700110// The length of RTCP CNAMEs.
111static const int kRtcpCnameLength = 16;
112
Steve Antonad182762018-09-05 20:22:40 +0000113enum {
114 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
115 MSG_SET_SESSIONDESCRIPTION_FAILED,
116 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
117 MSG_GETSTATS,
118 MSG_FREE_DATACHANNELS,
119 MSG_REPORT_USAGE_PATTERN,
120};
121
Harald Alvestrand19793842018-06-25 12:03:50 +0200122static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
123
Steve Antonad182762018-09-05 20:22:40 +0000124struct SetSessionDescriptionMsg : public rtc::MessageData {
125 explicit SetSessionDescriptionMsg(
126 webrtc::SetSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct CreateSessionDescriptionMsg : public rtc::MessageData {
134 explicit CreateSessionDescriptionMsg(
135 webrtc::CreateSessionDescriptionObserver* observer)
136 : observer(observer) {}
137
138 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
139 RTCError error;
140};
141
142struct GetStatsMsg : public rtc::MessageData {
143 GetStatsMsg(webrtc::StatsObserver* observer,
144 webrtc::MediaStreamTrackInterface* track)
145 : observer(observer), track(track) {}
146 rtc::scoped_refptr<webrtc::StatsObserver> observer;
147 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
148};
149
deadbeefab9b2d12015-10-14 11:33:11 -0700150// Check if we can send |new_stream| on a PeerConnection.
151bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
152 webrtc::MediaStreamInterface* new_stream) {
153 if (!new_stream || !current_streams) {
154 return false;
155 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700156 if (current_streams->find(new_stream->id()) != nullptr) {
157 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100158 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700159 return false;
160 }
161 return true;
162}
163
deadbeef5e97fb52015-10-15 12:49:08 -0700164// If the direction is "recvonly" or "inactive", treat the description
165// as containing no streams.
166// See: https://code.google.com/p/webrtc/issues/detail?id=5054
167std::vector<cricket::StreamParams> GetActiveStreams(
168 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800169 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700170 ? desc->streams()
171 : std::vector<cricket::StreamParams>();
172}
173
deadbeefab9b2d12015-10-14 11:33:11 -0700174bool IsValidOfferToReceiveMedia(int value) {
175 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
176 return (value >= Options::kUndefined) &&
177 (value <= Options::kMaxOfferToReceiveMedia);
178}
179
zhihuang1c378ed2017-08-17 14:10:50 -0700180// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800181void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700182 const std::vector<rtc::scoped_refptr<
183 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700184 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200185 cricket::MediaDescriptionOptions* video_media_description_options,
186 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700187 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700188 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
189 if (audio_media_description_options) {
190 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700191 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700192 }
193 } else {
194 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
195 if (video_media_description_options) {
196 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800197 sender->id(), sender->internal()->stream_ids(), {},
198 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700199 }
200 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700201 }
zhihuang1c378ed2017-08-17 14:10:50 -0700202}
olka3c747662017-08-17 06:50:32 -0700203
zhihuang1c378ed2017-08-17 14:10:50 -0700204// Add options to |session_options| from |rtp_data_channels|.
205void AddRtpDataChannelOptions(
206 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
207 rtp_data_channels,
208 cricket::MediaDescriptionOptions* data_media_description_options) {
209 if (!data_media_description_options) {
210 return;
211 }
deadbeefab9b2d12015-10-14 11:33:11 -0700212 // Check for data channels.
213 for (const auto& kv : rtp_data_channels) {
214 const DataChannel* channel = kv.second;
215 if (channel->state() == DataChannel::kConnecting ||
216 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700217 // Legacy RTP data channels are signaled with the track/stream ID set to
218 // the data channel's label.
219 data_media_description_options->AddRtpDataChannel(channel->label(),
220 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700221 }
222 }
223}
224
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225uint32_t ConvertIceTransportTypeToCandidateFilter(
226 PeerConnectionInterface::IceTransportsType type) {
227 switch (type) {
228 case PeerConnectionInterface::kNone:
229 return cricket::CF_NONE;
230 case PeerConnectionInterface::kRelay:
231 return cricket::CF_RELAY;
232 case PeerConnectionInterface::kNoHost:
233 return (cricket::CF_ALL & ~cricket::CF_HOST);
234 case PeerConnectionInterface::kAll:
235 return cricket::CF_ALL;
236 default:
nissec80e7412017-01-11 05:56:46 -0800237 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238 }
239 return cricket::CF_NONE;
240}
241
deadbeef293e9262017-01-11 12:28:30 -0800242// Helper to set an error and return from a method.
243bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
244 if (error) {
245 error->set_type(type);
246 }
247 return type == webrtc::RTCErrorType::NONE;
248}
249
Steve Anton038834f2017-07-14 15:59:59 -0700250bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700251 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700252 if (error_out) {
253 *error_out = std::move(error);
254 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700255 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700256}
257
Steve Antonba818672017-11-06 10:21:57 -0800258std::string GetSignalingStateString(
259 PeerConnectionInterface::SignalingState state) {
260 switch (state) {
261 case PeerConnectionInterface::kStable:
262 return "kStable";
263 case PeerConnectionInterface::kHaveLocalOffer:
264 return "kHaveLocalOffer";
265 case PeerConnectionInterface::kHaveLocalPrAnswer:
266 return "kHavePrAnswer";
267 case PeerConnectionInterface::kHaveRemoteOffer:
268 return "kHaveRemoteOffer";
269 case PeerConnectionInterface::kHaveRemotePrAnswer:
270 return "kHaveRemotePrAnswer";
271 case PeerConnectionInterface::kClosed:
272 return "kClosed";
273 }
274 RTC_NOTREACHED();
275 return "";
276}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277
Steve Anton75737c02017-11-06 10:37:17 -0800278IceCandidatePairType GetIceCandidatePairCounter(
279 const cricket::Candidate& local,
280 const cricket::Candidate& remote) {
281 const auto& l = local.type();
282 const auto& r = remote.type();
283 const auto& host = LOCAL_PORT_TYPE;
284 const auto& srflx = STUN_PORT_TYPE;
285 const auto& relay = RELAY_PORT_TYPE;
286 const auto& prflx = PRFLX_PORT_TYPE;
287 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800288 bool local_hostname =
289 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
290 bool remote_hostname = !remote.address().hostname().empty() &&
291 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800292 bool local_private = IPIsPrivate(local.address().ipaddr());
293 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800294 if (local_hostname) {
295 if (remote_hostname) {
296 return kIceCandidatePairHostNameHostName;
297 } else if (remote_private) {
298 return kIceCandidatePairHostNameHostPrivate;
299 } else {
300 return kIceCandidatePairHostNameHostPublic;
301 }
302 } else if (local_private) {
303 if (remote_hostname) {
304 return kIceCandidatePairHostPrivateHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800306 return kIceCandidatePairHostPrivateHostPrivate;
307 } else {
308 return kIceCandidatePairHostPrivateHostPublic;
309 }
310 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (remote_hostname) {
312 return kIceCandidatePairHostPublicHostName;
313 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800314 return kIceCandidatePairHostPublicHostPrivate;
315 } else {
316 return kIceCandidatePairHostPublicHostPublic;
317 }
318 }
319 }
320 if (l == host && r == srflx)
321 return kIceCandidatePairHostSrflx;
322 if (l == host && r == relay)
323 return kIceCandidatePairHostRelay;
324 if (l == host && r == prflx)
325 return kIceCandidatePairHostPrflx;
326 if (l == srflx && r == host)
327 return kIceCandidatePairSrflxHost;
328 if (l == srflx && r == srflx)
329 return kIceCandidatePairSrflxSrflx;
330 if (l == srflx && r == relay)
331 return kIceCandidatePairSrflxRelay;
332 if (l == srflx && r == prflx)
333 return kIceCandidatePairSrflxPrflx;
334 if (l == relay && r == host)
335 return kIceCandidatePairRelayHost;
336 if (l == relay && r == srflx)
337 return kIceCandidatePairRelaySrflx;
338 if (l == relay && r == relay)
339 return kIceCandidatePairRelayRelay;
340 if (l == relay && r == prflx)
341 return kIceCandidatePairRelayPrflx;
342 if (l == prflx && r == host)
343 return kIceCandidatePairPrflxHost;
344 if (l == prflx && r == srflx)
345 return kIceCandidatePairPrflxSrflx;
346 if (l == prflx && r == relay)
347 return kIceCandidatePairPrflxRelay;
348 return kIceCandidatePairMax;
349}
350
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800351// Logic to decide if an m= section can be recycled. This means that the new
352// m= section is not rejected, but the old local or remote m= section is
353// rejected. |old_content_one| and |old_content_two| refer to the m= section
354// of the old remote and old local descriptions in no particular order.
355// We need to check both the old local and remote because either
356// could be the most current from the latest negotation.
357bool IsMediaSectionBeingRecycled(SdpType type,
358 const ContentInfo& content,
359 const ContentInfo* old_content_one,
360 const ContentInfo* old_content_two) {
361 return type == SdpType::kOffer && !content.rejected &&
362 ((old_content_one && old_content_one->rejected) ||
363 (old_content_two && old_content_two->rejected));
364}
365
Steve Anton75737c02017-11-06 10:37:17 -0800366// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800367// |current_desc|. The number of m= sections in |new_desc| should be no
368// less than |current_desc|. In the case of checking an answer's
369// |new_desc|, the |current_desc| is the last offer that was set as the
370// local or remote. In the case of checking an offer's |new_desc| we
371// check against the local and remote descriptions stored from the last
372// negotiation, because either of these could be the most up to date for
373// possible rejected m sections. These are the |current_desc| and
374// |secondary_current_desc|.
375bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
376 const SessionDescription* secondary_current_desc,
377 const SessionDescription& new_desc,
378 const SdpType type) {
379 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800383 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
384 const cricket::ContentInfo* secondary_content_info = nullptr;
385 if (secondary_current_desc &&
386 i < secondary_current_desc->contents().size()) {
387 secondary_content_info = &secondary_current_desc->contents()[i];
388 }
389 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
390 &current_desc.contents()[i],
391 secondary_content_info)) {
392 // For new offer descriptions, if the media section can be recycled, it's
393 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800394 continue;
395 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 new_desc.contents()[i].media_description();
401 const MediaContentDescription* current_desc_mdesc =
402 current_desc.contents()[i].media_description();
403 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800404 return false;
405 }
406 }
407 return true;
408}
409
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
411 const SessionDescription& desc2) {
412 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800413}
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
416 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200417 // Array of structs needed to map {KeyExchangeProtocolType,
418 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
419 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
420 static constexpr struct {
421 KeyExchangeProtocolType protocol_type;
422 cricket::MediaType media_type;
423 KeyExchangeProtocolMedia protocol_media;
424 } kEnumCounterKeyProtocolMediaMap[] = {
425 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
426 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
427 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
428 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
429 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
430 kEnumCounterKeyProtocolMediaTypeDtlsData},
431 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
432 kEnumCounterKeyProtocolMediaTypeSdesAudio},
433 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
434 kEnumCounterKeyProtocolMediaTypeSdesVideo},
435 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
436 kEnumCounterKeyProtocolMediaTypeSdesData},
437 };
438
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700439 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
440 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100441
Mirko Bonadeiab499822018-09-11 10:43:20 +0200442 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
443 if (i.protocol_type == protocol_type && i.media_type == media_type) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
445 i.protocol_media,
446 kEnumCounterKeyProtocolMediaTypeMax);
447 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100448 }
449}
450
Harald Alvestrand76829d72018-07-18 23:24:36 +0200451void NoteAddIceCandidateResult(int result) {
452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
453 kAddIceCandidateMax);
454}
455
Steve Anton75737c02017-11-06 10:37:17 -0800456// Checks that each non-rejected content has SDES crypto keys or a DTLS
457// fingerprint, unless it's in a BUNDLE group, in which case only the
458// BUNDLE-tag section (first media section/description in the BUNDLE group)
459// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
460// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
461// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700462RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800463 const cricket::ContentGroup* bundle =
464 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800465 for (const cricket::ContentInfo& content_info : desc->contents()) {
466 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800467 continue;
468 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100469 // Note what media is used with each crypto protocol, for all sections.
470 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
471 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700472 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800473 const std::string& mid = content_info.name;
474 if (bundle && bundle->HasContentName(mid) &&
475 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 // This isn't the first media section in the BUNDLE group, so it's not
477 // required to have crypto attributes, since only the crypto attributes
478 // from the first section actually get used.
479 continue;
480 }
481
482 // If the content isn't rejected or bundled into another m= section, crypto
483 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800484 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800485 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!media || !tinfo) {
487 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800488 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800489 }
490 if (dtls_enabled) {
491 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING)
493 << "Session description must have DTLS fingerprint if "
494 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800495 return RTCError(RTCErrorType::INVALID_PARAMETER,
496 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800497 }
498 } else {
499 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100500 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800501 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800502 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800503 }
504 }
505 }
Steve Anton8a006912017-12-04 15:25:56 -0800506 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800507}
508
509// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
510// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
511// media section/description in the BUNDLE group) needs a ufrag and pwd.
512bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
513 const cricket::ContentGroup* bundle =
514 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800515 for (const cricket::ContentInfo& content_info : desc->contents()) {
516 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800517 continue;
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 const std::string& mid = content_info.name;
520 if (bundle && bundle->HasContentName(mid) &&
521 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 // This isn't the first media section in the BUNDLE group, so it's not
523 // required to have ufrag/password, since only the ufrag/password from
524 // the first section actually get used.
525 continue;
526 }
527
528 // If the content isn't rejected or bundled into another m= section,
529 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800530 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800531 if (!tinfo) {
532 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800534 return false;
535 }
536 if (tinfo->description.ice_ufrag.empty() ||
537 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 }
542 return true;
543}
544
Steve Anton75737c02017-11-06 10:37:17 -0800545// Get the SCTP port out of a SessionDescription.
546// Return -1 if not found.
547int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 const cricket::DataContentDescription* data_desc =
549 GetFirstDataContentDescription(session_description);
550 RTC_DCHECK(data_desc);
551 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800552 return -1;
553 }
Steve Anton75737c02017-11-06 10:37:17 -0800554 std::string value;
555 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
556 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800557 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800558 if (!codec.Matches(match_pattern)) {
559 continue;
560 }
561 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
562 return rtc::FromString<int>(value);
563 }
564 }
565 return -1;
566}
567
Steve Anton75737c02017-11-06 10:37:17 -0800568// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
569bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
570 const SessionDescriptionInterface* new_desc,
571 const std::string& content_name) {
572 if (!old_desc) {
573 return false;
574 }
575 const SessionDescription* new_sd = new_desc->description();
576 const SessionDescription* old_sd = old_desc->description();
577 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
578 if (!cinfo || cinfo->rejected) {
579 return false;
580 }
581 // If the content isn't rejected, check if ufrag and password has changed.
582 const cricket::TransportDescription* new_transport_desc =
583 new_sd->GetTransportDescriptionByName(content_name);
584 const cricket::TransportDescription* old_transport_desc =
585 old_sd->GetTransportDescriptionByName(content_name);
586 if (!new_transport_desc || !old_transport_desc) {
587 // No transport description exists. This is not an ICE restart.
588 return false;
589 }
590 if (cricket::IceCredentialsChanged(
591 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
592 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100593 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
594 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800595 return true;
596 }
597 return false;
598}
599
Steve Anton80dd7b52018-02-16 17:08:42 -0800600// Generates a string error message for SetLocalDescription/SetRemoteDescription
601// from an RTCError.
602std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
603 SdpType type,
604 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200605 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800606 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
607 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200608 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800609}
610
Seth Hampson5b4f0752018-04-02 16:31:36 -0700611std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
612 std::string output = "streams=[";
613 const char* separator = "";
614 for (const auto& stream_id : stream_ids) {
615 output.append(separator).append(stream_id);
616 separator = ", ";
617 }
618 output.append("]");
619 return output;
620}
621
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200622absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700623 int rtc_configuration_parameter) {
624 if (rtc_configuration_parameter ==
625 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200626 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700627 }
628 return rtc_configuration_parameter;
629}
630
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800631cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
632 switch (type) {
633 case DataMessageType::kText:
634 return cricket::DMT_TEXT;
635 case DataMessageType::kBinary:
636 return cricket::DMT_BINARY;
637 case DataMessageType::kControl:
638 return cricket::DMT_CONTROL;
639 default:
640 return cricket::DMT_NONE;
641 }
642 return cricket::DMT_NONE;
643}
644
645DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
646 switch (type) {
647 case cricket::DMT_TEXT:
648 return DataMessageType::kText;
649 case cricket::DMT_BINARY:
650 return DataMessageType::kBinary;
651 case cricket::DMT_CONTROL:
652 return DataMessageType::kControl;
653 case cricket::DMT_NONE:
654 default:
655 RTC_NOTREACHED();
656 }
657 return DataMessageType::kControl;
658}
659
Steve Anton75737c02017-11-06 10:37:17 -0800660} // namespace
661
Henrik Boström31638672017-11-23 17:48:32 +0100662// Upon completion, posts a task to execute the callback of the
663// SetSessionDescriptionObserver asynchronously on the same thread. At this
664// point, the state of the peer connection might no longer reflect the effects
665// of the SetRemoteDescription operation, as the peer connection could have been
666// modified during the post.
667// TODO(hbos): Remove this class once we remove the version of
668// PeerConnectionInterface::SetRemoteDescription() that takes a
669// SetSessionDescriptionObserver as an argument.
670class PeerConnection::SetRemoteDescriptionObserverAdapter
671 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
672 public:
673 SetRemoteDescriptionObserverAdapter(
674 rtc::scoped_refptr<PeerConnection> pc,
675 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
676 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
677
678 // SetRemoteDescriptionObserverInterface implementation.
679 void OnSetRemoteDescriptionComplete(RTCError error) override {
680 if (error.ok())
681 pc_->PostSetSessionDescriptionSuccess(wrapper_);
682 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100683 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100684 }
685
686 private:
687 rtc::scoped_refptr<PeerConnection> pc_;
688 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
689};
690
deadbeef293e9262017-01-11 12:28:30 -0800691bool PeerConnectionInterface::RTCConfiguration::operator==(
692 const PeerConnectionInterface::RTCConfiguration& o) const {
693 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700694 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800695 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000696 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800698 BundlePolicy bundle_policy;
699 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
701 int ice_candidate_pool_size;
702 bool disable_ipv6;
703 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700704 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100705 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700706 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200707 absl::optional<int> screencast_min_bitrate;
708 absl::optional<bool> combined_audio_video_bwe;
709 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800710 TcpCandidatePolicy tcp_candidate_policy;
711 CandidateNetworkPolicy candidate_network_policy;
712 int audio_jitter_buffer_max_packets;
713 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100714 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100715 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800716 int ice_connection_receiving_timeout;
717 int ice_backup_candidate_pair_ping_interval;
718 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800719 bool prioritize_most_likely_ice_candidate_pairs;
720 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800721 bool prune_turn_ports;
722 bool presume_writable_when_fully_relayed;
723 bool enable_ice_renomination;
724 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200725 absl::optional<int> ice_check_interval_strong_connectivity;
726 absl::optional<int> ice_check_interval_weak_connectivity;
727 absl::optional<int> ice_check_min_interval;
728 absl::optional<int> ice_unwritable_timeout;
729 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800730 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 audio_jitter_buffer_min_delay_ms ==
754 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100755 audio_jitter_buffer_enable_rtx_handling ==
756 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800757 ice_connection_receiving_timeout ==
758 o.ice_connection_receiving_timeout &&
759 ice_backup_candidate_pair_ping_interval ==
760 o.ice_backup_candidate_pair_ping_interval &&
761 continual_gathering_policy == o.continual_gathering_policy &&
762 certificates == o.certificates &&
763 prioritize_most_likely_ice_candidate_pairs ==
764 o.prioritize_most_likely_ice_candidate_pairs &&
765 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800766 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700767 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100768 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800769 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800770 screencast_min_bitrate == o.screencast_min_bitrate &&
771 combined_audio_video_bwe == o.combined_audio_video_bwe &&
772 enable_dtls_srtp == o.enable_dtls_srtp &&
773 ice_candidate_pool_size == o.ice_candidate_pool_size &&
774 prune_turn_ports == o.prune_turn_ports &&
775 presume_writable_when_fully_relayed ==
776 o.presume_writable_when_fully_relayed &&
777 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800778 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800779 ice_check_interval_strong_connectivity ==
780 o.ice_check_interval_strong_connectivity &&
781 ice_check_interval_weak_connectivity ==
782 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700783 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700784 ice_unwritable_timeout == o.ice_unwritable_timeout &&
785 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800786 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800787 stun_candidate_keepalive_interval ==
788 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200789 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800790 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800791 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700792 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700793 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700794 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700795 use_media_transport_for_data_channels ==
796 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100797 crypto_options == o.crypto_options &&
798 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800799}
800
801bool PeerConnectionInterface::RTCConfiguration::operator!=(
802 const PeerConnectionInterface::RTCConfiguration& o) const {
803 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800804}
805
zhihuang8f65cdf2016-05-06 18:40:30 -0700806// Generate a RTCP CNAME when a PeerConnection is created.
807std::string GenerateRtcpCname() {
808 std::string cname;
809 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100810 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800811 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700812 }
813 return cname;
814}
815
zhihuang1c378ed2017-08-17 14:10:50 -0700816bool ValidateOfferAnswerOptions(
817 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
818 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
819 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700820}
821
zhihuang1c378ed2017-08-17 14:10:50 -0700822// From |rtc_options|, fill parts of |session_options| shared by all generated
823// m= sections (in other words, nothing that involves a map/array).
824void ExtractSharedMediaSessionOptions(
825 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
826 cricket::MediaSessionOptions* session_options) {
827 session_options->vad_enabled = rtc_options.voice_activity_detection;
828 session_options->bundle_enabled = rtc_options.use_rtp_mux;
829}
zhihuanga77e6bb2017-08-14 18:17:48 -0700830
zhihuang38ede132017-06-15 12:52:32 -0700831PeerConnection::PeerConnection(PeerConnectionFactory* factory,
832 std::unique_ptr<RtcEventLog> event_log,
833 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700835 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100836 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700837 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700838 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700839 remote_streams_(StreamCollection::Create()),
840 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841
842PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100843 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800844 RTC_DCHECK_RUN_ON(signaling_thread());
845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Need to stop transceivers before destroying the stats collector because
847 // AudioRtpSender has a reference to the StatsCollector it will update when
848 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100849 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800850 transceiver->Stop();
851 }
Steve Anton4171afb2017-11-20 10:20:22 -0800852
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800854 if (stats_collector_) {
855 stats_collector_->WaitForPendingRequest();
856 stats_collector_ = nullptr;
857 }
Steve Anton75737c02017-11-06 10:37:17 -0800858
Steve Anton8af21862017-12-15 11:20:13 -0800859 // Don't destroy BaseChannels until after stats has been cleaned up so that
860 // the last stats request can still read from the channels.
861 DestroyAllChannels();
862
Mirko Bonadei675513b2017-11-09 11:09:25 +0100863 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800864
865 webrtc_session_desc_factory_.reset();
866 sctp_invoker_.reset();
867 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800868 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800869 transport_controller_.reset();
870
deadbeef91dd5672016-05-18 16:55:30 -0700871 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700872 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700873 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700874 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700875 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100876 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700877 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800878 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700879 event_log_.reset();
880 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881}
882
Steve Anton8af21862017-12-15 11:20:13 -0800883void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 // Destroy video channels first since they may have a pointer to a voice
885 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100886 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800887 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800888 DestroyTransceiverChannel(transceiver);
889 }
890 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100891 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800892 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800893 DestroyTransceiverChannel(transceiver);
894 }
895 }
896 DestroyDataChannel();
897}
898
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000900 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700901 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100902 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100903 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100904 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700905
906 RTCError config_error = ValidateConfiguration(configuration);
907 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700909 return false;
910 }
911
Benjamin Wrightcab58882018-05-02 15:12:47 -0700912 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100913 RTC_LOG(LS_ERROR)
914 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100915 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800916 return false;
917 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200918
Benjamin Wrightcab58882018-05-02 15:12:47 -0700919 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800920 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100921 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100922 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800923 return false;
924 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700925
Benjamin Wrightcab58882018-05-02 15:12:47 -0700926 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700927 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700928 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700929 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800930
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200931 cricket::ServerAddresses stun_servers;
932 std::vector<cricket::RelayServerConfig> turn_servers;
933
934 RTCErrorType parse_error =
935 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
936 if (parse_error != RTCErrorType::NONE) {
937 return false;
938 }
939
deadbeef91dd5672016-05-18 16:55:30 -0700940 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700941 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700942 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200943 RTC_FROM_HERE,
944 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
945 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946 return false;
947 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200948 // If initialization was successful, note if STUN or TURN servers
949 // were supplied.
950 if (!stun_servers.empty()) {
951 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
952 }
953 if (!turn_servers.empty()) {
954 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
955 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700957 // Send information about IPv4/IPv6 status.
958 PeerConnectionAddressFamilyCounter address_family;
959 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
960 address_family = kPeerConnection_IPv6;
961 } else {
962 address_family = kPeerConnection_IPv4;
963 }
964 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
965 kPeerConnectionAddressFamilyCounter_Max);
966
Zhi Huange830e682018-03-30 10:48:35 -0700967 const PeerConnectionFactoryInterface::Options& options = factory_->options();
968
Steve Anton75737c02017-11-06 10:37:17 -0800969 // RFC 3264: The numeric value of the session id and version in the
970 // o line MUST be representable with a "64 bit signed integer".
971 // Due to this constraint session id |session_id_| is max limited to
972 // LLONG_MAX.
973 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700974 JsepTransportController::Config config;
975 config.redetermine_role_on_ice_restart =
976 configuration.redetermine_role_on_ice_restart;
977 config.ssl_max_version = factory_->options().ssl_max_version;
978 config.disable_encryption = options.disable_encryption;
979 config.bundle_policy = configuration.bundle_policy;
980 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700981 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
982 // stub.
983 config.crypto_options = configuration.crypto_options.has_value()
984 ? *configuration.crypto_options
985 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700986 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +0100987 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -0700988#if defined(ENABLE_EXTERNAL_AUTH)
989 config.enable_external_auth = true;
990#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700991 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700992
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700993 if (configuration.use_media_transport ||
994 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700995 if (!factory_->media_transport_factory()) {
996 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700997 << "PeerConnecton is initialized with use_media_transport = true or "
998 << "use_media_transport_for_data_channels = true "
999 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001000 return false;
1001 }
1002
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001003 config.use_media_transport_for_media = configuration.use_media_transport;
1004 config.use_media_transport_for_data_channels =
1005 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001006 config.media_transport_factory = factory_->media_transport_factory();
1007 }
1008
Zhi Huange830e682018-03-30 10:48:35 -07001009 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001010 signaling_thread(), network_thread(), port_allocator_.get(),
1011 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001012 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001013 this, &PeerConnection::OnTransportControllerConnectionState);
1014 transport_controller_->SignalStandardizedIceConnectionState.connect(
1015 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001016 transport_controller_->SignalConnectionState.connect(
1017 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001018 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001019 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001020 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001021 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001022 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001023 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1024 transport_controller_->SignalDtlsHandshakeError.connect(
1025 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1026
1027 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001028
deadbeefab9b2d12015-10-14 11:33:11 -07001029 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001030 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031
Steve Antonba818672017-11-06 10:21:57 -08001032 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001033 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001034
Steve Anton75737c02017-11-06 10:37:17 -08001035 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1036 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1037 if (!configuration.certificates.empty()) {
1038 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1039 // just picking the first one. The decision should be made based on the DTLS
1040 // handshake. The DTLS negotiations need to know about all certificates.
1041 certificate = configuration.certificates[0];
1042 }
1043
Steve Antond25da372017-11-06 14:50:29 -08001044 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001045
1046 if (options.disable_encryption) {
1047 dtls_enabled_ = false;
1048 } else {
1049 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001050 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001051 // |configuration| can override the default |dtls_enabled_| value.
1052 if (configuration.enable_dtls_srtp) {
1053 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1054 }
1055 }
1056
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001057 if (configuration.use_media_transport_for_data_channels) {
1058 if (configuration.enable_rtp_data_channel) {
1059 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1060 "use_media_transport_for_data_channels are "
1061 "incompatible and cannot both be set to true";
1062 return false;
1063 }
1064 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1065 } else if (configuration.enable_rtp_data_channel) {
1066 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1067 // set. It takes precendence over the disable_sctp_data_channels
1068 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001069 data_channel_type_ = cricket::DCT_RTP;
1070 } else {
1071 // DTLS has to be enabled to use SCTP.
1072 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1073 data_channel_type_ = cricket::DCT_SCTP;
1074 }
1075 }
1076
1077 video_options_.screencast_min_bitrate_kbps =
1078 configuration.screencast_min_bitrate;
1079 audio_options_.combined_audio_video_bwe =
1080 configuration.combined_audio_video_bwe;
1081
1082 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001083 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001084
1085 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001086 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001087
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001088 audio_options_.audio_jitter_buffer_min_delay_ms =
1089 configuration.audio_jitter_buffer_min_delay_ms;
1090
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001091 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1092 configuration.audio_jitter_buffer_enable_rtx_handling;
1093
Steve Anton75737c02017-11-06 10:37:17 -08001094 // Whether the certificate generator/certificate is null or not determines
1095 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1096 // the right instructions by clearing the variables if needed.
1097 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001098 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001099 certificate = nullptr;
1100 } else if (certificate) {
1101 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001102 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001103 }
1104
1105 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1106 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001107 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001108 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1109 this, &PeerConnection::OnCertificateReady);
1110
1111 if (options.disable_encryption) {
1112 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1113 }
1114
1115 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001116 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001117 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118
Steve Anton4171afb2017-11-20 10:20:22 -08001119 // Add default audio/video transceivers for Plan B SDP.
1120 if (!IsUnifiedPlan()) {
1121 transceivers_.push_back(
1122 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1123 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1124 transceivers_.push_back(
1125 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1126 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1127 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001128 int delay_ms =
1129 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001130 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1131 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 return true;
1133}
1134
Steve Anton038834f2017-07-14 15:59:59 -07001135RTCError PeerConnection::ValidateConfiguration(
1136 const RTCConfiguration& config) const {
1137 if (config.ice_regather_interval_range &&
1138 config.continual_gathering_policy == GATHER_ONCE) {
1139 return RTCError(RTCErrorType::INVALID_PARAMETER,
1140 "ice_regather_interval_range specified but continual "
1141 "gathering policy is GATHER_ONCE");
1142 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001143 auto result =
1144 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1145 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001146}
1147
Yves Gerey665174f2018-06-19 15:03:05 +02001148rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001149 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001150 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1151 "Plan SdpSemantics. Please use GetSenders "
1152 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001153 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154}
1155
Yves Gerey665174f2018-06-19 15:03:05 +02001156rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001157 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001158 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1159 "Plan SdpSemantics. Please use GetReceivers "
1160 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001161 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162}
1163
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001164bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001165 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001166 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1167 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001168 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 if (IsClosed()) {
1170 return false;
1171 }
deadbeefab9b2d12015-10-14 11:33:11 -07001172 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 return false;
1174 }
deadbeefab9b2d12015-10-14 11:33:11 -07001175
1176 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001177 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1178 observer->SignalAudioTrackAdded.connect(this,
1179 &PeerConnection::OnAudioTrackAdded);
1180 observer->SignalAudioTrackRemoved.connect(
1181 this, &PeerConnection::OnAudioTrackRemoved);
1182 observer->SignalVideoTrackAdded.connect(this,
1183 &PeerConnection::OnVideoTrackAdded);
1184 observer->SignalVideoTrackRemoved.connect(
1185 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001186 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001187
deadbeefab9b2d12015-10-14 11:33:11 -07001188 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001189 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001190 }
1191 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001192 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001193 }
1194
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001195 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001196 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 return true;
1198}
1199
1200void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001201 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001202 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1203 "Plan SdpSemantics. Please use RemoveTrack "
1204 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001205 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001206 if (!IsClosed()) {
1207 for (const auto& track : local_stream->GetAudioTracks()) {
1208 RemoveAudioTrack(track.get(), local_stream);
1209 }
1210 for (const auto& track : local_stream->GetVideoTracks()) {
1211 RemoveVideoTrack(track.get(), local_stream);
1212 }
deadbeefab9b2d12015-10-14 11:33:11 -07001213 }
deadbeefab9b2d12015-10-14 11:33:11 -07001214 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001215 stream_observers_.erase(
1216 std::remove_if(
1217 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001218 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001219 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001220 }),
1221 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001222
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 if (IsClosed()) {
1224 return;
1225 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001226 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227}
1228
Steve Anton2d6c76a2018-01-05 17:10:52 -08001229RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001230 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001231 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001232 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001233 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001234 if (!track) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1236 }
1237 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1238 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1240 "Track has invalid kind: " + track->kind());
1241 }
Steve Antonf9381f02017-12-14 10:23:57 -08001242 if (IsClosed()) {
1243 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1244 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001245 }
Steve Anton4171afb2017-11-20 10:20:22 -08001246 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001247 LOG_AND_RETURN_ERROR(
1248 RTCErrorType::INVALID_PARAMETER,
1249 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001250 }
Steve Antonf9381f02017-12-14 10:23:57 -08001251 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001252 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1253 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001254 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001255 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001256 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001257 }
1258 return sender_or_error;
1259}
deadbeefe1f9d832016-01-14 15:35:42 -08001260
Steve Antonf9381f02017-12-14 10:23:57 -08001261RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1262PeerConnection::AddTrackPlanB(
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001264 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001265 if (stream_ids.size() > 1u) {
1266 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1267 "AddTrack with more than one stream is not "
1268 "supported with Plan B semantics.");
1269 }
1270 std::vector<std::string> adjusted_stream_ids = stream_ids;
1271 if (adjusted_stream_ids.empty()) {
1272 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1273 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001274 cricket::MediaType media_type =
1275 (track->kind() == MediaStreamTrackInterface::kAudioKind
1276 ? cricket::MEDIA_TYPE_AUDIO
1277 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001278 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001279 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001280 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001281 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001282 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001283 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001284 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001285 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001286 if (sender_info) {
1287 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001288 }
Steve Antonf9381f02017-12-14 10:23:57 -08001289 } else {
1290 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001291 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001292 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001293 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001294 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001295 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001296 if (sender_info) {
1297 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001298 }
deadbeefe1f9d832016-01-14 15:35:42 -08001299 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001300 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001301}
deadbeefe1f9d832016-01-14 15:35:42 -08001302
Steve Antonf9381f02017-12-14 10:23:57 -08001303RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1304PeerConnection::AddTrackUnifiedPlan(
1305 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001306 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001307 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1308 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001309 RTC_LOG(LS_INFO) << "Reusing an existing "
1310 << cricket::MediaTypeToString(transceiver->media_type())
1311 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001312 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001313 transceiver->internal()->set_direction(
1314 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001315 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001316 transceiver->internal()->set_direction(
1317 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001318 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001319 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001320 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 } else {
1322 cricket::MediaType media_type =
1323 (track->kind() == MediaStreamTrackInterface::kAudioKind
1324 ? cricket::MEDIA_TYPE_AUDIO
1325 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001326 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1327 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001328 std::string sender_id = track->id();
1329 // Avoid creating a sender with an existing ID by generating a random ID.
1330 // This can happen if this is the second time AddTrack has created a sender
1331 // for this track.
1332 if (FindSenderById(sender_id)) {
1333 sender_id = rtc::CreateRandomUuid();
1334 }
Florent Castelli892acf02018-10-01 22:47:20 +02001335 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001336 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1337 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001338 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001339 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001340 }
Steve Antonf9381f02017-12-14 10:23:57 -08001341 return transceiver->sender();
1342}
1343
1344rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1345PeerConnection::FindFirstTransceiverForAddedTrack(
1346 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1347 RTC_DCHECK(track);
1348 for (auto transceiver : transceivers_) {
1349 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001350 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001351 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001352 !transceiver->internal()->has_ever_been_used_to_send() &&
1353 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001354 return transceiver;
1355 }
1356 }
1357 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001358}
1359
1360bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1361 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001362 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001363}
1364
Steve Anton24db5732018-07-23 10:27:33 -07001365RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001366 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001367 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001368 if (!sender) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1370 }
deadbeefe1f9d832016-01-14 15:35:42 -08001371 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1373 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001374 }
Steve Antonf9381f02017-12-14 10:23:57 -08001375 if (IsUnifiedPlan()) {
1376 auto transceiver = FindTransceiverBySender(sender);
1377 if (!transceiver || !sender->track()) {
1378 return RTCError::OK();
1379 }
1380 sender->SetTrack(nullptr);
1381 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001382 transceiver->internal()->set_direction(
1383 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001384 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001385 transceiver->internal()->set_direction(
1386 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001387 }
Steve Anton4171afb2017-11-20 10:20:22 -08001388 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001389 bool removed;
1390 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1391 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1392 } else {
1393 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1394 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1395 }
1396 if (!removed) {
1397 LOG_AND_RETURN_ERROR(
1398 RTCErrorType::INVALID_PARAMETER,
1399 "Couldn't find sender " + sender->id() + " to remove.");
1400 }
Steve Anton4171afb2017-11-20 10:20:22 -08001401 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001402 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001403 return RTCError::OK();
1404}
1405
1406rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1407PeerConnection::FindTransceiverBySender(
1408 rtc::scoped_refptr<RtpSenderInterface> sender) {
1409 for (auto transceiver : transceivers_) {
1410 if (transceiver->sender() == sender) {
1411 return transceiver;
1412 }
1413 }
1414 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001415}
1416
Steve Anton9158ef62017-11-27 13:01:52 -08001417RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1418PeerConnection::AddTransceiver(
1419 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1420 return AddTransceiver(track, RtpTransceiverInit());
1421}
1422
1423RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1424PeerConnection::AddTransceiver(
1425 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1426 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001427 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001428 RTC_CHECK(IsUnifiedPlan())
1429 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001430 if (!track) {
1431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1432 }
1433 cricket::MediaType media_type;
1434 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1435 media_type = cricket::MEDIA_TYPE_AUDIO;
1436 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1437 media_type = cricket::MEDIA_TYPE_VIDEO;
1438 } else {
1439 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1440 "Track kind is not audio or video");
1441 }
1442 return AddTransceiver(media_type, track, init);
1443}
1444
1445RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1446PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1447 return AddTransceiver(media_type, RtpTransceiverInit());
1448}
1449
1450RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1451PeerConnection::AddTransceiver(cricket::MediaType media_type,
1452 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001453 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001454 RTC_CHECK(IsUnifiedPlan())
1455 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001456 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1457 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1458 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1459 "media type is not audio or video");
1460 }
1461 return AddTransceiver(media_type, nullptr, init);
1462}
1463
1464RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1465PeerConnection::AddTransceiver(
1466 cricket::MediaType media_type,
1467 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001468 const RtpTransceiverInit& init,
1469 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001470 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1471 media_type == cricket::MEDIA_TYPE_VIDEO));
1472 if (track) {
1473 RTC_DCHECK_EQ(media_type,
1474 (track->kind() == MediaStreamTrackInterface::kAudioKind
1475 ? cricket::MEDIA_TYPE_AUDIO
1476 : cricket::MEDIA_TYPE_VIDEO));
1477 }
1478
Amit Hilbuchaa584152019-02-06 17:09:52 -08001479 size_t num_rids = absl::c_count_if(init.send_encodings,
1480 [](const RtpEncodingParameters& encoding) {
1481 return !encoding.rid.empty();
1482 });
1483 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001484 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001485 RTCErrorType::INVALID_PARAMETER,
1486 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001487 }
1488
Amit Hilbuchaa584152019-02-06 17:09:52 -08001489 if (absl::c_any_of(init.send_encodings,
1490 [](const RtpEncodingParameters& encoding) {
1491 return encoding.ssrc.has_value();
1492 })) {
1493 LOG_AND_RETURN_ERROR(
1494 RTCErrorType::UNSUPPORTED_PARAMETER,
1495 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001496 }
1497
1498 RtpParameters parameters;
1499 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001500
1501 // Encodings are dropped from the tail if too many are provided.
1502 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1503 parameters.encodings.erase(
1504 parameters.encodings.begin() + kMaxSimulcastStreams,
1505 parameters.encodings.end());
1506 }
1507
1508 // Single RID should be removed.
1509 if (parameters.encodings.size() == 1 &&
1510 !parameters.encodings[0].rid.empty()) {
1511 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1512 parameters.encodings[0].rid.clear();
1513 }
1514
1515 // If RIDs were not provided, they are generated for simulcast scenario.
1516 if (parameters.encodings.size() > 1 && num_rids == 0) {
1517 rtc::UniqueStringGenerator rid_generator;
1518 for (RtpEncodingParameters& encoding : parameters.encodings) {
1519 encoding.rid = rid_generator();
1520 }
1521 }
1522
Florent Castelli892acf02018-10-01 22:47:20 +02001523 if (UnimplementedRtpParameterHasValue(parameters)) {
1524 LOG_AND_RETURN_ERROR(
1525 RTCErrorType::UNSUPPORTED_PARAMETER,
1526 "Attempted to set an unimplemented parameter of RtpParameters.");
1527 }
Steve Anton9158ef62017-11-27 13:01:52 -08001528
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001529 auto result = cricket::CheckRtpParametersValues(parameters);
1530 if (!result.ok()) {
1531 LOG_AND_RETURN_ERROR(result.type(), result.message());
1532 }
1533
Steve Anton3d954a62018-04-02 11:27:23 -07001534 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1535 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001536 // Set the sender ID equal to the track ID if the track is specified unless
1537 // that sender ID is already in use.
1538 std::string sender_id =
1539 (track && !FindSenderById(track->id()) ? track->id()
1540 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001541 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001542 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001543 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1544 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1545 transceiver->internal()->set_direction(init.direction);
1546
Steve Anton22da89f2018-01-25 13:58:07 -08001547 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001548 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001549 }
Steve Antonf9381f02017-12-14 10:23:57 -08001550
1551 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1552}
1553
Steve Anton02ee47c2018-01-10 16:26:06 -08001554rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1555PeerConnection::CreateSender(
1556 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001557 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001559 const std::vector<std::string>& stream_ids,
1560 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001561 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001562 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1563 RTC_DCHECK(!track ||
1564 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1565 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1566 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001567 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001568 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001569 } else {
1570 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1571 RTC_DCHECK(!track ||
1572 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1573 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001574 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001575 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001576 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001577 bool set_track_succeeded = sender->SetTrack(track);
1578 RTC_DCHECK(set_track_succeeded);
1579 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001580 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001581 return sender;
1582}
1583
1584rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1585PeerConnection::CreateReceiver(cricket::MediaType media_type,
1586 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001587 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1588 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001589 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001590 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001591 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1592 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001593 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001594 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001595 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001596 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001597 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1598 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001599 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001600 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001601 return receiver;
1602}
1603
1604rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1605PeerConnection::CreateAndAddTransceiver(
1606 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1607 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1608 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001609 // Ensure that the new sender does not have an ID that is already in use by
1610 // another sender.
1611 // Allow receiver IDs to conflict since those come from remote SDP (which
1612 // could be invalid, but should not cause a crash).
1613 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001614 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1615 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001616 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001617 transceiver->internal()->SignalNegotiationNeeded.connect(
1618 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001619 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001620}
1621
Steve Anton52d86772018-02-20 15:48:12 -08001622void PeerConnection::OnNegotiationNeeded() {
1623 RTC_DCHECK_RUN_ON(signaling_thread());
1624 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001625 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001626}
1627
deadbeeffac06552015-11-25 11:26:01 -08001628rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001629 const std::string& kind,
1630 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001631 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001632 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1633 "Plan SdpSemantics. Please use AddTransceiver "
1634 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001635 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001636 if (IsClosed()) {
1637 return nullptr;
1638 }
Steve Anton4171afb2017-11-20 10:20:22 -08001639
Seth Hampson5b4f0752018-04-02 16:31:36 -07001640 // Internally we need to have one stream with Plan B semantics, so we
1641 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001642 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001643 if (stream_id.empty()) {
1644 stream_ids.push_back(rtc::CreateRandomUuid());
1645 RTC_LOG(LS_INFO)
1646 << "No stream_id specified for sender. Generated stream ID: "
1647 << stream_ids[0];
1648 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001649 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001650 }
1651
Steve Anton4171afb2017-11-20 10:20:22 -08001652 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001653 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001654 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001655 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001656 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001657 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001658 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001659 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001660 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001661 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001662 auto video_sender =
1663 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001664 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001665 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001666 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001667 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001668 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001669 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001670 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001671 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001672 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001673
deadbeefe1f9d832016-01-14 15:35:42 -08001674 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001675}
1676
deadbeef70ab1a12015-09-28 16:53:55 -07001677std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1678 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001679 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001680 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001681 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001682 }
1683 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001684}
1685
Steve Anton4171afb2017-11-20 10:20:22 -08001686std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1687PeerConnection::GetSendersInternal() const {
1688 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1689 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001690 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001691 auto senders = transceiver->internal()->senders();
1692 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1693 }
1694 return all_senders;
1695}
1696
deadbeef70ab1a12015-09-28 16:53:55 -07001697std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1698PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001699 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001700 for (const auto& receiver : GetReceiversInternal()) {
1701 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001702 }
1703 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001704}
1705
Steve Anton4171afb2017-11-20 10:20:22 -08001706std::vector<
1707 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1708PeerConnection::GetReceiversInternal() const {
1709 std::vector<
1710 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1711 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001712 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001713 auto receivers = transceiver->internal()->receivers();
1714 all_receivers.insert(all_receivers.end(), receivers.begin(),
1715 receivers.end());
1716 }
1717 return all_receivers;
1718}
1719
Steve Anton9158ef62017-11-27 13:01:52 -08001720std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1721PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001722 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001723 RTC_CHECK(IsUnifiedPlan())
1724 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001725 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001726 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001727 all_transceivers.push_back(transceiver);
1728 }
1729 return all_transceivers;
1730}
1731
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001732bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001733 MediaStreamTrackInterface* track,
1734 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001735 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001736 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001737 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001739 return false;
1740 }
1741
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001742 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001743 // The StatsCollector is used to tell if a track is valid because it may
1744 // remember tracks that the PeerConnection previously removed.
1745 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1747 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001748 return false;
1749 }
Steve Antonad182762018-09-05 20:22:40 +00001750 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1751 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001752 return true;
1753}
1754
hbos74e1a4f2016-09-15 23:33:01 -07001755void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001756 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001757 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001758 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001759 stats_collector_->GetStatsReport(callback);
1760}
1761
Henrik Boström1df1bf82018-03-20 13:24:20 +01001762void PeerConnection::GetStats(
1763 rtc::scoped_refptr<RtpSenderInterface> selector,
1764 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1765 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1766 RTC_DCHECK(callback);
1767 RTC_DCHECK(stats_collector_);
1768 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1769 if (selector) {
1770 for (const auto& proxy_transceiver : transceivers_) {
1771 for (const auto& proxy_sender :
1772 proxy_transceiver->internal()->senders()) {
1773 if (proxy_sender == selector) {
1774 internal_sender = proxy_sender->internal();
1775 break;
1776 }
1777 }
1778 if (internal_sender)
1779 break;
1780 }
1781 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001782 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001783 // belong to the PeerConnection (in Plan B, senders can be removed from the
1784 // PeerConnection). This means that "all the stats objects representing the
1785 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1786 // produces an empty stats report.
1787 stats_collector_->GetStatsReport(internal_sender, callback);
1788}
1789
1790void PeerConnection::GetStats(
1791 rtc::scoped_refptr<RtpReceiverInterface> selector,
1792 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1793 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1794 RTC_DCHECK(callback);
1795 RTC_DCHECK(stats_collector_);
1796 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1797 if (selector) {
1798 for (const auto& proxy_transceiver : transceivers_) {
1799 for (const auto& proxy_receiver :
1800 proxy_transceiver->internal()->receivers()) {
1801 if (proxy_receiver == selector) {
1802 internal_receiver = proxy_receiver->internal();
1803 break;
1804 }
1805 }
1806 if (internal_receiver)
1807 break;
1808 }
1809 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001810 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001811 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1812 // the PeerConnection). This means that "all the stats objects representing
1813 // the selector" is an empty set. Invoking GetStatsReport() with a null
1814 // selector produces an empty stats report.
1815 stats_collector_->GetStatsReport(internal_receiver, callback);
1816}
1817
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001819 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return signaling_state_;
1821}
1822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823PeerConnectionInterface::IceConnectionState
1824PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001825 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 return ice_connection_state_;
1827}
1828
Alex Loiko9289eda2018-11-23 16:18:59 +00001829PeerConnectionInterface::IceConnectionState
1830PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001831 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001832 return standardized_ice_connection_state_;
1833}
1834
Jonas Olsson635474e2018-10-18 15:58:17 +02001835PeerConnectionInterface::PeerConnectionState
1836PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001837 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001838 return connection_state_;
1839}
1840
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841PeerConnectionInterface::IceGatheringState
1842PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001843 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844 return ice_gathering_state_;
1845}
1846
Yves Gerey665174f2018-06-19 15:03:05 +02001847rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 const std::string& label,
1849 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001850 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001851 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001852
deadbeefab9b2d12015-10-14 11:33:11 -07001853 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001854
kwibergd1fe2812016-04-27 06:47:29 -07001855 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001856 if (config) {
1857 internal_config.reset(new InternalDataChannelInit(*config));
1858 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001859 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001860 InternalCreateDataChannel(label, internal_config.get()));
1861 if (!channel.get()) {
1862 return nullptr;
1863 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001865 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1866 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001867 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001868 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001869 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001870 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 return DataChannelProxy::Create(signaling_thread(), channel.get());
1872}
1873
1874void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001875 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001876 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001877 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001878
nisse7ce109a2017-01-31 00:57:56 -08001879 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001881 return;
1882 }
deadbeefab9b2d12015-10-14 11:33:11 -07001883
Steve Anton8d3444d2017-10-20 15:30:51 -07001884 if (IsClosed()) {
1885 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001886 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001887 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001888 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001889 return;
1890 }
1891
zhihuang1c378ed2017-08-17 14:10:50 -07001892 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001893 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001894 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001895 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001896 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001897 return;
1898 }
1899
Steve Anton22da89f2018-01-25 13:58:07 -08001900 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1901 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1902 if (IsUnifiedPlan()) {
1903 RTCError error = HandleLegacyOfferOptions(options);
1904 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001905 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001906 return;
1907 }
1908 }
1909
zhihuang1c378ed2017-08-17 14:10:50 -07001910 cricket::MediaSessionOptions session_options;
1911 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001912 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913}
1914
Steve Anton22da89f2018-01-25 13:58:07 -08001915RTCError PeerConnection::HandleLegacyOfferOptions(
1916 const RTCOfferAnswerOptions& options) {
1917 RTC_DCHECK(IsUnifiedPlan());
1918
1919 if (options.offer_to_receive_audio == 0) {
1920 RemoveRecvDirectionFromReceivingTransceiversOfType(
1921 cricket::MEDIA_TYPE_AUDIO);
1922 } else if (options.offer_to_receive_audio == 1) {
1923 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1924 } else if (options.offer_to_receive_audio > 1) {
1925 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1926 "offer_to_receive_audio > 1 is not supported.");
1927 }
1928
1929 if (options.offer_to_receive_video == 0) {
1930 RemoveRecvDirectionFromReceivingTransceiversOfType(
1931 cricket::MEDIA_TYPE_VIDEO);
1932 } else if (options.offer_to_receive_video == 1) {
1933 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1934 } else if (options.offer_to_receive_video > 1) {
1935 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1936 "offer_to_receive_video > 1 is not supported.");
1937 }
1938
1939 return RTCError::OK();
1940}
1941
1942void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1943 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001944 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001945 RtpTransceiverDirection new_direction =
1946 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1947 if (new_direction != transceiver->direction()) {
1948 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1949 << " transceiver (MID="
1950 << transceiver->mid().value_or("<not set>") << ") from "
1951 << RtpTransceiverDirectionToString(
1952 transceiver->direction())
1953 << " to "
1954 << RtpTransceiverDirectionToString(new_direction)
1955 << " since CreateOffer specified offer_to_receive=0";
1956 transceiver->internal()->set_direction(new_direction);
1957 }
Steve Anton22da89f2018-01-25 13:58:07 -08001958 }
1959}
1960
1961void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1962 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001963 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001964 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001965 RTC_LOG(LS_INFO)
1966 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1967 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001968 RtpTransceiverInit init;
1969 init.direction = RtpTransceiverDirection::kRecvOnly;
1970 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1971 }
1972}
1973
1974std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1975PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1976 std::vector<
1977 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1978 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001979 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001980 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001981 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1982 receiving_transceivers.push_back(transceiver);
1983 }
1984 }
1985 return receiving_transceivers;
1986}
1987
htaa2a49d92016-03-04 02:51:39 -08001988void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1989 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001990 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08001991 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001992 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001993 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001994 return;
1995 }
1996
Steve Antondffead82018-02-06 10:31:29 -08001997 if (!(signaling_state_ == kHaveRemoteOffer ||
1998 signaling_state_ == kHaveLocalPrAnswer)) {
1999 std::string error =
2000 "PeerConnection cannot create an answer in a state other than "
2001 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002002 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002003 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002004 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002005 return;
2006 }
2007
Steve Antondffead82018-02-06 10:31:29 -08002008 // The remote description should be set if we're in the right state.
2009 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002010
Steve Anton22da89f2018-01-25 13:58:07 -08002011 if (IsUnifiedPlan()) {
2012 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2013 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2014 "supported with Unified Plan semantics. Use the "
2015 "RtpTransceiver API instead.";
2016 }
2017 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2018 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2019 "supported with Unified Plan semantics. Use the "
2020 "RtpTransceiver API instead.";
2021 }
2022 }
2023
htaa2a49d92016-03-04 02:51:39 -08002024 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002025 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002026
Steve Antond25da372017-11-06 14:50:29 -08002027 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028}
2029
2030void PeerConnection::SetLocalDescription(
2031 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002032 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002033 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002034 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002035
Steve Anton80dd7b52018-02-16 17:08:42 -08002036 // The SetLocalDescription contract is that we take ownership of the session
2037 // description regardless of the outcome, so wrap it in a unique_ptr right
2038 // away. Ideally, SetLocalDescription's signature will be changed to take the
2039 // description as a unique_ptr argument to formalize this agreement.
2040 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2041
nisse7ce109a2017-01-31 00:57:56 -08002042 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002043 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 return;
2045 }
Steve Anton8a006912017-12-04 15:25:56 -08002046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002048 PostSetSessionDescriptionFailure(
2049 observer,
2050 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002051 return;
2052 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002053
Steve Anton80dd7b52018-02-16 17:08:42 -08002054 // If a session error has occurred the PeerConnection is in a possibly
2055 // inconsistent state so fail right away.
2056 if (session_error() != SessionError::kNone) {
2057 std::string error_message = GetSessionErrorMsg();
2058 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002059 PostSetSessionDescriptionFailure(
2060 observer,
2061 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002062 return;
2063 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002064
Steve Anton80dd7b52018-02-16 17:08:42 -08002065 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2066 if (!error.ok()) {
2067 std::string error_message = GetSetDescriptionErrorMessage(
2068 cricket::CS_LOCAL, desc->GetType(), error);
2069 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002070 PostSetSessionDescriptionFailure(
2071 observer,
2072 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002073 return;
2074 }
2075
2076 // Grab the description type before moving ownership to ApplyLocalDescription,
2077 // which may destroy it before returning.
2078 const SdpType type = desc->GetType();
2079
2080 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002081 // |desc| may be destroyed at this point.
2082
2083 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002084 // If ApplyLocalDescription fails, the PeerConnection could be in an
2085 // inconsistent state, so act conservatively here and set the session error
2086 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2087 SetSessionError(SessionError::kContent, error.message());
2088 std::string error_message =
2089 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2090 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002091 PostSetSessionDescriptionFailure(
2092 observer,
2093 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002094 return;
2095 }
Steve Anton8a006912017-12-04 15:25:56 -08002096 RTC_DCHECK(local_description());
2097
2098 PostSetSessionDescriptionSuccess(observer);
2099
Steve Antonad182762018-09-05 20:22:40 +00002100 // MaybeStartGathering needs to be called after posting
2101 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2102 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002103 transport_controller_->MaybeStartGathering();
2104
Steve Antona3a92c22017-12-07 10:27:41 -08002105 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002106 // TODO(deadbeef): We already had to hop to the network thread for
2107 // MaybeStartGathering...
2108 network_thread()->Invoke<void>(
2109 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2110 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002111 // Make UMA notes about what was agreed to.
2112 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002113 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002114 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002115}
2116
2117RTCError PeerConnection::ApplyLocalDescription(
2118 std::unique_ptr<SessionDescriptionInterface> desc) {
2119 RTC_DCHECK_RUN_ON(signaling_thread());
2120 RTC_DCHECK(desc);
2121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 // Update stats here so that we have the most recent stats for tracks and
2123 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002124 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002125
Steve Antondcc3c022017-12-22 16:02:54 -08002126 // Take a reference to the old local description since it's used below to
2127 // compare against the new local description. When setting the new local
2128 // description, grab ownership of the replaced session description in case it
2129 // is the same as |old_local_description|, to keep it alive for the duration
2130 // of the method.
2131 const SessionDescriptionInterface* old_local_description =
2132 local_description();
2133 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002134 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002135 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002136 replaced_local_description = pending_local_description_
2137 ? std::move(pending_local_description_)
2138 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002139 current_local_description_ = std::move(desc);
2140 pending_local_description_ = nullptr;
2141 current_remote_description_ = std::move(pending_remote_description_);
2142 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002143 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002144 pending_local_description_ = std::move(desc);
2145 }
2146 // The session description to apply now must be accessed by
2147 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002148 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002149
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002150 if (!is_caller_) {
2151 if (remote_description()) {
2152 // Remote description was applied first, so this PC is the callee.
2153 is_caller_ = false;
2154 } else {
2155 // Local description is applied first, so this PC is the caller.
2156 is_caller_ = true;
2157 }
2158 }
2159
Zhi Huange830e682018-03-30 10:48:35 -07002160 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2161 if (!error.ok()) {
2162 return error;
2163 }
2164
Steve Antondcc3c022017-12-22 16:02:54 -08002165 if (IsUnifiedPlan()) {
2166 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002167 cricket::CS_LOCAL, *local_description(), old_local_description,
2168 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002169 if (!error.ok()) {
2170 return error;
2171 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002172 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2173 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002174 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002175 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2176 // Note that code paths that don't set MID won't be able to use
2177 // information about DTLS transports.
2178 if (transceiver->mid()) {
2179 auto dtls_transport =
2180 LookupDtlsTransportByMidInternal(*transceiver->mid());
2181 transceiver->internal()->sender_internal()->set_transport(
2182 dtls_transport);
2183 transceiver->internal()->receiver_internal()->set_transport(
2184 dtls_transport);
2185 }
2186
Steve Antondcc3c022017-12-22 16:02:54 -08002187 const ContentInfo* content =
2188 FindMediaSectionForTransceiver(transceiver, local_description());
2189 if (!content) {
2190 continue;
2191 }
2192 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002193 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2194 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002195 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002196 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2197 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2198 // "recvonly", process the removal of a remote track for the media
2199 // description, given transceiver, removeList, and muteTracks.
2200 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2201 (transceiver->internal()->fired_direction() &&
2202 RtpTransceiverDirectionHasRecv(
2203 *transceiver->internal()->fired_direction()))) {
2204 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2205 &removed_streams);
2206 }
2207 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2208 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002209 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002210 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002211 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002212 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002213 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002214 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002215 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002216 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002217 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002218 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002219 }
2220 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002221 // Media channels will be created only when offer is set. These may use new
2222 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002223 if (type == SdpType::kOffer) {
2224 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2225 // description is applied. Restore back to old description.
2226 RTCError error = CreateChannels(*local_description()->description());
2227 if (!error.ok()) {
2228 return error;
2229 }
2230 }
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Remove unused channels if MediaContentDescription is rejected.
2232 RemoveUnusedChannels(local_description()->description());
2233 }
Steve Anton8a006912017-12-04 15:25:56 -08002234
Zhi Huange830e682018-03-30 10:48:35 -07002235 error = UpdateSessionState(type, cricket::CS_LOCAL,
2236 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002237 if (!error.ok()) {
2238 return error;
2239 }
Steve Antondcc3c022017-12-22 16:02:54 -08002240
Steve Anton8a006912017-12-04 15:25:56 -08002241 if (remote_description()) {
2242 // Now that we have a local description, we can push down remote candidates.
2243 UseCandidatesInSessionDescription(remote_description());
2244 }
2245
2246 pending_ice_restarts_.clear();
2247 if (session_error() != SessionError::kNone) {
2248 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2249 }
2250
deadbeefab9b2d12015-10-14 11:33:11 -07002251 // If setting the description decided our SSL role, allocate any necessary
2252 // SCTP sids.
2253 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002254 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002255 AllocateSctpSids(role);
2256 }
2257
Steve Antond3679212018-01-17 17:41:02 -08002258 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002259 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002260 const ContentInfo* content =
2261 FindMediaSectionForTransceiver(transceiver, local_description());
2262 if (!content) {
2263 continue;
2264 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002265 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2266 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002267 // 0 is a special value meaning "this sender has no associated send
2268 // stream". Need to call this so the sender won't attempt to configure
2269 // a no longer existing stream and run into DCHECKs in the lower
2270 // layers.
2271 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002272 } else {
2273 // Get the StreamParams from the channel which could generate SSRCs.
2274 const std::vector<StreamParams>& streams = channel->local_streams();
2275 transceiver->internal()->sender_internal()->set_stream_ids(
2276 streams[0].stream_ids());
2277 transceiver->internal()->sender_internal()->SetSsrc(
2278 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002279 }
2280 }
2281 } else {
2282 // Plan B semantics.
2283
Steve Antondcc3c022017-12-22 16:02:54 -08002284 // Update state and SSRC of local MediaStreams and DataChannels based on the
2285 // local session description.
2286 const cricket::ContentInfo* audio_content =
2287 GetFirstAudioContent(local_description()->description());
2288 if (audio_content) {
2289 if (audio_content->rejected) {
2290 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2291 } else {
2292 const cricket::AudioContentDescription* audio_desc =
2293 audio_content->media_description()->as_audio();
2294 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2295 }
deadbeeffaac4972015-11-12 15:33:07 -08002296 }
deadbeefab9b2d12015-10-14 11:33:11 -07002297
Steve Antondcc3c022017-12-22 16:02:54 -08002298 const cricket::ContentInfo* video_content =
2299 GetFirstVideoContent(local_description()->description());
2300 if (video_content) {
2301 if (video_content->rejected) {
2302 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2303 } else {
2304 const cricket::VideoContentDescription* video_desc =
2305 video_content->media_description()->as_video();
2306 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2307 }
deadbeeffaac4972015-11-12 15:33:07 -08002308 }
deadbeefab9b2d12015-10-14 11:33:11 -07002309 }
2310
2311 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002312 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002313 if (data_content) {
2314 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002315 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002316 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002317 cricket::kMediaProtocolRtpPrefix)) {
2318 UpdateLocalRtpDataChannels(data_desc->streams());
2319 }
2320 }
2321
Steve Anton8a006912017-12-04 15:25:56 -08002322 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323}
2324
Steve Anton06817cd2018-12-18 15:55:30 -08002325// The SDP parser used to populate these values by default for the 'content
2326// name' if an a=mid line was absent.
2327static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2328 switch (media_type) {
2329 case cricket::MEDIA_TYPE_AUDIO:
2330 return cricket::CN_AUDIO;
2331 case cricket::MEDIA_TYPE_VIDEO:
2332 return cricket::CN_VIDEO;
2333 case cricket::MEDIA_TYPE_DATA:
2334 return cricket::CN_DATA;
2335 }
2336 RTC_NOTREACHED();
2337 return "";
2338}
2339
2340void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002341 cricket::SessionDescription* new_remote_description) {
2342 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002343 const cricket::ContentInfos& local_contents =
2344 (local_description() ? local_description()->description()->contents()
2345 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002346 const cricket::ContentInfos& remote_contents =
2347 (remote_description() ? remote_description()->description()->contents()
2348 : cricket::ContentInfos());
2349 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2350 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002351 if (!content.name.empty()) {
2352 continue;
2353 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002354 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002355 absl::string_view source_explanation;
2356 if (IsUnifiedPlan()) {
2357 if (i < local_contents.size()) {
2358 new_mid = local_contents[i].name;
2359 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002360 } else if (i < remote_contents.size()) {
2361 new_mid = remote_contents[i].name;
2362 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002363 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002364 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002365 source_explanation = "generated just now";
2366 }
2367 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002368 new_mid = std::string(
2369 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002370 source_explanation = "to match pre-existing behavior";
2371 }
Steve Antond7180cc2019-02-07 10:44:53 -08002372 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002373 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002374 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002375 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2376 << " is missing an a=mid line. Filling in the value '"
2377 << new_mid << "' " << source_explanation << ".";
2378 }
2379}
2380
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002382 SetSessionDescriptionObserver* observer,
2383 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002384 SetRemoteDescription(
2385 std::unique_ptr<SessionDescriptionInterface>(desc),
2386 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2387 new SetRemoteDescriptionObserverAdapter(this, observer)));
2388}
2389
2390void PeerConnection::SetRemoteDescription(
2391 std::unique_ptr<SessionDescriptionInterface> desc,
2392 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002393 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002394 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002395
nisse7ce109a2017-01-31 00:57:56 -08002396 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002397 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 return;
2399 }
Steve Anton8a006912017-12-04 15:25:56 -08002400
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002402 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002403 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 return;
2405 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002406
Steve Anton80dd7b52018-02-16 17:08:42 -08002407 // If a session error has occurred the PeerConnection is in a possibly
2408 // inconsistent state so fail right away.
2409 if (session_error() != SessionError::kNone) {
2410 std::string error_message = GetSessionErrorMsg();
2411 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2412 observer->OnSetRemoteDescriptionComplete(
2413 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2414 return;
2415 }
Steve Anton71439a62018-02-15 11:53:06 -08002416
Steve Antonba42e992018-04-09 14:10:01 -07002417 if (desc->GetType() == SdpType::kOffer) {
2418 // Report to UMA the format of the received offer.
2419 ReportSdpFormatReceived(*desc);
2420 }
2421
Steve Anton06817cd2018-12-18 15:55:30 -08002422 // Handle remote descriptions missing a=mid lines for interop with legacy end
2423 // points.
2424 FillInMissingRemoteMids(desc->description());
2425
Steve Anton80dd7b52018-02-16 17:08:42 -08002426 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002427 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002428 std::string error_message = GetSetDescriptionErrorMessage(
2429 cricket::CS_REMOTE, desc->GetType(), error);
2430 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002431 observer->OnSetRemoteDescriptionComplete(
2432 RTCError(error.type(), std::move(error_message)));
2433 return;
2434 }
Steve Anton71439a62018-02-15 11:53:06 -08002435
Steve Anton80dd7b52018-02-16 17:08:42 -08002436 // Grab the description type before moving ownership to
2437 // ApplyRemoteDescription, which may destroy it before returning.
2438 const SdpType type = desc->GetType();
2439
2440 error = ApplyRemoteDescription(std::move(desc));
2441 // |desc| may be destroyed at this point.
2442
2443 if (!error.ok()) {
2444 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2445 // inconsistent state, so act conservatively here and set the session error
2446 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2447 SetSessionError(SessionError::kContent, error.message());
2448 std::string error_message =
2449 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2450 RTC_LOG(LS_ERROR) << error_message;
2451 observer->OnSetRemoteDescriptionComplete(
2452 RTCError(error.type(), std::move(error_message)));
2453 return;
2454 }
2455 RTC_DCHECK(remote_description());
2456
2457 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002458 // TODO(deadbeef): We already had to hop to the network thread for
2459 // MaybeStartGathering...
2460 network_thread()->Invoke<void>(
2461 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2462 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002463 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002464 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002465 }
2466
2467 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002468 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002469}
2470
2471RTCError PeerConnection::ApplyRemoteDescription(
2472 std::unique_ptr<SessionDescriptionInterface> desc) {
2473 RTC_DCHECK_RUN_ON(signaling_thread());
2474 RTC_DCHECK(desc);
2475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002476 // Update stats here so that we have the most recent stats for tracks and
2477 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002478 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002479
Steve Antondcc3c022017-12-22 16:02:54 -08002480 // Take a reference to the old remote description since it's used below to
2481 // compare against the new remote description. When setting the new remote
2482 // description, grab ownership of the replaced session description in case it
2483 // is the same as |old_remote_description|, to keep it alive for the duration
2484 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002485 const SessionDescriptionInterface* old_remote_description =
2486 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002487 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002488 SdpType type = desc->GetType();
2489 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002490 replaced_remote_description = pending_remote_description_
2491 ? std::move(pending_remote_description_)
2492 : std::move(current_remote_description_);
2493 current_remote_description_ = std::move(desc);
2494 pending_remote_description_ = nullptr;
2495 current_local_description_ = std::move(pending_local_description_);
2496 } else {
2497 replaced_remote_description = std::move(pending_remote_description_);
2498 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 }
Steve Anton8a006912017-12-04 15:25:56 -08002500 // The session description to apply now must be accessed by
2501 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002502 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503
Zhi Huange830e682018-03-30 10:48:35 -07002504 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2505 if (!error.ok()) {
2506 return error;
2507 }
Steve Anton8a006912017-12-04 15:25:56 -08002508 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002509 if (IsUnifiedPlan()) {
2510 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002511 cricket::CS_REMOTE, *remote_description(), local_description(),
2512 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002513 if (!error.ok()) {
2514 return error;
2515 }
Steve Antondcc3c022017-12-22 16:02:54 -08002516 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002517 // Media channels will be created only when offer is set. These may use new
2518 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002519 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002520 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002521 // description is applied. Restore back to old description.
2522 RTCError error = CreateChannels(*remote_description()->description());
2523 if (!error.ok()) {
2524 return error;
2525 }
2526 }
Steve Antondcc3c022017-12-22 16:02:54 -08002527 // Remove unused channels if MediaContentDescription is rejected.
2528 RemoveUnusedChannels(remote_description()->description());
2529 }
Steve Anton8a006912017-12-04 15:25:56 -08002530
Zhi Huange830e682018-03-30 10:48:35 -07002531 // NOTE: Candidates allocation will be initiated only when
2532 // SetLocalDescription is called.
2533 error = UpdateSessionState(type, cricket::CS_REMOTE,
2534 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002535 if (!error.ok()) {
2536 return error;
2537 }
2538
2539 if (local_description() &&
2540 !UseCandidatesInSessionDescription(remote_description())) {
2541 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2542 }
2543
2544 if (old_remote_description) {
2545 for (const cricket::ContentInfo& content :
2546 old_remote_description->description()->contents()) {
2547 // Check if this new SessionDescription contains new ICE ufrag and
2548 // password that indicates the remote peer requests an ICE restart.
2549 // TODO(deadbeef): When we start storing both the current and pending
2550 // remote description, this should reset pending_ice_restarts and compare
2551 // against the current description.
2552 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2553 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002554 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002555 pending_ice_restarts_.insert(content.name);
2556 }
2557 } else {
2558 // We retain all received candidates only if ICE is not restarted.
2559 // When ICE is restarted, all previous candidates belong to an old
2560 // generation and should not be kept.
2561 // TODO(deadbeef): This goes against the W3C spec which says the remote
2562 // description should only contain candidates from the last set remote
2563 // description plus any candidates added since then. We should remove
2564 // this once we're sure it won't break anything.
2565 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2566 old_remote_description, content.name, mutable_remote_description());
2567 }
2568 }
2569 }
2570
2571 if (session_error() != SessionError::kNone) {
2572 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2573 }
2574
2575 // Set the the ICE connection state to connecting since the connection may
2576 // become writable with peer reflexive candidates before any remote candidate
2577 // is signaled.
2578 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2579 // is to have a new signal the indicates a change in checking state from the
2580 // transport and expose a new checking() member from transport that can be
2581 // read to determine the current checking state. The existing SignalConnecting
2582 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002583 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002584 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002585 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2586 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2587 }
2588
deadbeefab9b2d12015-10-14 11:33:11 -07002589 // If setting the description decided our SSL role, allocate any necessary
2590 // SCTP sids.
2591 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002592 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002593 AllocateSctpSids(role);
2594 }
2595
Steve Antondcc3c022017-12-22 16:02:54 -08002596 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002597 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002598 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002599 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002600 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002601 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002602 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002603 const ContentInfo* content =
2604 FindMediaSectionForTransceiver(transceiver, remote_description());
2605 if (!content) {
2606 continue;
2607 }
2608 const MediaContentDescription* media_desc = content->media_description();
2609 RtpTransceiverDirection local_direction =
2610 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002611 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2612 // RTCSessionDescription: Set the associated remote streams given
2613 // transceiver.[[Receiver]], msids, addList, and removeList".
2614 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2615 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2616 std::vector<std::string> stream_ids;
2617 if (!media_desc->streams().empty()) {
2618 // The remote description has signaled the stream IDs.
2619 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002620 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002621 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2622 << " (" << GetStreamIdsString(stream_ids) << ").";
2623 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2624 stream_ids, &added_streams,
2625 &removed_streams);
2626 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2627 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2628 // and transceiver's current direction is neither sendrecv nor recvonly,
2629 // process the addition of a remote track for the media description.
2630 if (!transceiver->fired_direction() ||
2631 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2632 RTC_LOG(LS_INFO)
2633 << "Processing the addition of a remote track for MID="
2634 << content->name << ".";
2635 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002636 }
Steve Antondcc3c022017-12-22 16:02:54 -08002637 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002638 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002639 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2640 // removal of a remote track for the media description, given transceiver,
2641 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002642 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002643 (transceiver->fired_direction() &&
2644 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2645 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2646 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002647 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002648 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002649 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002650 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002651 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002652 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002653 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002654 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002655 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002656 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2657 if (transceiver->mid()) {
2658 auto dtls_transport =
2659 LookupDtlsTransportByMidInternal(*transceiver->mid());
2660 transceiver->internal()->sender_internal()->set_transport(
2661 dtls_transport);
2662 transceiver->internal()->receiver_internal()->set_transport(
2663 dtls_transport);
2664 }
Steve Antondcc3c022017-12-22 16:02:54 -08002665 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002666 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002667 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002668 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002669 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2670 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002671 transceiver->Stop();
2672 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002673 if (!content->rejected &&
2674 RtpTransceiverDirectionHasRecv(local_direction)) {
2675 // Set ssrc to 0 in the case of an unsignalled ssrc.
2676 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002677 if (!media_desc->streams().empty() &&
2678 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002679 ssrc = media_desc->streams()[0].first_ssrc();
2680 }
2681 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002682 }
Steve Antondcc3c022017-12-22 16:02:54 -08002683 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002684 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002685 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002686 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002687 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002688 observer->OnTrack(transceiver);
2689 observer->OnAddTrack(transceiver->receiver(),
2690 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002691 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002692 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002693 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002694 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002695 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002696 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002697 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002698 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002699 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002700 }
Steve Antondcc3c022017-12-22 16:02:54 -08002701 }
2702
Henrik Boströmfdb92012017-11-09 19:55:44 +01002703 const cricket::ContentInfo* audio_content =
2704 GetFirstAudioContent(remote_description()->description());
2705 const cricket::ContentInfo* video_content =
2706 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002707 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002708 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002709 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002710 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002711 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002712 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002713
2714 // Check if the descriptions include streams, just in case the peer supports
2715 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002716 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002717 (audio_desc && !audio_desc->streams().empty()) ||
2718 (video_desc && !video_desc->streams().empty())) {
2719 remote_peer_supports_msid_ = true;
2720 }
deadbeefab9b2d12015-10-14 11:33:11 -07002721
2722 // We wait to signal new streams until we finish processing the description,
2723 // since only at that point will new streams have all their tracks.
2724 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2725
Steve Antondcc3c022017-12-22 16:02:54 -08002726 if (!IsUnifiedPlan()) {
2727 // TODO(steveanton): When removing RTP senders/receivers in response to a
2728 // rejected media section, there is some cleanup logic that expects the
2729 // voice/ video channel to still be set. But in this method the voice/video
2730 // channel would have been destroyed by the SetRemoteDescription caller
2731 // above so the cleanup that relies on them fails to run. The RemoveSenders
2732 // calls should be moved to right before the DestroyChannel calls to fix
2733 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002734
Steve Antondcc3c022017-12-22 16:02:54 -08002735 // Find all audio rtp streams and create corresponding remote AudioTracks
2736 // and MediaStreams.
2737 if (audio_content) {
2738 if (audio_content->rejected) {
2739 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2740 } else {
2741 bool default_audio_track_needed =
2742 !remote_peer_supports_msid_ &&
2743 RtpTransceiverDirectionHasSend(audio_desc->direction());
2744 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2745 default_audio_track_needed, audio_desc->type(),
2746 new_streams);
2747 }
deadbeeffaac4972015-11-12 15:33:07 -08002748 }
deadbeefab9b2d12015-10-14 11:33:11 -07002749
Steve Antondcc3c022017-12-22 16:02:54 -08002750 // Find all video rtp streams and create corresponding remote VideoTracks
2751 // and MediaStreams.
2752 if (video_content) {
2753 if (video_content->rejected) {
2754 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2755 } else {
2756 bool default_video_track_needed =
2757 !remote_peer_supports_msid_ &&
2758 RtpTransceiverDirectionHasSend(video_desc->direction());
2759 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2760 default_video_track_needed, video_desc->type(),
2761 new_streams);
2762 }
deadbeeffaac4972015-11-12 15:33:07 -08002763 }
deadbeefab9b2d12015-10-14 11:33:11 -07002764
Steve Antondcc3c022017-12-22 16:02:54 -08002765 // Update the DataChannels with the information from the remote peer.
2766 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002767 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002768 cricket::kMediaProtocolRtpPrefix)) {
2769 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2770 }
deadbeefab9b2d12015-10-14 11:33:11 -07002771 }
deadbeefab9b2d12015-10-14 11:33:11 -07002772
Steve Antondcc3c022017-12-22 16:02:54 -08002773 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002774 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002775 for (size_t i = 0; i < new_streams->count(); ++i) {
2776 MediaStreamInterface* new_stream = new_streams->at(i);
2777 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002778 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002779 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2780 }
deadbeefab9b2d12015-10-14 11:33:11 -07002781
Steve Antondcc3c022017-12-22 16:02:54 -08002782 UpdateEndedRemoteMediaStreams();
2783 }
deadbeefab9b2d12015-10-14 11:33:11 -07002784
Steve Anton8a006912017-12-04 15:25:56 -08002785 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002786}
2787
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002788void PeerConnection::SetAssociatedRemoteStreams(
2789 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2790 const std::vector<std::string>& stream_ids,
2791 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2792 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2793 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2794 for (const std::string& stream_id : stream_ids) {
2795 rtc::scoped_refptr<MediaStreamInterface> stream =
2796 remote_streams_->find(stream_id);
2797 if (!stream) {
2798 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2799 MediaStream::Create(stream_id));
2800 remote_streams_->AddStream(stream);
2801 added_streams->push_back(stream);
2802 }
2803 media_streams.push_back(stream);
2804 }
2805 // Special case: "a=msid" missing, use random stream ID.
2806 if (media_streams.empty() &&
2807 !(remote_description()->description()->msid_signaling() &
2808 cricket::kMsidSignalingMediaSection)) {
2809 if (!missing_msid_default_stream_) {
2810 missing_msid_default_stream_ = MediaStreamProxy::Create(
2811 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2812 added_streams->push_back(missing_msid_default_stream_);
2813 }
2814 media_streams.push_back(missing_msid_default_stream_);
2815 }
2816 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2817 receiver->streams();
2818 // SetStreams() will add/remove the receiver's track to/from the streams. This
2819 // differs from the spec - the spec uses an "addList" and "removeList" to
2820 // update the stream-track relationships in a later step. We do this earlier,
2821 // changing the order of things, but the end-result is the same.
2822 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2823 // instead. https://crbug.com/webrtc/9480
2824 receiver->SetStreams(media_streams);
2825 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2826}
2827
Steve Anton0f5400a2018-07-17 14:25:36 -07002828void PeerConnection::ProcessRemovalOfRemoteTrack(
2829 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2830 transceiver,
2831 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2832 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2833 RTC_DCHECK(transceiver->mid());
2834 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2835 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002836 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002837 transceiver->internal()->receiver_internal()->streams();
2838 // This will remove the remote track from the streams.
2839 transceiver->internal()->receiver_internal()->set_stream_ids({});
2840 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002841 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2842}
2843
2844void PeerConnection::RemoveRemoteStreamsIfEmpty(
2845 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2846 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2847 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2848 // streams, see if the stream was removed by checking if this was the last
2849 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002850 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002851 if (remote_stream->GetAudioTracks().empty() &&
2852 remote_stream->GetVideoTracks().empty()) {
2853 remote_streams_->RemoveStream(remote_stream);
2854 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002855 }
2856 }
2857}
2858
Steve Antondcc3c022017-12-22 16:02:54 -08002859RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2860 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002861 const SessionDescriptionInterface& new_session,
2862 const SessionDescriptionInterface* old_local_description,
2863 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002864 RTC_DCHECK(IsUnifiedPlan());
2865
Steve Anton7464fca2018-01-19 11:10:37 -08002866 const cricket::ContentGroup* bundle_group = nullptr;
2867 if (new_session.GetType() == SdpType::kOffer) {
2868 auto bundle_group_or_error =
2869 GetEarlyBundleGroup(*new_session.description());
2870 if (!bundle_group_or_error.ok()) {
2871 return bundle_group_or_error.MoveError();
2872 }
2873 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002874 }
Steve Antondcc3c022017-12-22 16:02:54 -08002875
Steve Antondcc3c022017-12-22 16:02:54 -08002876 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002877 for (size_t i = 0; i < new_contents.size(); ++i) {
2878 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002879 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002880 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002881 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2882 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002883 const cricket::ContentInfo* old_local_content = nullptr;
2884 if (old_local_description &&
2885 i < old_local_description->description()->contents().size()) {
2886 old_local_content =
2887 &old_local_description->description()->contents()[i];
2888 }
2889 const cricket::ContentInfo* old_remote_content = nullptr;
2890 if (old_remote_description &&
2891 i < old_remote_description->description()->contents().size()) {
2892 old_remote_content =
2893 &old_remote_description->description()->contents()[i];
2894 }
Steve Antondcc3c022017-12-22 16:02:54 -08002895 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002896 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2897 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002898 if (!transceiver_or_error.ok()) {
2899 return transceiver_or_error.MoveError();
2900 }
2901 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002902 RTCError error =
2903 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2904 if (!error.ok()) {
2905 return error;
2906 }
2907 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002908 if (GetDataMid() && new_content.name != *GetDataMid()) {
2909 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002910 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2911 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002912 continue;
2913 }
2914 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2915 if (!error.ok()) {
2916 return error;
2917 }
Steve Antondcc3c022017-12-22 16:02:54 -08002918 } else {
2919 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2920 "Unknown section type.");
2921 }
2922 }
2923
2924 return RTCError::OK();
2925}
2926
2927RTCError PeerConnection::UpdateTransceiverChannel(
2928 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2929 transceiver,
2930 const cricket::ContentInfo& content,
2931 const cricket::ContentGroup* bundle_group) {
2932 RTC_DCHECK(IsUnifiedPlan());
2933 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002934 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002935 if (content.rejected) {
2936 if (channel) {
2937 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002938 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002939 }
2940 } else {
2941 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002942 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002943 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002944 } else {
Steve Anton69470252018-02-09 11:43:08 -08002945 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002946 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002947 }
2948 if (!channel) {
2949 LOG_AND_RETURN_ERROR(
2950 RTCErrorType::INTERNAL_ERROR,
2951 "Failed to create channel for mid=" + content.name);
2952 }
2953 transceiver->internal()->SetChannel(channel);
2954 }
2955 }
2956 return RTCError::OK();
2957}
2958
Steve Antonfa2260d2017-12-28 16:38:23 -08002959RTCError PeerConnection::UpdateDataChannel(
2960 cricket::ContentSource source,
2961 const cricket::ContentInfo& content,
2962 const cricket::ContentGroup* bundle_group) {
2963 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002964 // If data channels are disabled, ignore this media section. CreateAnswer
2965 // will take care of rejecting it.
2966 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002967 }
2968 if (content.rejected) {
2969 DestroyDataChannel();
2970 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002971 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002972 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002973 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2974 "Failed to create data channel.");
2975 }
2976 }
2977 if (source == cricket::CS_REMOTE) {
2978 const MediaContentDescription* data_desc = content.media_description();
2979 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2980 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2981 }
2982 }
2983 }
2984 return RTCError::OK();
2985}
2986
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002987// This method will extract any send encodings that were sent by the remote
2988// connection. This is currently only relevant for Simulcast scenario (where
2989// the number of layers may be communicated by the server).
2990static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2991 const MediaContentDescription& desc) {
2992 if (!desc.HasSimulcast()) {
2993 return {};
2994 }
2995 std::vector<RtpEncodingParameters> result;
2996 const SimulcastDescription& simulcast = desc.simulcast_description();
2997
2998 // This is a remote description, the parameters we are after should appear
2999 // as receive streams.
3000 for (const auto& alternatives : simulcast.receive_layers()) {
3001 RTC_DCHECK(!alternatives.empty());
3002 // There is currently no way to specify or choose from alternatives.
3003 // We will always use the first alternative, which is the most preferred.
3004 const SimulcastLayer& layer = alternatives[0];
3005 RtpEncodingParameters parameters;
3006 parameters.rid = layer.rid;
3007 parameters.active = !layer.is_paused;
3008 result.push_back(parameters);
3009 }
3010
3011 return result;
3012}
3013
3014static RTCError UpdateSimulcastLayerStatusInSender(
3015 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003016 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003017 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003018 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003019 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003020
3021 // The simulcast envelope cannot be changed, only the status of the streams.
3022 // So we will iterate over the send encodings rather than the layers.
3023 for (RtpEncodingParameters& encoding : parameters.encodings) {
3024 auto iter = std::find_if(layers.begin(), layers.end(),
3025 [&encoding](const SimulcastLayer& layer) {
3026 return layer.rid == encoding.rid;
3027 });
3028 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003029 if (iter == layers.end()) {
3030 disabled_layers.push_back(encoding.rid);
3031 continue;
3032 }
3033
3034 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003035 }
3036
Amit Hilbuch619b2942019-02-26 15:55:19 -08003037 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003038 if (result.ok()) {
3039 result = sender->DisableEncodingLayers(disabled_layers);
3040 }
3041
3042 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003043}
3044
Amit Hilbuch2297d332019-02-19 12:49:22 -08003045static RTCError DisableSimulcastInSender(
3046 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003047 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003048 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003049 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003050 return RTCError::OK();
3051 }
3052
Amit Hilbuch2297d332019-02-19 12:49:22 -08003053 std::vector<std::string> disabled_layers;
3054 std::transform(
3055 parameters.encodings.begin() + 1, parameters.encodings.end(),
3056 std::back_inserter(disabled_layers),
3057 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3058 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003059}
3060
Steve Antondcc3c022017-12-22 16:02:54 -08003061RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3062PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003063 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003064 size_t mline_index,
3065 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003066 const ContentInfo* old_local_content,
3067 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003068 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003069 // If this is an offer then the m= section might be recycled. If the m=
3070 // section is being recycled (defined as: rejected in the current local or
3071 // remote description and not rejected in new description), dissociate the
3072 // currently associated RtpTransceiver by setting its mid property to null,
3073 // and discard the mapping between the transceiver and its m= section index.
3074 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3075 old_remote_content)) {
3076 // We want to dissociate the transceiver that has the rejected mid.
3077 const std::string& old_mid =
3078 (old_local_content && old_local_content->rejected)
3079 ? old_local_content->name
3080 : old_remote_content->name;
3081 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003082 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003083 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3084 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003085 old_transceiver->internal()->set_mid(absl::nullopt);
3086 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003087 }
3088 }
3089 const MediaContentDescription* media_desc = content.media_description();
3090 auto transceiver = GetAssociatedTransceiver(content.name);
3091 if (source == cricket::CS_LOCAL) {
3092 // Find the RtpTransceiver that corresponds to this m= section, using the
3093 // mapping between transceivers and m= section indices established when
3094 // creating the offer.
3095 if (!transceiver) {
3096 transceiver = GetTransceiverByMLineIndex(mline_index);
3097 }
3098 if (!transceiver) {
3099 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3100 "Unknown transceiver");
3101 }
3102 } else {
3103 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3104 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3105 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003106 // When simulcast is requested, a transceiver cannot be associated because
3107 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003108 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003109 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3110 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003111 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3112 }
3113 // If no RtpTransceiver was found in the previous step, create one with a
3114 // recvonly direction.
3115 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003116 RTC_LOG(LS_INFO) << "Adding "
3117 << cricket::MediaTypeToString(media_desc->type())
3118 << " transceiver for MID=" << content.name
3119 << " at i=" << mline_index
3120 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003121 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003122 std::vector<RtpEncodingParameters> send_encodings =
3123 GetSendEncodingsFromRemoteDescription(*media_desc);
3124 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3125 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003126 std::string receiver_id;
3127 if (!media_desc->streams().empty()) {
3128 receiver_id = media_desc->streams()[0].id;
3129 } else {
3130 receiver_id = rtc::CreateRandomUuid();
3131 }
3132 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003133 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003134 transceiver->internal()->set_direction(
3135 RtpTransceiverDirection::kRecvOnly);
3136 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003137
3138 // Check if the offer indicated simulcast but the answer rejected it.
3139 // This can happen when simulcast is not supported on the remote party.
3140 // This check can be simplified to comparing the number of send encodings,
3141 // but that might break legacy implementation in which simulcast is not
3142 // signaled in the remote description.
3143 if (old_local_content && old_local_content->media_description() &&
3144 old_local_content->media_description()->HasSimulcast() &&
3145 !media_desc->HasSimulcast()) {
3146 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003147 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003148 if (!error.ok()) {
3149 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3150 return std::move(error);
3151 }
3152 }
Steve Antondcc3c022017-12-22 16:02:54 -08003153 }
3154 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003155 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003156 LOG_AND_RETURN_ERROR(
3157 RTCErrorType::INVALID_PARAMETER,
3158 "Transceiver type does not match media description type.");
3159 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003160 if (media_desc->HasSimulcast()) {
3161 std::vector<SimulcastLayer> layers =
3162 source == cricket::CS_LOCAL
3163 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3164 : media_desc->simulcast_description()
3165 .receive_layers()
3166 .GetAllLayers();
3167 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003168 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003169 if (!error.ok()) {
3170 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3171 return std::move(error);
3172 }
3173 }
Steve Antondcc3c022017-12-22 16:02:54 -08003174 // Associate the found or created RtpTransceiver with the m= section by
3175 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3176 // section, and establish a mapping between the transceiver and the index of
3177 // the m= section.
3178 transceiver->internal()->set_mid(content.name);
3179 transceiver->internal()->set_mline_index(mline_index);
3180 return std::move(transceiver);
3181}
3182
3183rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3184PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3185 RTC_DCHECK(IsUnifiedPlan());
3186 for (auto transceiver : transceivers_) {
3187 if (transceiver->mid() == mid) {
3188 return transceiver;
3189 }
3190 }
3191 return nullptr;
3192}
3193
3194rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3195PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3196 RTC_DCHECK(IsUnifiedPlan());
3197 for (auto transceiver : transceivers_) {
3198 if (transceiver->internal()->mline_index() == mline_index) {
3199 return transceiver;
3200 }
3201 }
3202 return nullptr;
3203}
3204
3205rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3206PeerConnection::FindAvailableTransceiverToReceive(
3207 cricket::MediaType media_type) const {
3208 RTC_DCHECK(IsUnifiedPlan());
3209 // From JSEP section 5.10 (Applying a Remote Description):
3210 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3211 // the same type that were added to the PeerConnection by addTrack and are not
3212 // associated with any m= section and are not stopped, find the first such
3213 // RtpTransceiver.
3214 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003215 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003216 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3217 !transceiver->stopped()) {
3218 return transceiver;
3219 }
3220 }
3221 return nullptr;
3222}
3223
Steve Antoned10bd92017-12-05 10:52:59 -08003224const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3225 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3226 transceiver,
3227 const SessionDescriptionInterface* sdesc) const {
3228 RTC_DCHECK(transceiver);
3229 RTC_DCHECK(sdesc);
3230 if (IsUnifiedPlan()) {
3231 if (!transceiver->internal()->mid()) {
3232 // This transceiver is not associated with a media section yet.
3233 return nullptr;
3234 }
3235 return sdesc->description()->GetContentByName(
3236 *transceiver->internal()->mid());
3237 } else {
3238 // Plan B only allows at most one audio and one video section, so use the
3239 // first media section of that type.
3240 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003241 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003242 }
3243}
3244
deadbeef46c73892016-11-16 19:42:04 -08003245PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003246 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003247 return configuration_;
3248}
3249
deadbeef293e9262017-01-11 12:28:30 -08003250bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3251 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003252 RTC_DCHECK_RUN_ON(signaling_thread());
3253 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003254 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003255 if (IsClosed()) {
3256 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3257 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3258 }
3259
Qingsi Wanga2d60672018-04-11 16:57:45 -07003260 // According to JSEP, after setLocalDescription, changing the candidate pool
3261 // size is not allowed, and changing the set of ICE servers will not result
3262 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003263 if (local_description() && configuration.ice_candidate_pool_size !=
3264 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003265 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3266 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003267 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003268 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003269
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003270 if (local_description() &&
3271 configuration.use_media_transport != configuration_.use_media_transport) {
3272 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3273 "SetLocalDescription.";
3274 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3275 }
3276
3277 if (remote_description() &&
3278 configuration.use_media_transport != configuration_.use_media_transport) {
3279 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3280 "SetRemoteDescription.";
3281 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3282 }
3283
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003284 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003285 configuration.use_media_transport_for_data_channels !=
3286 configuration_.use_media_transport_for_data_channels) {
3287 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3288 "after calling SetLocalDescription.";
3289 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3290 }
3291
3292 if (remote_description() &&
3293 configuration.use_media_transport_for_data_channels !=
3294 configuration_.use_media_transport_for_data_channels) {
3295 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3296 "after calling SetRemoteDescription.";
3297 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3298 }
3299
3300 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003301 configuration.crypto_options != configuration_.crypto_options) {
3302 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3303 "SetLocalDescription.";
3304 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3305 }
3306
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003307 if (configuration.use_media_transport_for_data_channels ||
3308 configuration.use_media_transport) {
3309 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3310 << "Media transport requires MaxBundle policy.";
3311 }
3312
deadbeef293e9262017-01-11 12:28:30 -08003313 // The simplest (and most future-compatible) way to tell if the config was
3314 // modified in an invalid way is to copy each property we do support
3315 // modifying, then use operator==. There are far more properties we don't
3316 // support modifying than those we do, and more could be added.
3317 RTCConfiguration modified_config = configuration_;
3318 modified_config.servers = configuration.servers;
3319 modified_config.type = configuration.type;
3320 modified_config.ice_candidate_pool_size =
3321 configuration.ice_candidate_pool_size;
3322 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003323 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003324 modified_config.ice_check_interval_strong_connectivity =
3325 configuration.ice_check_interval_strong_connectivity;
3326 modified_config.ice_check_interval_weak_connectivity =
3327 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003328 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3329 modified_config.ice_unwritable_min_checks =
3330 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003331 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003332 modified_config.stun_candidate_keepalive_interval =
3333 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003334 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003335 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003336 modified_config.active_reset_srtp_params =
3337 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003338 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003339 modified_config.use_media_transport_for_data_channels =
3340 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003341 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003342 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003343 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3344 }
3345
Steve Anton038834f2017-07-14 15:59:59 -07003346 // Validate the modified configuration.
3347 RTCError validate_error = ValidateConfiguration(modified_config);
3348 if (!validate_error.ok()) {
3349 return SafeSetError(std::move(validate_error), error);
3350 }
3351
deadbeef293e9262017-01-11 12:28:30 -08003352 // Note that this isn't possible through chromium, since it's an unsigned
3353 // short in WebIDL.
3354 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003355 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003356 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3357 }
3358
3359 // Parse ICE servers before hopping to network thread.
3360 cricket::ServerAddresses stun_servers;
3361 std::vector<cricket::RelayServerConfig> turn_servers;
3362 RTCErrorType parse_error =
3363 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3364 if (parse_error != RTCErrorType::NONE) {
3365 return SafeSetError(parse_error, error);
3366 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003367 // Note if STUN or TURN servers were supplied.
3368 if (!stun_servers.empty()) {
3369 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3370 }
3371 if (!turn_servers.empty()) {
3372 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3373 }
deadbeef293e9262017-01-11 12:28:30 -08003374
3375 // In theory this shouldn't fail.
3376 if (!network_thread()->Invoke<bool>(
3377 RTC_FROM_HERE,
3378 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3379 stun_servers, turn_servers, modified_config.type,
3380 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003381 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003382 modified_config.turn_customizer,
3383 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003384 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003385 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3386 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003387
deadbeefd1a38b52016-12-10 13:15:33 -08003388 // As described in JSEP, calling setConfiguration with new ICE servers or
3389 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3390 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003391 if (modified_config.servers != configuration_.servers ||
3392 modified_config.type != configuration_.type ||
3393 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003394 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003395 }
skvladd1f5fda2017-02-03 16:54:05 -08003396
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003397 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003398 transport_controller_->SetMediaTransportSettings(
3399 modified_config.use_media_transport,
3400 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003401
Zhi Huangb57e1692018-06-12 11:41:11 -07003402 if (configuration_.active_reset_srtp_params !=
3403 modified_config.active_reset_srtp_params) {
3404 transport_controller_->SetActiveResetSrtpParams(
3405 modified_config.active_reset_srtp_params);
3406 }
3407
deadbeef293e9262017-01-11 12:28:30 -08003408 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003409 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003410 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003411}
3412
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413bool PeerConnection::AddIceCandidate(
3414 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003415 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003416 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003417 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003418 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003419 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003420 return false;
3421 }
Steve Antond25da372017-11-06 14:50:29 -08003422
3423 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003424 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003425 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003426 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003427 return false;
3428 }
3429
3430 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003431 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003432 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003433 return false;
3434 }
3435
3436 bool valid = false;
3437 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3438 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003439 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003440 return false;
3441 }
3442
3443 // Add this candidate to the remote session description.
3444 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003445 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003446 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003447 return false;
3448 }
3449
3450 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003451 bool result = UseCandidate(ice_candidate);
3452 if (result) {
3453 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3454 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3455 } else {
3456 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3457 }
3458 return result;
Steve Antond25da372017-11-06 14:50:29 -08003459 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003460 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003461 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003462 return true;
3463 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003464}
3465
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003466bool PeerConnection::RemoveIceCandidates(
3467 const std::vector<cricket::Candidate>& candidates) {
3468 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003469 if (IsClosed()) {
3470 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3471 return false;
3472 }
3473
Steve Antond25da372017-11-06 14:50:29 -08003474 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003475 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3476 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003477 return false;
3478 }
3479
3480 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003481 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003482 return false;
3483 }
3484
3485 size_t number_removed =
3486 mutable_remote_description()->RemoveCandidates(candidates);
3487 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003488 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003489 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003490 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003491 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003492 }
3493
3494 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003495 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3496 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003497 RTC_LOG(LS_ERROR)
3498 << "RemoveIceCandidates: Error when removing remote candidates: "
3499 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003500 }
3501 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003502}
3503
Niels Möller0c4f7be2018-05-07 14:01:37 +02003504RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003505 if (!worker_thread()->IsCurrent()) {
3506 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003507 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003508 }
3509
Niels Möller0c4f7be2018-05-07 14:01:37 +02003510 const bool has_min = bitrate.min_bitrate_bps.has_value();
3511 const bool has_start = bitrate.start_bitrate_bps.has_value();
3512 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003513 if (has_min && *bitrate.min_bitrate_bps < 0) {
3514 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3515 "min_bitrate_bps <= 0");
3516 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003517 if (has_start) {
3518 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003519 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003520 "start_bitrate_bps < min_bitrate_bps");
3521 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003522 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3523 "curent_bitrate_bps < 0");
3524 }
3525 }
3526 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003527 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003529 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003530 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3531 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3532 "max_bitrate_bps < min_bitrate_bps");
3533 } else if (*bitrate.max_bitrate_bps < 0) {
3534 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3535 "max_bitrate_bps < 0");
3536 }
3537 }
3538
zstein4b979802017-06-02 14:37:37 -07003539 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003540 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003541
3542 return RTCError::OK();
3543}
3544
Alex Narest78609d52017-10-20 10:37:47 +02003545void PeerConnection::SetBitrateAllocationStrategy(
3546 std::unique_ptr<rtc::BitrateAllocationStrategy>
3547 bitrate_allocation_strategy) {
3548 rtc::Thread* worker_thread = factory_->worker_thread();
3549 if (!worker_thread->IsCurrent()) {
3550 rtc::BitrateAllocationStrategy* strategy_raw =
3551 bitrate_allocation_strategy.release();
3552 auto functor = [this, strategy_raw]() {
3553 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003554 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003555 };
3556 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3557 return;
3558 }
3559 RTC_DCHECK(call_.get());
3560 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3561}
3562
henrika5f6bf242017-11-01 11:06:56 +01003563void PeerConnection::SetAudioPlayout(bool playout) {
3564 if (!worker_thread()->IsCurrent()) {
3565 worker_thread()->Invoke<void>(
3566 RTC_FROM_HERE,
3567 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3568 return;
3569 }
3570 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003571 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003572 audio_state->SetPlayout(playout);
3573}
3574
3575void PeerConnection::SetAudioRecording(bool recording) {
3576 if (!worker_thread()->IsCurrent()) {
3577 worker_thread()->Invoke<void>(
3578 RTC_FROM_HERE,
3579 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3580 return;
3581 }
3582 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003583 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003584 audio_state->SetRecording(recording);
3585}
3586
Steve Anton8c0f7a72017-10-03 10:03:10 -07003587std::unique_ptr<rtc::SSLCertificate>
3588PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003589 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3590 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003591 return nullptr;
3592 }
Steve Antonf25303e2018-10-16 15:23:31 -07003593 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003594}
3595
Zhi Huang70b820f2018-01-27 14:16:15 -08003596std::unique_ptr<rtc::SSLCertChain>
3597PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003598 auto audio_transceiver = GetFirstAudioTransceiver();
3599 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003600 return nullptr;
3601 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003602 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003603 audio_transceiver->internal()->channel()->transport_name());
3604}
3605
3606rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3607PeerConnection::GetFirstAudioTransceiver() const {
3608 for (auto transceiver : transceivers_) {
3609 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3610 return transceiver;
3611 }
3612 }
3613 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003614}
3615
ivoc14d5dbe2016-07-04 07:06:55 -07003616bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3617 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003618 // TODO(eladalon): It would be better to not allow negative values into PC.
3619 const size_t max_size = (max_size_bytes < 0)
3620 ? RtcEventLog::kUnlimitedOutput
3621 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003622 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3623 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3624 output_period_ms = 5000;
3625 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003626 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003627 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003628 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003629}
3630
Bjorn Tereliusde939432017-11-20 17:38:14 +01003631bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3632 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003633 // TODO(eladalon): In C++14, this can be done with a lambda.
3634 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003635 bool operator()() {
3636 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3637 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003638 PeerConnection* const pc;
3639 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003640 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003641 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003642 return worker_thread()->Invoke<bool>(
3643 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003644}
3645
3646void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003647 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003648 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3649}
3650
Harald Alvestrandad88c882018-11-28 16:47:46 +01003651rtc::scoped_refptr<DtlsTransportInterface>
3652PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3653 return transport_controller_->LookupDtlsTransportByMid(mid);
3654}
3655
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003656rtc::scoped_refptr<DtlsTransport>
3657PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3658 return transport_controller_->LookupDtlsTransportByMid(mid);
3659}
3660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003661const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003662 return pending_local_description_ ? pending_local_description_.get()
3663 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003664}
3665
3666const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003667 return pending_remote_description_ ? pending_remote_description_.get()
3668 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003669}
3670
deadbeeffe4a8a42016-12-20 17:56:17 -08003671const SessionDescriptionInterface* PeerConnection::current_local_description()
3672 const {
Steve Anton75737c02017-11-06 10:37:17 -08003673 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003674}
3675
3676const SessionDescriptionInterface* PeerConnection::current_remote_description()
3677 const {
Steve Anton75737c02017-11-06 10:37:17 -08003678 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003679}
3680
3681const SessionDescriptionInterface* PeerConnection::pending_local_description()
3682 const {
Steve Anton75737c02017-11-06 10:37:17 -08003683 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003684}
3685
3686const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3687 const {
Steve Anton75737c02017-11-06 10:37:17 -08003688 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003689}
3690
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003691void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003692 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003693 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003694 // Update stats here so that we have the most recent stats for tracks and
3695 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003696 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003697
Steve Anton75737c02017-11-06 10:37:17 -08003698 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003699 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003700
Mirko Bonadei739baf02019-01-27 17:29:42 +01003701 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003702 transceiver->Stop();
3703 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003704
3705 // Ensure that all asynchronous stats requests are completed before destroying
3706 // the transport controller below.
3707 if (stats_collector_) {
3708 stats_collector_->WaitForPendingRequest();
3709 }
3710
3711 // Don't destroy BaseChannels until after stats has been cleaned up so that
3712 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003713 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003714
Qingsi Wang93a84392018-01-30 17:13:09 -08003715 // The event log is used in the transport controller, which must be outlived
3716 // by the former. CreateOffer by the peer connection is implemented
3717 // asynchronously and if the peer connection is closed without resetting the
3718 // WebRTC session description factory, the session description factory would
3719 // call the transport controller.
3720 webrtc_session_desc_factory_.reset();
3721 transport_controller_.reset();
3722
deadbeef42a42632017-03-10 15:18:00 -08003723 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003724 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3725 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003726
Steve Anton978b8762017-09-29 12:15:02 -07003727 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003728 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003729 call_.reset();
3730 // The event log must outlive call (and any other object that uses it).
3731 event_log_.reset();
3732 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003733 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003734 // The .h file says that observer can be discarded after close() returns.
3735 // Make sure this is true.
3736 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003737}
3738
Steve Antonad182762018-09-05 20:22:40 +00003739void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003741 switch (msg->message_id) {
3742 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3743 SetSessionDescriptionMsg* param =
3744 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3745 param->observer->OnSuccess();
3746 delete param;
3747 break;
3748 }
3749 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3750 SetSessionDescriptionMsg* param =
3751 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3752 param->observer->OnFailure(std::move(param->error));
3753 delete param;
3754 break;
3755 }
3756 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3757 CreateSessionDescriptionMsg* param =
3758 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3759 param->observer->OnFailure(std::move(param->error));
3760 delete param;
3761 break;
3762 }
3763 case MSG_GETSTATS: {
3764 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3765 StatsReports reports;
3766 stats_->GetStats(param->track, &reports);
3767 param->observer->OnComplete(reports);
3768 delete param;
3769 break;
3770 }
3771 case MSG_FREE_DATACHANNELS: {
3772 sctp_data_channels_to_free_.clear();
3773 break;
3774 }
3775 case MSG_REPORT_USAGE_PATTERN: {
3776 ReportUsagePattern();
3777 break;
3778 }
3779 default:
3780 RTC_NOTREACHED() << "Not implemented";
3781 break;
3782 }
3783}
3784
Steve Antonafb0bb72018-02-20 11:35:37 -08003785cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3786 RTC_DCHECK(!IsUnifiedPlan());
3787 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3788 GetAudioTransceiver()->internal()->channel());
3789 if (voice_channel) {
3790 return voice_channel->media_channel();
3791 } else {
3792 return nullptr;
3793 }
3794}
3795
3796cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3797 RTC_DCHECK(!IsUnifiedPlan());
3798 auto* video_channel = static_cast<cricket::VideoChannel*>(
3799 GetVideoTransceiver()->internal()->channel());
3800 if (video_channel) {
3801 return video_channel->media_channel();
3802 } else {
3803 return nullptr;
3804 }
3805}
3806
Steve Anton4171afb2017-11-20 10:20:22 -08003807void PeerConnection::CreateAudioReceiver(
3808 MediaStreamInterface* stream,
3809 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003810 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3811 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003812 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3813 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003814 auto* audio_receiver = new AudioRtpReceiver(
3815 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003816 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003817 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3818 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3819 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003820 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003821 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003822 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003823}
3824
Steve Anton4171afb2017-11-20 10:20:22 -08003825void PeerConnection::CreateVideoReceiver(
3826 MediaStreamInterface* stream,
3827 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003828 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3829 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003830 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3831 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003832 auto* video_receiver = new VideoRtpReceiver(
3833 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003834 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003835 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3836 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3837 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003838 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003839 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003840 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003841}
3842
deadbeef70ab1a12015-09-28 16:53:55 -07003843// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3844// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003845rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003846 const RtpSenderInfo& remote_sender_info) {
3847 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3848 if (!receiver) {
3849 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3850 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003851 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003852 }
Steve Anton4171afb2017-11-20 10:20:22 -08003853 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3854 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3855 } else {
3856 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3857 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003858 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003859}
3860
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003861void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3862 MediaStreamInterface* stream) {
3863 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003864 RTC_DCHECK(track);
3865 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003866 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003867 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003868 // We already have a sender for this track, so just change the stream_id
3869 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003870 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003871 return;
3872 }
3873
3874 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003875 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003876 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003877 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003878 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003879 // If the sender has already been configured in SDP, we call SetSsrc,
3880 // which will connect the sender to the underlying transport. This can
3881 // occur if a local session description that contains the ID of the sender
3882 // is set before AddStream is called. It can also occur if the local
3883 // session description is not changed and RemoveStream is called, and
3884 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003885 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003886 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003887 if (sender_info) {
3888 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003889 }
3890}
3891
3892// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3893// indefinitely, when we have unified plan SDP.
3894void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3895 MediaStreamInterface* stream) {
3896 RTC_DCHECK(!IsClosed());
3897 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003898 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003899 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3900 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003901 return;
3902 }
Steve Anton4171afb2017-11-20 10:20:22 -08003903 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003904}
3905
3906void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3907 MediaStreamInterface* stream) {
3908 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003909 RTC_DCHECK(track);
3910 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003911 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003912 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003913 // We already have a sender for this track, so just change the stream_id
3914 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003915 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003916 return;
3917 }
3918
3919 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003920 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003921 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003922 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003923 GetVideoTransceiver()->internal()->AddSender(new_sender);
3924 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003925 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003926 if (sender_info) {
3927 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003928 }
3929}
3930
3931void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3932 MediaStreamInterface* stream) {
3933 RTC_DCHECK(!IsClosed());
3934 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003935 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003936 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3937 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003938 return;
3939 }
Steve Anton4171afb2017-11-20 10:20:22 -08003940 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003941}
3942
Steve Antonba818672017-11-06 10:21:57 -08003943void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003944 if (ice_connection_state_ == new_state) {
3945 return;
3946 }
3947
deadbeefcbecd352015-09-23 11:50:27 -07003948 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003949 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003950 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003951 return;
3952 }
Steve Antonba818672017-11-06 10:21:57 -08003953
Mirko Bonadei675513b2017-11-09 11:09:25 +01003954 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3955 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003956 RTC_DCHECK(ice_connection_state_ !=
3957 PeerConnectionInterface::kIceConnectionClosed);
3958
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003959 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003960 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003961}
3962
Alex Loiko9289eda2018-11-23 16:18:59 +00003963void PeerConnection::SetStandardizedIceConnectionState(
3964 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003965 if (standardized_ice_connection_state_ == new_state)
3966 return;
3967 if (IsClosed())
3968 return;
3969 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003970 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003971}
3972
Jonas Olsson635474e2018-10-18 15:58:17 +02003973void PeerConnection::SetConnectionState(
3974 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02003975 if (connection_state_ == new_state)
3976 return;
3977 if (IsClosed())
3978 return;
3979 connection_state_ = new_state;
3980 Observer()->OnConnectionChange(new_state);
3981}
3982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003983void PeerConnection::OnIceGatheringChange(
3984 PeerConnectionInterface::IceGatheringState new_state) {
3985 if (IsClosed()) {
3986 return;
3987 }
3988 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003989 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003990}
3991
jbauch81bf7b02017-03-25 08:31:12 -07003992void PeerConnection::OnIceCandidate(
3993 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07003994 if (IsClosed()) {
3995 return;
3996 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003997 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003998 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3999 candidate->candidate().address().IsPrivateIP()) {
4000 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4001 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004002 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004003}
4004
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004005void PeerConnection::OnIceCandidatesRemoved(
4006 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004007 if (IsClosed()) {
4008 return;
4009 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004010 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004011}
4012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004013void PeerConnection::ChangeSignalingState(
4014 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004015 if (signaling_state_ == signaling_state) {
4016 return;
4017 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004018 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4019 << GetSignalingStateString(signaling_state_)
4020 << " New state: "
4021 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004022 signaling_state_ = signaling_state;
4023 if (signaling_state == kClosed) {
4024 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004025 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004026 standardized_ice_connection_state_ =
4027 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004028 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4029 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004030 if (ice_gathering_state_ != kIceGatheringComplete) {
4031 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004032 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004033 }
4034 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004035 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004036}
4037
deadbeefeb459812015-12-15 19:24:43 -08004038void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4039 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004040 if (IsClosed()) {
4041 return;
4042 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004043 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004044 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004045}
4046
deadbeefeb459812015-12-15 19:24:43 -08004047void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4048 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004049 if (IsClosed()) {
4050 return;
4051 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004052 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004053 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004054}
4055
4056void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4057 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004058 if (IsClosed()) {
4059 return;
4060 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004061 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004062 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004063}
4064
4065void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4066 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004067 if (IsClosed()) {
4068 return;
4069 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004070 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004071 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004072}
4073
Henrik Boström31638672017-11-23 17:48:32 +01004074void PeerConnection::PostSetSessionDescriptionSuccess(
4075 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004076 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4077 signaling_thread()->Post(RTC_FROM_HERE, this,
4078 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004079}
4080
deadbeefab9b2d12015-10-14 11:33:11 -07004081void PeerConnection::PostSetSessionDescriptionFailure(
4082 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004083 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004084 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004085 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4086 msg->error = std::move(error);
4087 signaling_thread()->Post(RTC_FROM_HERE, this,
4088 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004089}
4090
4091void PeerConnection::PostCreateSessionDescriptionFailure(
4092 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004093 RTCError error) {
4094 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004095 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4096 msg->error = std::move(error);
4097 signaling_thread()->Post(RTC_FROM_HERE, this,
4098 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004099}
4100
zhihuang1c378ed2017-08-17 14:10:50 -07004101void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004102 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004103 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004104 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004105
Steve Antondcc3c022017-12-22 16:02:54 -08004106 if (IsUnifiedPlan()) {
4107 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4108 } else {
4109 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4110 }
4111
Steve Antonfa2260d2017-12-28 16:38:23 -08004112 // Intentionally unset the data channel type for RTP data channel with the
4113 // second condition. Otherwise the RTP data channels would be successfully
4114 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4115 // when building with chromium. We want to leave RTP data channels broken, so
4116 // people won't try to use them.
4117 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4118 session_options->data_channel_type = data_channel_type();
4119 }
4120
Steve Antondcc3c022017-12-22 16:02:54 -08004121 // Apply ICE restart flag and renomination flag.
4122 for (auto& options : session_options->media_description_options) {
4123 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4124 options.transport_options.enable_ice_renomination =
4125 configuration_.enable_ice_renomination;
4126 }
4127
4128 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004129 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004130 session_options->pooled_ice_credentials =
4131 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4132 RTC_FROM_HERE,
4133 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4134 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004135 session_options->offer_extmap_allow_mixed =
4136 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004137}
4138
4139void PeerConnection::GetOptionsForPlanBOffer(
4140 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4141 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004142 // Figure out transceiver directional preferences.
4143 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4144 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4145
4146 // By default, generate sendrecv/recvonly m= sections.
4147 bool recv_audio = true;
4148 bool recv_video = true;
4149
4150 // By default, only offer a new m= section if we have media to send with it.
4151 bool offer_new_audio_description = send_audio;
4152 bool offer_new_video_description = send_video;
4153 bool offer_new_data_description = HasDataChannels();
4154
4155 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004156 if (offer_answer_options.offer_to_receive_audio !=
4157 RTCOfferAnswerOptions::kUndefined) {
4158 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004159 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004160 offer_new_audio_description ||
4161 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004162 }
Steve Antondcc3c022017-12-22 16:02:54 -08004163 if (offer_answer_options.offer_to_receive_video !=
4164 RTCOfferAnswerOptions::kUndefined) {
4165 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004166 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004167 offer_new_video_description ||
4168 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004169 }
4170
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004171 absl::optional<size_t> audio_index;
4172 absl::optional<size_t> video_index;
4173 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004174 // If a current description exists, generate m= sections in the same order,
4175 // using the first audio/video/data section that appears and rejecting
4176 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004177 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004178 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004179 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004180 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4181 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4182 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004183 }
4184
zhihuang1c378ed2017-08-17 14:10:50 -07004185 // Add audio/video/data m= sections to the end if needed.
4186 if (!audio_index && offer_new_audio_description) {
4187 session_options->media_description_options.push_back(
4188 cricket::MediaDescriptionOptions(
4189 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004190 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4191 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004192 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004193 }
zhihuang1c378ed2017-08-17 14:10:50 -07004194 if (!video_index && offer_new_video_description) {
4195 session_options->media_description_options.push_back(
4196 cricket::MediaDescriptionOptions(
4197 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004198 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4199 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004200 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004201 }
zhihuang1c378ed2017-08-17 14:10:50 -07004202 if (!data_index && offer_new_data_description) {
4203 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004204 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004205 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004206 }
4207
4208 cricket::MediaDescriptionOptions* audio_media_description_options =
4209 !audio_index ? nullptr
4210 : &session_options->media_description_options[*audio_index];
4211 cricket::MediaDescriptionOptions* video_media_description_options =
4212 !video_index ? nullptr
4213 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004214
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004215 AddPlanBRtpSenderOptions(GetSendersInternal(),
4216 audio_media_description_options,
4217 video_media_description_options,
4218 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004219}
4220
Steve Antondcc3c022017-12-22 16:02:54 -08004221static cricket::MediaDescriptionOptions
4222GetMediaDescriptionOptionsForTransceiver(
4223 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4224 transceiver,
4225 const std::string& mid) {
4226 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004227 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004228 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004229 // This behavior is specified in JSEP. The gist is that:
4230 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4231 // sendrecv.
4232 // 2. If the MSID is included, then it must be included in any subsequent
4233 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004234 if (transceiver->stopped() ||
4235 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4236 !transceiver->internal()->has_ever_been_used_to_send())) {
4237 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004238 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004239
4240 cricket::SenderOptions sender_options;
4241 sender_options.track_id = transceiver->sender()->id();
4242 sender_options.stream_ids = transceiver->sender()->stream_ids();
4243
4244 // The following sets up RIDs and Simulcast.
4245 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004246 RtpParameters send_parameters =
4247 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004248 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4249 send_parameters.encodings.end(),
4250 [](const RtpEncodingParameters& encoding) {
4251 return !encoding.rid.empty();
4252 });
4253
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004254 std::vector<RidDescription> send_rids;
4255 SimulcastLayerList send_layers;
4256 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4257 if (encoding.rid.empty()) {
4258 continue;
4259 }
4260 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4261 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4262 }
4263
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004264 if (has_rids) {
4265 sender_options.rids = send_rids;
4266 }
4267
4268 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004269 // When RIDs are configured, we must set num_sim_layers to 0 to.
4270 // Otherwise, num_sim_layers must be 1 because either there is no
4271 // simulcast, or simulcast is acheived by munging the SDP.
4272 sender_options.num_sim_layers = has_rids ? 0 : 1;
4273 media_description_options.sender_options.push_back(sender_options);
4274
Steve Antondcc3c022017-12-22 16:02:54 -08004275 return media_description_options;
4276}
4277
Steve Anton5c72e712018-12-10 14:25:30 -08004278// Returns the ContentInfo at mline index |i|, or null if none exists.
4279static const ContentInfo* GetContentByIndex(
4280 const SessionDescriptionInterface* sdesc,
4281 size_t i) {
4282 if (!sdesc) {
4283 return nullptr;
4284 }
4285 const ContentInfos& contents = sdesc->description()->contents();
4286 return (i < contents.size() ? &contents[i] : nullptr);
4287}
4288
Steve Antondcc3c022017-12-22 16:02:54 -08004289void PeerConnection::GetOptionsForUnifiedPlanOffer(
4290 const RTCOfferAnswerOptions& offer_answer_options,
4291 cricket::MediaSessionOptions* session_options) {
4292 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4293 // Offers) and 5.2.2 (Subsequent Offers).
4294 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4295 const ContentInfos& local_contents =
4296 (local_description() ? local_description()->description()->contents()
4297 : ContentInfos());
4298 const ContentInfos& remote_contents =
4299 (remote_description() ? remote_description()->description()->contents()
4300 : ContentInfos());
4301 // The mline indices that can be recycled. New transceivers should reuse these
4302 // slots first.
4303 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004304 // First, go through each media section that exists in either the local or
4305 // remote description and generate a media section in this offer for the
4306 // associated transceiver. If a media section can be recycled, generate a
4307 // default, rejected media section here that can be later overwritten.
4308 for (size_t i = 0;
4309 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4310 // Either |local_content| or |remote_content| is non-null.
4311 const ContentInfo* local_content =
4312 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004313 const ContentInfo* current_local_content =
4314 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004315 const ContentInfo* remote_content =
4316 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004317 const ContentInfo* current_remote_content =
4318 GetContentByIndex(current_remote_description(), i);
4319 bool had_been_rejected =
4320 (current_local_content && current_local_content->rejected) ||
4321 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004322 const std::string& mid =
4323 (local_content ? local_content->name : remote_content->name);
4324 cricket::MediaType media_type =
4325 (local_content ? local_content->media_description()->type()
4326 : remote_content->media_description()->type());
4327 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4328 media_type == cricket::MEDIA_TYPE_VIDEO) {
4329 auto transceiver = GetAssociatedTransceiver(mid);
4330 RTC_CHECK(transceiver);
4331 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004332 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004333 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004334 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004335 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4336 RtpTransceiverDirection::kInactive,
4337 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004338 recycleable_mline_indices.push(i);
4339 } else {
4340 session_options->media_description_options.push_back(
4341 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4342 // CreateOffer shouldn't really cause any state changes in
4343 // PeerConnection, but we need a way to match new transceivers to new
4344 // media sections in SetLocalDescription and JSEP specifies this is done
4345 // by recording the index of the media section generated for the
4346 // transceiver in the offer.
4347 transceiver->internal()->set_mline_index(i);
4348 }
4349 } else {
4350 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004351 RTC_CHECK(GetDataMid());
4352 if (had_been_rejected || mid != *GetDataMid()) {
4353 session_options->media_description_options.push_back(
4354 GetMediaDescriptionOptionsForRejectedData(mid));
4355 } else {
4356 session_options->media_description_options.push_back(
4357 GetMediaDescriptionOptionsForActiveData(mid));
4358 }
Steve Antondcc3c022017-12-22 16:02:54 -08004359 }
4360 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004361
Steve Antondcc3c022017-12-22 16:02:54 -08004362 // Next, look for transceivers that are newly added (that is, are not stopped
4363 // and not associated). Reuse media sections marked as recyclable first,
4364 // otherwise append to the end of the offer. New media sections should be
4365 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004366 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004367 if (transceiver->mid() || transceiver->stopped()) {
4368 continue;
4369 }
4370 size_t mline_index;
4371 if (!recycleable_mline_indices.empty()) {
4372 mline_index = recycleable_mline_indices.front();
4373 recycleable_mline_indices.pop();
4374 session_options->media_description_options[mline_index] =
4375 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004376 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004377 } else {
4378 mline_index = session_options->media_description_options.size();
4379 session_options->media_description_options.push_back(
4380 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004381 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004382 }
4383 // See comment above for why CreateOffer changes the transceiver's state.
4384 transceiver->internal()->set_mline_index(mline_index);
4385 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004386 // Lastly, add a m-section if we have local data channels and an m section
4387 // does not already exist.
4388 if (!GetDataMid() && HasDataChannels()) {
4389 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004390 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004391 }
Steve Antondcc3c022017-12-22 16:02:54 -08004392}
4393
4394void PeerConnection::GetOptionsForAnswer(
4395 const RTCOfferAnswerOptions& offer_answer_options,
4396 cricket::MediaSessionOptions* session_options) {
4397 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4398
4399 if (IsUnifiedPlan()) {
4400 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4401 } else {
4402 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4403 }
4404
Steve Antonfa2260d2017-12-28 16:38:23 -08004405 // Intentionally unset the data channel type for RTP data channel. Otherwise
4406 // the RTP data channels would be successfully negotiated by default and the
4407 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4408 // We want to leave RTP data channels broken, so people won't try to use them.
4409 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4410 session_options->data_channel_type = data_channel_type();
4411 }
4412
Steve Antondcc3c022017-12-22 16:02:54 -08004413 // Apply ICE renomination flag.
4414 for (auto& options : session_options->media_description_options) {
4415 options.transport_options.enable_ice_renomination =
4416 configuration_.enable_ice_renomination;
4417 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004418
4419 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004420 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004421 session_options->pooled_ice_credentials =
4422 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4423 RTC_FROM_HERE,
4424 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4425 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004426}
4427
Steve Antondcc3c022017-12-22 16:02:54 -08004428void PeerConnection::GetOptionsForPlanBAnswer(
4429 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004430 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004431 // Figure out transceiver directional preferences.
4432 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4433 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4434
4435 // By default, generate sendrecv/recvonly m= sections. The direction is also
4436 // restricted by the direction in the offer.
4437 bool recv_audio = true;
4438 bool recv_video = true;
4439
4440 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004441 if (offer_answer_options.offer_to_receive_audio !=
4442 RTCOfferAnswerOptions::kUndefined) {
4443 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004444 }
Steve Antondcc3c022017-12-22 16:02:54 -08004445 if (offer_answer_options.offer_to_receive_video !=
4446 RTCOfferAnswerOptions::kUndefined) {
4447 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004448 }
4449
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004450 absl::optional<size_t> audio_index;
4451 absl::optional<size_t> video_index;
4452 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004453
4454 // Generate m= sections that match those in the offer.
4455 // Note that mediasession.cc will handle intersection our preferred
4456 // direction with the offered direction.
4457 GenerateMediaDescriptionOptions(
4458 remote_description(),
4459 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4460 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4461 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004462
4463 cricket::MediaDescriptionOptions* audio_media_description_options =
4464 !audio_index ? nullptr
4465 : &session_options->media_description_options[*audio_index];
4466 cricket::MediaDescriptionOptions* video_media_description_options =
4467 !video_index ? nullptr
4468 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004469
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004470 AddPlanBRtpSenderOptions(GetSendersInternal(),
4471 audio_media_description_options,
4472 video_media_description_options,
4473 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004474}
zhihuangaf388472016-11-02 16:49:48 -07004475
Steve Antondcc3c022017-12-22 16:02:54 -08004476void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4477 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4478 cricket::MediaSessionOptions* session_options) {
4479 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4480 // Answers) and 5.3.2 (Subsequent Answers).
4481 RTC_DCHECK(remote_description());
4482 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4483 for (const ContentInfo& content :
4484 remote_description()->description()->contents()) {
4485 cricket::MediaType media_type = content.media_description()->type();
4486 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4487 media_type == cricket::MEDIA_TYPE_VIDEO) {
4488 auto transceiver = GetAssociatedTransceiver(content.name);
4489 RTC_CHECK(transceiver);
4490 session_options->media_description_options.push_back(
4491 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4492 } else {
4493 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004494 // Reject all data sections if data channels are disabled.
4495 // Reject a data section if it has already been rejected.
4496 // Reject all data sections except for the first one.
4497 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4498 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004499 session_options->media_description_options.push_back(
4500 GetMediaDescriptionOptionsForRejectedData(content.name));
4501 } else {
4502 session_options->media_description_options.push_back(
4503 GetMediaDescriptionOptionsForActiveData(content.name));
4504 }
Steve Antondcc3c022017-12-22 16:02:54 -08004505 }
4506 }
htaa2a49d92016-03-04 02:51:39 -08004507}
4508
zhihuang1c378ed2017-08-17 14:10:50 -07004509void PeerConnection::GenerateMediaDescriptionOptions(
4510 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004511 RtpTransceiverDirection audio_direction,
4512 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004513 absl::optional<size_t>* audio_index,
4514 absl::optional<size_t>* video_index,
4515 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004516 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004517 for (const cricket::ContentInfo& content :
4518 session_desc->description()->contents()) {
4519 if (IsAudioContent(&content)) {
4520 // If we already have an audio m= section, reject this extra one.
4521 if (*audio_index) {
4522 session_options->media_description_options.push_back(
4523 cricket::MediaDescriptionOptions(
4524 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004525 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004526 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004527 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004528 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004529 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4530 content.name, audio_direction,
4531 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004532 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004533 }
4534 } else if (IsVideoContent(&content)) {
4535 // If we already have an video m= section, reject this extra one.
4536 if (*video_index) {
4537 session_options->media_description_options.push_back(
4538 cricket::MediaDescriptionOptions(
4539 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004540 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004541 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004542 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004543 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004544 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4545 content.name, video_direction,
4546 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004547 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004548 }
4549 } else {
4550 RTC_DCHECK(IsDataContent(&content));
4551 // If we already have an data m= section, reject this extra one.
4552 if (*data_index) {
4553 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004554 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004555 } else {
4556 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004557 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004558 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004559 }
4560 }
htaa2a49d92016-03-04 02:51:39 -08004561 }
deadbeefab9b2d12015-10-14 11:33:11 -07004562}
4563
Steve Antonfa2260d2017-12-28 16:38:23 -08004564cricket::MediaDescriptionOptions
4565PeerConnection::GetMediaDescriptionOptionsForActiveData(
4566 const std::string& mid) const {
4567 // Direction for data sections is meaningless, but legacy endpoints might
4568 // expect sendrecv.
4569 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4570 RtpTransceiverDirection::kSendRecv,
4571 /*stopped=*/false);
4572 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4573 return options;
4574}
4575
4576cricket::MediaDescriptionOptions
4577PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4578 const std::string& mid) const {
4579 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4580 RtpTransceiverDirection::kInactive,
4581 /*stopped=*/true);
4582 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4583 return options;
4584}
4585
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004586absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004587 switch (data_channel_type_) {
4588 case cricket::DCT_RTP:
4589 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004590 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004591 }
4592 return rtp_data_channel_->content_name();
4593 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004594 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004595 case cricket::DCT_MEDIA_TRANSPORT:
4596 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004597 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004598 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004599 }
4600}
4601
Steve Anton4171afb2017-11-20 10:20:22 -08004602void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4603 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4604 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004605 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004606}
4607
Steve Anton4171afb2017-11-20 10:20:22 -08004608void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004609 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004610 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004611 cricket::MediaType media_type,
4612 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004613 RTC_DCHECK(!IsUnifiedPlan());
4614
Steve Anton4171afb2017-11-20 10:20:22 -08004615 std::vector<RtpSenderInfo>* current_senders =
4616 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004617
Steve Anton4171afb2017-11-20 10:20:22 -08004618 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004619 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004620 for (auto sender_it = current_senders->begin();
4621 sender_it != current_senders->end();
4622 /* incremented manually */) {
4623 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004624 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004625 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004626 std::string params_stream_id;
4627 if (params) {
4628 params_stream_id =
4629 (!params->first_stream_id().empty() ? params->first_stream_id()
4630 : kDefaultStreamId);
4631 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004632 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004633 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004634 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004635 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004636 sender_exists) {
4637 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004638 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004639 OnRemoteSenderRemoved(info, media_type);
4640 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004641 }
4642 }
4643
Steve Anton4171afb2017-11-20 10:20:22 -08004644 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004645 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004646 if (!params.has_ssrcs()) {
4647 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4648 // sender, this means it is coming from a Unified Plan endpoint,so we just
4649 // create a default.
4650 default_sender_needed = true;
4651 break;
4652 }
4653
Seth Hampson845e8782018-03-02 11:34:10 -08004654 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004655 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004656 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4657 // not supported in Plan B, we just take the first here and create the
4658 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004659 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004660 (!params.first_stream_id().empty() ? params.first_stream_id()
4661 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004662 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004663 uint32_t ssrc = params.first_ssrc();
4664
4665 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004666 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004667 if (!stream) {
4668 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004669 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004670 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004671 remote_streams_->AddStream(stream);
4672 new_streams->AddStream(stream);
4673 }
4674
Steve Anton4171afb2017-11-20 10:20:22 -08004675 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004676 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004677 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004678 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004679 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004680 }
4681 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004682
Steve Anton4171afb2017-11-20 10:20:22 -08004683 // Add default sender if necessary.
4684 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004685 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004686 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004687 if (!default_stream) {
4688 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004689 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004690 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004691 remote_streams_->AddStream(default_stream);
4692 new_streams->AddStream(default_stream);
4693 }
Steve Anton4171afb2017-11-20 10:20:22 -08004694 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4695 ? kDefaultAudioSenderId
4696 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004697 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004698 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004699 if (!default_sender_info) {
4700 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004701 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004702 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004703 }
4704 }
deadbeefab9b2d12015-10-14 11:33:11 -07004705}
4706
Steve Anton4171afb2017-11-20 10:20:22 -08004707void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4708 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004709 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4710 << " receiver for track_id=" << sender_info.sender_id
4711 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004712
Steve Anton3d954a62018-04-02 11:27:23 -07004713 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004714 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004715 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004716 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004717 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004718 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004719 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004720 }
4721}
4722
Steve Anton4171afb2017-11-20 10:20:22 -08004723void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4724 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004725 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4726 << " receiver for track_id=" << sender_info.sender_id
4727 << " and stream_id=" << sender_info.stream_id;
4728
Seth Hampson845e8782018-03-02 11:34:10 -08004729 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004730
Henrik Boström933d8b02017-10-10 10:05:16 -07004731 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004732 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004733 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4734 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004735 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004736 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004737 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004738 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004739 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004740 }
4741 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004742 // Stopping or destroying a VideoRtpReceiver will end the
4743 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004744 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004745 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004746 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004747 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004748 // There's no guarantee the track is still available, e.g. the track may
4749 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004750 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004751 }
4752 } else {
nisseede5da42017-01-12 05:15:36 -08004753 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004754 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004755 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004756 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004757 }
deadbeefab9b2d12015-10-14 11:33:11 -07004758}
4759
4760void PeerConnection::UpdateEndedRemoteMediaStreams() {
4761 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4762 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4763 MediaStreamInterface* stream = remote_streams_->at(i);
4764 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4765 streams_to_remove.push_back(stream);
4766 }
4767 }
4768
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004769 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004770 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004771 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004772 }
4773}
4774
Steve Anton4171afb2017-11-20 10:20:22 -08004775void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004776 const std::vector<cricket::StreamParams>& streams,
4777 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004778 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004779
Seth Hampson845e8782018-03-02 11:34:10 -08004780 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004781 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004782 for (auto sender_it = current_senders->begin();
4783 sender_it != current_senders->end();
4784 /* incremented manually */) {
4785 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004786 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004787 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4788 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004789 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004790 OnLocalSenderRemoved(info, media_type);
4791 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004792 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004793 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004794 }
4795 }
4796
Steve Anton4171afb2017-11-20 10:20:22 -08004797 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004798 for (const cricket::StreamParams& params : streams) {
4799 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004800 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004801 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004802 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004803 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004804 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004805 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004806 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004807 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004808 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004809 }
4810 }
4811}
4812
Steve Anton4171afb2017-11-20 10:20:22 -08004813void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4814 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004815 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004816 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004817 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004818 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4819 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004820 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004821 return;
4822 }
4823
deadbeeffac06552015-11-25 11:26:01 -08004824 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004825 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004826 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004827 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004828 }
deadbeeffac06552015-11-25 11:26:01 -08004829
Seth Hampson5b4f0752018-04-02 16:31:36 -07004830 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004831 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004832}
4833
Steve Anton4171afb2017-11-20 10:20:22 -08004834void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4835 cricket::MediaType media_type) {
4836 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004837 if (!sender) {
4838 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004839 // SessionDescriptions has been renegotiated.
4840 return;
4841 }
deadbeeffac06552015-11-25 11:26:01 -08004842
4843 // A sender has been removed from the SessionDescription but it's still
4844 // associated with the PeerConnection. This only occurs if the SDP doesn't
4845 // match with the calls to CreateSender, AddStream and RemoveStream.
4846 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004847 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004848 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004849 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004850 }
deadbeeffac06552015-11-25 11:26:01 -08004851
Steve Anton4171afb2017-11-20 10:20:22 -08004852 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004853}
4854
4855void PeerConnection::UpdateLocalRtpDataChannels(
4856 const cricket::StreamParamsVec& streams) {
4857 std::vector<std::string> existing_channels;
4858
4859 // Find new and active data channels.
4860 for (const cricket::StreamParams& params : streams) {
4861 // |it->sync_label| is actually the data channel label. The reason is that
4862 // we use the same naming of data channels as we do for
4863 // MediaStreams and Tracks.
4864 // For MediaStreams, the sync_label is the MediaStream label and the
4865 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004866 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004867 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004868 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004869 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004870 continue;
4871 }
4872 // Set the SSRC the data channel should use for sending.
4873 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4874 existing_channels.push_back(data_channel_it->first);
4875 }
4876
4877 UpdateClosingRtpDataChannels(existing_channels, true);
4878}
4879
4880void PeerConnection::UpdateRemoteRtpDataChannels(
4881 const cricket::StreamParamsVec& streams) {
4882 std::vector<std::string> existing_channels;
4883
4884 // Find new and active data channels.
4885 for (const cricket::StreamParams& params : streams) {
4886 // The data channel label is either the mslabel or the SSRC if the mslabel
4887 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004888 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004889 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004890 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004891 auto data_channel_it = rtp_data_channels_.find(label);
4892 if (data_channel_it == rtp_data_channels_.end()) {
4893 // This is a new data channel.
4894 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4895 } else {
4896 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4897 }
4898 existing_channels.push_back(label);
4899 }
4900
4901 UpdateClosingRtpDataChannels(existing_channels, false);
4902}
4903
4904void PeerConnection::UpdateClosingRtpDataChannels(
4905 const std::vector<std::string>& active_channels,
4906 bool is_local_update) {
4907 auto it = rtp_data_channels_.begin();
4908 while (it != rtp_data_channels_.end()) {
4909 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004910 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004911 ++it;
4912 continue;
4913 }
4914
4915 if (is_local_update) {
4916 data_channel->SetSendSsrc(0);
4917 } else {
4918 data_channel->RemotePeerRequestClose();
4919 }
4920
4921 if (data_channel->state() == DataChannel::kClosed) {
4922 rtp_data_channels_.erase(it);
4923 it = rtp_data_channels_.begin();
4924 } else {
4925 ++it;
4926 }
4927 }
4928}
4929
4930void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4931 uint32_t remote_ssrc) {
4932 rtc::scoped_refptr<DataChannel> channel(
4933 InternalCreateDataChannel(label, nullptr));
4934 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004935 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004936 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004937 return;
4938 }
4939 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004940 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4941 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004942 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004943}
4944
4945rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4946 const std::string& label,
4947 const InternalDataChannelInit* config) {
4948 if (IsClosed()) {
4949 return nullptr;
4950 }
Steve Anton75737c02017-11-06 10:37:17 -08004951 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004952 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004953 << "InternalCreateDataChannel: Data is not supported in this call.";
4954 return nullptr;
4955 }
4956 InternalDataChannelInit new_config =
4957 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004958 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004959 if (new_config.id < 0) {
4960 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004961 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004962 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004963 RTC_LOG(LS_ERROR)
4964 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004965 return nullptr;
4966 }
4967 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004968 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004969 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004970 return nullptr;
4971 }
4972 }
4973
Steve Anton75737c02017-11-06 10:37:17 -08004974 rtc::scoped_refptr<DataChannel> channel(
4975 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004976 if (!channel) {
4977 sid_allocator_.ReleaseSid(new_config.id);
4978 return nullptr;
4979 }
4980
4981 if (channel->data_channel_type() == cricket::DCT_RTP) {
4982 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004983 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4984 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004985 return nullptr;
4986 }
4987 rtp_data_channels_[channel->label()] = channel;
4988 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004989 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004990 sctp_data_channels_.push_back(channel);
4991 channel->SignalClosed.connect(this,
4992 &PeerConnection::OnSctpDataChannelClosed);
4993 }
4994
Steve Anton2d8609c2018-01-23 16:38:46 -08004995 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004996 return channel;
4997}
4998
4999bool PeerConnection::HasDataChannels() const {
5000 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5001}
5002
5003void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
5004 for (const auto& channel : sctp_data_channels_) {
5005 if (channel->id() < 0) {
5006 int sid;
5007 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005008 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07005009 continue;
5010 }
5011 channel->SetSctpSid(sid);
5012 }
5013 }
5014}
5015
5016void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005017 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005018 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5019 ++it) {
5020 if (it->get() == channel) {
5021 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005022 // After the closing procedure is done, it's safe to use this ID for
5023 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005024 sid_allocator_.ReleaseSid(channel->id());
5025 }
deadbeefbd292462015-12-14 18:15:29 -08005026 // Since this method is triggered by a signal from the DataChannel,
5027 // we can't free it directly here; we need to free it asynchronously.
5028 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005029 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005030 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5031 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005032 return;
5033 }
5034 }
5035}
5036
deadbeefab9b2d12015-10-14 11:33:11 -07005037void PeerConnection::OnDataChannelDestroyed() {
5038 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5039 // DataChannel may callback to us and try to modify the list.
5040 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5041 temp_rtp_dcs.swap(rtp_data_channels_);
5042 for (const auto& kv : temp_rtp_dcs) {
5043 kv.second->OnTransportChannelDestroyed();
5044 }
5045
5046 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5047 temp_sctp_dcs.swap(sctp_data_channels_);
5048 for (const auto& channel : temp_sctp_dcs) {
5049 channel->OnTransportChannelDestroyed();
5050 }
5051}
5052
5053void PeerConnection::OnDataChannelOpenMessage(
5054 const std::string& label,
5055 const InternalDataChannelInit& config) {
5056 rtc::scoped_refptr<DataChannel> channel(
5057 InternalCreateDataChannel(label, &config));
5058 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005059 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005060 return;
5061 }
5062
deadbeefa601f5c2016-06-06 14:27:39 -07005063 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5064 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005065 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005066 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005067}
5068
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005069bool PeerConnection::HandleOpenMessage_s(
5070 const cricket::ReceiveDataParams& params,
5071 const rtc::CopyOnWriteBuffer& buffer) {
5072 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5073 // Received OPEN message; parse and signal that a new data channel should
5074 // be created.
5075 std::string label;
5076 InternalDataChannelInit config;
5077 config.id = params.ssrc;
5078 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5079 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5080 << params.ssrc;
5081 return true;
5082 }
5083 config.open_handshake_role = InternalDataChannelInit::kAcker;
5084 OnDataChannelOpenMessage(label, config);
5085 return true;
5086 }
5087 return false;
5088}
5089
Steve Anton4171afb2017-11-20 10:20:22 -08005090rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5091PeerConnection::GetAudioTransceiver() const {
5092 // This method only works with Plan B SDP, where there is a single
5093 // audio/video transceiver.
5094 RTC_DCHECK(!IsUnifiedPlan());
5095 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005096 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005097 return transceiver;
5098 }
5099 }
5100 RTC_NOTREACHED();
5101 return nullptr;
5102}
5103
5104rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5105PeerConnection::GetVideoTransceiver() const {
5106 // This method only works with Plan B SDP, where there is a single
5107 // audio/video transceiver.
5108 RTC_DCHECK(!IsUnifiedPlan());
5109 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005110 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005111 return transceiver;
5112 }
5113 }
5114 RTC_NOTREACHED();
5115 return nullptr;
5116}
5117
5118// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5119// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005120bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005121 switch (type) {
5122 case cricket::MEDIA_TYPE_AUDIO:
5123 return !GetAudioTransceiver()->internal()->senders().empty();
5124 case cricket::MEDIA_TYPE_VIDEO:
5125 return !GetVideoTransceiver()->internal()->senders().empty();
5126 case cricket::MEDIA_TYPE_DATA:
5127 return false;
5128 }
5129 RTC_NOTREACHED();
5130 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005131}
5132
Steve Anton4171afb2017-11-20 10:20:22 -08005133rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5134PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005135 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005136 for (auto sender : transceiver->internal()->senders()) {
5137 if (sender->track() == track) {
5138 return sender;
5139 }
5140 }
5141 }
5142 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005143}
5144
Steve Anton4171afb2017-11-20 10:20:22 -08005145rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5146PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005147 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005148 for (auto sender : transceiver->internal()->senders()) {
5149 if (sender->id() == sender_id) {
5150 return sender;
5151 }
5152 }
5153 }
5154 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005155}
5156
Steve Anton4171afb2017-11-20 10:20:22 -08005157rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5158PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005159 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005160 for (auto receiver : transceiver->internal()->receivers()) {
5161 if (receiver->id() == receiver_id) {
5162 return receiver;
5163 }
5164 }
5165 }
5166 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005167}
5168
Steve Anton4171afb2017-11-20 10:20:22 -08005169std::vector<PeerConnection::RtpSenderInfo>*
5170PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5171 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5172 media_type == cricket::MEDIA_TYPE_VIDEO);
5173 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5174 ? &remote_audio_sender_infos_
5175 : &remote_video_sender_infos_;
5176}
5177
5178std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005179 cricket::MediaType media_type) {
5180 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5181 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005182 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5183 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005184}
5185
Steve Anton4171afb2017-11-20 10:20:22 -08005186const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5187 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005188 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005189 const std::string sender_id) const {
5190 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005191 if (sender_info.stream_id == stream_id &&
5192 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005193 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005194 }
5195 }
5196 return nullptr;
5197}
5198
5199DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5200 for (const auto& channel : sctp_data_channels_) {
5201 if (channel->id() == sid) {
5202 return channel;
5203 }
5204 }
5205 return nullptr;
5206}
5207
deadbeef91dd5672016-05-18 16:55:30 -07005208bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005209 const cricket::ServerAddresses& stun_servers,
5210 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005211 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005212 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005213 // To handle both internal and externally created port allocator, we will
5214 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005215 port_allocator_flags_ = port_allocator_->flags();
5216 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5217 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5218 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005219 // If the disable-IPv6 flag was specified, we'll not override it
5220 // by experiment.
5221 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005222 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005223 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5224 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005225 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005226 }
5227
zhihuangb09b3f92017-03-07 14:40:51 -08005228 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005229 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005230 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005231 }
5232
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005233 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005234 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005235 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005236 }
5237
honghaiz60347052016-05-31 18:29:12 -07005238 if (configuration.candidate_network_policy ==
5239 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005240 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005241 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005242 }
5243
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005244 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005245 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005246 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5247 }
5248
Qingsi Wanga2d60672018-04-11 16:57:45 -07005249 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005250 // No step delay is used while allocating ports.
5251 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5252 port_allocator_->set_candidate_filter(
5253 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005254 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005255
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005256 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005257 for (auto& turn_server : turn_servers_copy) {
5258 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005259 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005260 // Call this last since it may create pooled allocator sessions using the
5261 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005262 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005263 stun_servers, std::move(turn_servers_copy),
5264 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5265 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005266 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005267 return true;
5268}
5269
deadbeef91dd5672016-05-18 16:55:30 -07005270bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005271 const cricket::ServerAddresses& stun_servers,
5272 const std::vector<cricket::RelayServerConfig>& turn_servers,
5273 IceTransportsType type,
5274 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005275 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005276 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005277 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005278 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005279 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005280 // According to JSEP, after setLocalDescription, changing the candidate pool
5281 // size is not allowed, and changing the set of ICE servers will not result
5282 // in new candidates being gathered.
5283 if (local_description()) {
5284 port_allocator_->FreezeCandidatePool();
5285 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005286 // Add the custom tls turn servers if they exist.
5287 auto turn_servers_copy = turn_servers;
5288 for (auto& turn_server : turn_servers_copy) {
5289 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5290 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005291 // Call this last since it may create pooled allocator sessions using the
5292 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005293 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005294 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5295 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005296}
5297
Steve Antonba818672017-11-06 10:21:57 -08005298cricket::ChannelManager* PeerConnection::channel_manager() const {
5299 return factory_->channel_manager();
5300}
5301
Elad Alon99c3fe52017-10-13 16:29:40 +02005302bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005303 std::unique_ptr<RtcEventLogOutput> output,
5304 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005305 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005306 if (!event_log_) {
5307 return false;
5308 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005309 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005310}
5311
5312void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005313 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005314 if (event_log_) {
5315 event_log_->StopLogging();
5316 }
ivoc14d5dbe2016-07-04 07:06:55 -07005317}
nisseeaabdf62017-05-05 02:23:02 -07005318
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005319cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005320 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005321 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005322 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005323 if (channel && channel->content_name() == content_name) {
5324 return channel;
5325 }
Steve Anton75737c02017-11-06 10:37:17 -08005326 }
5327 if (rtp_data_channel() &&
5328 rtp_data_channel()->content_name() == content_name) {
5329 return rtp_data_channel();
5330 }
5331 return nullptr;
5332}
5333
5334bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005335 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005336 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005337 RTC_LOG(LS_INFO)
5338 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005339 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005340 return false;
5341 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005342 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005343 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005344 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005345 return false;
5346 }
5347
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005348 absl::optional<rtc::SSLRole> dtls_role;
5349 if (sctp_mid_) {
5350 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5351 } else if (is_caller_) {
5352 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5353 }
Zhi Huange830e682018-03-30 10:48:35 -07005354 if (dtls_role) {
5355 *role = *dtls_role;
5356 return true;
5357 }
5358 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005359}
5360
5361bool PeerConnection::GetSslRole(const std::string& content_name,
5362 rtc::SSLRole* role) {
5363 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005364 RTC_LOG(LS_INFO)
5365 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005366 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005367 return false;
5368 }
5369
Zhi Huange830e682018-03-30 10:48:35 -07005370 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5371 if (dtls_role) {
5372 *role = *dtls_role;
5373 return true;
5374 }
5375 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005376}
5377
Steve Antonf8470812017-12-04 10:46:21 -08005378void PeerConnection::SetSessionError(SessionError error,
5379 const std::string& error_desc) {
5380 RTC_DCHECK_RUN_ON(signaling_thread());
5381 if (error != session_error_) {
5382 session_error_ = error;
5383 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005384 }
5385}
5386
Zhi Huange830e682018-03-30 10:48:35 -07005387RTCError PeerConnection::UpdateSessionState(
5388 SdpType type,
5389 cricket::ContentSource source,
5390 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005391 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005392
5393 // If there's already a pending error then no state transition should happen.
5394 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005395 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005396
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005397 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005398 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005399 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005400 }
5401
5402 // Update the signaling state according to the specified state machine (see
5403 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005404 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005405 ChangeSignalingState(source == cricket::CS_LOCAL
5406 ? PeerConnectionInterface::kHaveLocalOffer
5407 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005408 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005409 ChangeSignalingState(source == cricket::CS_LOCAL
5410 ? PeerConnectionInterface::kHaveLocalPrAnswer
5411 : PeerConnectionInterface::kHaveRemotePrAnswer);
5412 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005413 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005414 ChangeSignalingState(PeerConnectionInterface::kStable);
5415 }
5416
5417 // Update internal objects according to the session description's media
5418 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005419 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005420 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005421 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005422 }
5423
Steve Anton8a006912017-12-04 15:25:56 -08005424 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005425}
5426
Steve Anton8a006912017-12-04 15:25:56 -08005427RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005428 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005429 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005430 const SessionDescriptionInterface* sdesc =
5431 (source == cricket::CS_LOCAL ? local_description()
5432 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005433 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005434
5435 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005436 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005437 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005438 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005439 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005440 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005441 continue;
5442 }
5443 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005444 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005445 if (!content_desc) {
5446 continue;
5447 }
5448 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005449 bool success = (source == cricket::CS_LOCAL)
5450 ? channel->SetLocalContent(content_desc, type, &error)
5451 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005452 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005454 }
5455 }
5456
5457 // If using the RtpDataChannel, push down the new SDP section for it too.
5458 if (rtp_data_channel_) {
5459 const ContentInfo* data_content =
5460 cricket::GetFirstDataContent(sdesc->description());
5461 if (data_content && !data_content->rejected) {
5462 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005463 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005464 if (data_desc) {
5465 std::string error;
5466 bool success =
5467 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005468 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005469 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005470 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005471 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005472 }
Steve Anton75737c02017-11-06 10:37:17 -08005473 }
5474 }
5475 }
Steve Antoned10bd92017-12-05 10:52:59 -08005476
Steve Anton75737c02017-11-06 10:37:17 -08005477 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5478 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5479 if (sctp_transport_ && local_description() && remote_description() &&
5480 cricket::GetFirstDataContent(local_description()->description()) &&
5481 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005482 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005483 RTC_FROM_HERE,
5484 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005485 if (!success) {
5486 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5487 "Failed to push down SCTP parameters.");
5488 }
Steve Anton75737c02017-11-06 10:37:17 -08005489 }
Steve Antoned10bd92017-12-05 10:52:59 -08005490
Steve Anton8a006912017-12-04 15:25:56 -08005491 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005492}
5493
5494bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5495 RTC_DCHECK(network_thread()->IsCurrent());
5496 RTC_DCHECK(local_description());
5497 RTC_DCHECK(remote_description());
5498 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5499 // When we support "max-message-size", that would also be pushed down here.
5500 return sctp_transport_->Start(
5501 GetSctpPort(local_description()->description()),
5502 GetSctpPort(remote_description()->description()));
5503}
5504
Steve Anton8a006912017-12-04 15:25:56 -08005505RTCError PeerConnection::PushdownTransportDescription(
5506 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005507 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005508 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005509
Zhi Huange830e682018-03-30 10:48:35 -07005510 if (source == cricket::CS_LOCAL) {
5511 const SessionDescriptionInterface* sdesc = local_description();
5512 RTC_DCHECK(sdesc);
5513 return transport_controller_->SetLocalDescription(type,
5514 sdesc->description());
5515 } else {
5516 const SessionDescriptionInterface* sdesc = remote_description();
5517 RTC_DCHECK(sdesc);
5518 return transport_controller_->SetRemoteDescription(type,
5519 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005520 }
Steve Anton75737c02017-11-06 10:37:17 -08005521}
5522
5523bool PeerConnection::GetTransportDescription(
5524 const SessionDescription* description,
5525 const std::string& content_name,
5526 cricket::TransportDescription* tdesc) {
5527 if (!description || !tdesc) {
5528 return false;
5529 }
5530 const TransportInfo* transport_info =
5531 description->GetTransportInfoByName(content_name);
5532 if (!transport_info) {
5533 return false;
5534 }
5535 *tdesc = transport_info->description;
5536 return true;
5537}
5538
Steve Anton75737c02017-11-06 10:37:17 -08005539cricket::IceConfig PeerConnection::ParseIceConfig(
5540 const PeerConnectionInterface::RTCConfiguration& config) const {
5541 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005542 switch (config.continual_gathering_policy) {
5543 case PeerConnectionInterface::GATHER_ONCE:
5544 gathering_policy = cricket::GATHER_ONCE;
5545 break;
5546 case PeerConnectionInterface::GATHER_CONTINUALLY:
5547 gathering_policy = cricket::GATHER_CONTINUALLY;
5548 break;
5549 default:
5550 RTC_NOTREACHED();
5551 gathering_policy = cricket::GATHER_ONCE;
5552 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005553
Steve Anton75737c02017-11-06 10:37:17 -08005554 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005555 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5556 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005557 ice_config.prioritize_most_likely_candidate_pairs =
5558 config.prioritize_most_likely_ice_candidate_pairs;
5559 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005560 RTCConfigurationToIceConfigOptionalInt(
5561 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005562 ice_config.continual_gathering_policy = gathering_policy;
5563 ice_config.presume_writable_when_fully_relayed =
5564 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005565 ice_config.ice_check_interval_strong_connectivity =
5566 config.ice_check_interval_strong_connectivity;
5567 ice_config.ice_check_interval_weak_connectivity =
5568 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005569 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005570 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5571 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005572 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005573 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005574 ice_config.regather_all_networks_interval_range =
5575 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005576 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005577 return ice_config;
5578}
5579
Steve Antona41959e2018-11-28 11:15:33 -08005580static absl::string_view GetTrackIdBySsrc(
5581 const SessionDescriptionInterface* session_description,
5582 uint32_t ssrc) {
5583 if (!session_description) {
5584 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005585 }
Steve Antona41959e2018-11-28 11:15:33 -08005586 for (const cricket::ContentInfo& content :
5587 session_description->description()->contents()) {
5588 const cricket::MediaContentDescription& media =
5589 *content.media_description();
5590 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5591 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5592 const cricket::StreamParams* stream_params =
5593 cricket::GetStreamBySsrc(media.streams(), ssrc);
5594 if (stream_params) {
5595 return stream_params->id;
5596 }
5597 }
5598 }
5599 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005600}
5601
Steve Antona41959e2018-11-28 11:15:33 -08005602absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5603 return GetTrackIdBySsrc(local_description(), ssrc);
5604}
5605
5606absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5607 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005608}
5609
5610bool PeerConnection::SendData(const cricket::SendDataParams& params,
5611 const rtc::CopyOnWriteBuffer& payload,
5612 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005613 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5614 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5615 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005616 return false;
5617 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005618 if (media_transport_) {
5619 SendDataParams send_params;
5620 send_params.type = ToWebrtcDataMessageType(params.type);
5621 send_params.ordered = params.ordered;
5622 if (params.max_rtx_count >= 0) {
5623 send_params.max_rtx_count = params.max_rtx_count;
5624 } else if (params.max_rtx_ms >= 0) {
5625 send_params.max_rtx_ms = params.max_rtx_ms;
5626 }
5627 return media_transport_->SendData(params.sid, send_params, payload).ok();
5628 }
Steve Anton75737c02017-11-06 10:37:17 -08005629 return rtp_data_channel_
5630 ? rtp_data_channel_->SendData(params, payload, result)
5631 : network_thread()->Invoke<bool>(
5632 RTC_FROM_HERE,
5633 Bind(&cricket::SctpTransportInternal::SendData,
5634 sctp_transport_.get(), params, payload, result));
5635}
5636
5637bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005638 RTC_DCHECK_RUN_ON(signaling_thread());
5639 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005640 // Don't log an error here, because DataChannels are expected to call
5641 // ConnectDataChannel in this state. It's the only way to initially tell
5642 // whether or not the underlying transport is ready.
5643 return false;
5644 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005645 if (media_transport_) {
5646 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5647 &DataChannel::OnChannelReady);
5648 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5649 &DataChannel::OnDataReceived);
5650 SignalMediaTransportChannelClosing_s.connect(
5651 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5652 SignalMediaTransportChannelClosed_s.connect(
5653 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5654 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005655 rtp_data_channel_->SignalReadyToSendData.connect(
5656 webrtc_data_channel, &DataChannel::OnChannelReady);
5657 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5658 &DataChannel::OnDataReceived);
5659 } else {
5660 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5661 &DataChannel::OnChannelReady);
5662 SignalSctpDataReceived.connect(webrtc_data_channel,
5663 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005664 SignalSctpClosingProcedureStartedRemotely.connect(
5665 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5666 SignalSctpClosingProcedureComplete.connect(
5667 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005668 }
5669 return true;
5670}
5671
5672void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005673 RTC_DCHECK_RUN_ON(signaling_thread());
5674 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005675 RTC_LOG(LS_ERROR)
5676 << "DisconnectDataChannel called when rtp_data_channel_ and "
5677 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005678 return;
5679 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005680 if (media_transport_) {
5681 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5682 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5683 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5684 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5685 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005686 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5687 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5688 } else {
5689 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5690 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005691 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5692 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005693 }
5694}
5695
5696void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005697 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005698 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005699 return;
5700 }
Steve Anton75737c02017-11-06 10:37:17 -08005701 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005702 RTC_LOG(LS_ERROR)
5703 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005704 return;
5705 }
5706 network_thread()->Invoke<void>(
5707 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5708 sctp_transport_.get(), sid));
5709}
5710
5711void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005712 if (media_transport_) {
5713 media_transport_->CloseChannel(sid);
5714 return;
5715 }
Steve Anton75737c02017-11-06 10:37:17 -08005716 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005717 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005718 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005719 return;
5720 }
5721 network_thread()->Invoke<void>(
5722 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5723 sctp_transport_.get(), sid));
5724}
5725
5726bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005727 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005728 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005729 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005730 sctp_ready_to_send_data_;
5731}
5732
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005733void PeerConnection::OnDataReceived(int channel_id,
5734 DataMessageType type,
5735 const rtc::CopyOnWriteBuffer& buffer) {
5736 cricket::ReceiveDataParams params;
5737 params.sid = channel_id;
5738 params.type = ToCricketDataMessageType(type);
5739 media_transport_invoker_->AsyncInvoke<void>(
5740 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5741 RTC_DCHECK_RUN_ON(signaling_thread());
5742 if (!HandleOpenMessage_s(params, buffer)) {
5743 SignalMediaTransportReceivedData_s(params, buffer);
5744 }
5745 });
5746}
5747
5748void PeerConnection::OnChannelClosing(int channel_id) {
5749 media_transport_invoker_->AsyncInvoke<void>(
5750 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5751 RTC_DCHECK_RUN_ON(signaling_thread());
5752 SignalMediaTransportChannelClosing_s(channel_id);
5753 });
5754}
5755
5756void PeerConnection::OnChannelClosed(int channel_id) {
5757 media_transport_invoker_->AsyncInvoke<void>(
5758 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5759 RTC_DCHECK_RUN_ON(signaling_thread());
5760 SignalMediaTransportChannelClosed_s(channel_id);
5761 });
5762}
5763
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005764absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005765 if (sctp_mid_ && transport_controller_) {
5766 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5767 if (dtls_transport) {
5768 return dtls_transport->transport_name();
5769 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005770 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005771 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005772 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005773}
5774
Qingsi Wang72a43a12018-02-20 16:03:18 -08005775cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5776 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005777 network_thread()->Invoke<void>(
5778 RTC_FROM_HERE,
5779 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5780 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005781 return candidate_states_list;
5782}
5783
Steve Anton5dfde182018-02-06 10:34:40 -08005784std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5785 const {
5786 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005787 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005788 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005789 if (channel) {
5790 transport_names_by_mid[channel->content_name()] =
5791 channel->transport_name();
5792 }
Steve Anton75737c02017-11-06 10:37:17 -08005793 }
Steve Anton5dfde182018-02-06 10:34:40 -08005794 if (rtp_data_channel_) {
5795 transport_names_by_mid[rtp_data_channel_->content_name()] =
5796 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005797 }
5798 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005799 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005800 RTC_DCHECK(transport_name);
5801 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
Steve Anton5dfde182018-02-06 10:34:40 -08005803 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005804}
5805
Steve Anton5dfde182018-02-06 10:34:40 -08005806std::map<std::string, cricket::TransportStats>
5807PeerConnection::GetTransportStatsByNames(
5808 const std::set<std::string>& transport_names) {
5809 if (!network_thread()->IsCurrent()) {
5810 return network_thread()
5811 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5812 RTC_FROM_HERE,
5813 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005814 }
Steve Anton5dfde182018-02-06 10:34:40 -08005815 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5816 for (const std::string& transport_name : transport_names) {
5817 cricket::TransportStats transport_stats;
5818 bool success =
5819 transport_controller_->GetStats(transport_name, &transport_stats);
5820 if (success) {
5821 transport_stats_by_name[transport_name] = std::move(transport_stats);
5822 } else {
5823 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5824 << transport_name;
5825 }
5826 }
5827 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005828}
5829
5830bool PeerConnection::GetLocalCertificate(
5831 const std::string& transport_name,
5832 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005833 if (!certificate) {
5834 return false;
5835 }
5836 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5837 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005838}
5839
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005840std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005841 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005842 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005843}
5844
5845cricket::DataChannelType PeerConnection::data_channel_type() const {
5846 return data_channel_type_;
5847}
5848
5849bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5850 return pending_ice_restarts_.find(content_name) !=
5851 pending_ice_restarts_.end();
5852}
5853
Steve Anton75737c02017-11-06 10:37:17 -08005854bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5855 return transport_controller_->NeedsIceRestart(content_name);
5856}
5857
5858void PeerConnection::OnCertificateReady(
5859 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5860 transport_controller_->SetLocalCertificate(certificate);
5861}
5862
5863void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005864 SetSessionError(SessionError::kTransport,
5865 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005866}
5867
Alex Loiko9289eda2018-11-23 16:18:59 +00005868void PeerConnection::OnTransportControllerConnectionState(
5869 cricket::IceConnectionState state) {
5870 switch (state) {
5871 case cricket::kIceConnectionConnecting:
5872 // If the current state is Connected or Completed, then there were
5873 // writable channels but now there are not, so the next state must
5874 // be Disconnected.
5875 // kIceConnectionConnecting is currently used as the default,
5876 // un-connected state by the TransportController, so its only use is
5877 // detecting disconnections.
5878 if (ice_connection_state_ ==
5879 PeerConnectionInterface::kIceConnectionConnected ||
5880 ice_connection_state_ ==
5881 PeerConnectionInterface::kIceConnectionCompleted) {
5882 SetIceConnectionState(
5883 PeerConnectionInterface::kIceConnectionDisconnected);
5884 }
5885 break;
5886 case cricket::kIceConnectionFailed:
5887 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5888 break;
5889 case cricket::kIceConnectionConnected:
5890 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5891 "all transports are writable.";
5892 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5893 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5894 break;
5895 case cricket::kIceConnectionCompleted:
5896 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5897 "all transports are complete.";
5898 if (ice_connection_state_ !=
5899 PeerConnectionInterface::kIceConnectionConnected) {
5900 // If jumping directly from "checking" to "connected",
5901 // signal "connected" first.
5902 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5903 }
5904 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5905 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5906 ReportTransportStats();
5907 break;
5908 default:
5909 RTC_NOTREACHED();
5910 }
5911}
5912
Steve Anton75737c02017-11-06 10:37:17 -08005913void PeerConnection::OnTransportControllerCandidatesGathered(
5914 const std::string& transport_name,
5915 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005916 int sdp_mline_index;
5917 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005918 RTC_LOG(LS_ERROR)
5919 << "OnTransportControllerCandidatesGathered: content name "
5920 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005921 return;
5922 }
5923
5924 for (cricket::Candidates::const_iterator citer = candidates.begin();
5925 citer != candidates.end(); ++citer) {
5926 // Use transport_name as the candidate media id.
5927 std::unique_ptr<JsepIceCandidate> candidate(
5928 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5929 if (local_description()) {
5930 mutable_local_description()->AddCandidate(candidate.get());
5931 }
5932 OnIceCandidate(std::move(candidate));
5933 }
5934}
5935
5936void PeerConnection::OnTransportControllerCandidatesRemoved(
5937 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005938 // Sanity check.
5939 for (const cricket::Candidate& candidate : candidates) {
5940 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005941 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005942 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005943 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005944 return;
5945 }
5946 }
5947
5948 if (local_description()) {
5949 mutable_local_description()->RemoveCandidates(candidates);
5950 }
5951 OnIceCandidatesRemoved(candidates);
5952}
5953
5954void PeerConnection::OnTransportControllerDtlsHandshakeError(
5955 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005956 RTC_HISTOGRAM_ENUMERATION(
5957 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5958 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005959}
5960
Steve Antoned10bd92017-12-05 10:52:59 -08005961void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005962 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005963 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005964 if (channel && !channel->enabled()) {
5965 channel->Enable(true);
5966 }
Steve Anton75737c02017-11-06 10:37:17 -08005967 }
5968
Steve Anton4171afb2017-11-20 10:20:22 -08005969 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005970 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005971 }
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
5974// Returns the media index for a local ice candidate given the content name.
5975bool PeerConnection::GetLocalCandidateMediaIndex(
5976 const std::string& content_name,
5977 int* sdp_mline_index) {
5978 if (!local_description() || !sdp_mline_index) {
5979 return false;
5980 }
5981
5982 bool content_found = false;
5983 const ContentInfos& contents = local_description()->description()->contents();
5984 for (size_t index = 0; index < contents.size(); ++index) {
5985 if (contents[index].name == content_name) {
5986 *sdp_mline_index = static_cast<int>(index);
5987 content_found = true;
5988 break;
5989 }
5990 }
5991 return content_found;
5992}
5993
5994bool PeerConnection::UseCandidatesInSessionDescription(
5995 const SessionDescriptionInterface* remote_desc) {
5996 if (!remote_desc) {
5997 return true;
5998 }
5999 bool ret = true;
6000
6001 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6002 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6003 for (size_t n = 0; n < candidates->count(); ++n) {
6004 const IceCandidateInterface* candidate = candidates->at(n);
6005 bool valid = false;
6006 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6007 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006008 RTC_LOG(LS_INFO)
6009 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006010 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006011 }
6012 continue;
6013 }
6014 ret = UseCandidate(candidate);
6015 if (!ret) {
6016 break;
6017 }
6018 }
6019 }
6020 return ret;
6021}
6022
6023bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6024 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6025 size_t remote_content_size =
6026 remote_description()->description()->contents().size();
6027 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006028 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006029 return false;
6030 }
6031
6032 cricket::ContentInfo content =
6033 remote_description()->description()->contents()[mediacontent_index];
6034 std::vector<cricket::Candidate> candidates;
6035 candidates.push_back(candidate->candidate());
6036 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006037 RTCError error =
6038 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006039 if (error.ok()) {
6040 // Candidates successfully submitted for checking.
6041 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6042 ice_connection_state_ ==
6043 PeerConnectionInterface::kIceConnectionDisconnected) {
6044 // If state is New, then the session has just gotten its first remote ICE
6045 // candidates, so go to Checking.
6046 // If state is Disconnected, the session is re-using old candidates or
6047 // receiving additional ones, so go to Checking.
6048 // If state is Connected, stay Connected.
6049 // TODO(bemasc): If state is Connected, and the new candidates are for a
6050 // newly added transport, then the state actually _should_ move to
6051 // checking. Add a way to distinguish that case.
6052 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6053 }
6054 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006055 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006056 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006057 }
6058 return true;
6059}
6060
6061void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006062 // Destroy video channel first since it may have a pointer to the
6063 // voice channel.
6064 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006065 if (!video_info || video_info->rejected) {
6066 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006067 }
6068
Steve Anton6fec8802017-12-04 10:37:29 -08006069 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6070 if (!audio_info || audio_info->rejected) {
6071 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006072 }
6073
6074 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6075 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006076 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006077 }
6078}
6079
Steve Antondcc3c022017-12-22 16:02:54 -08006080RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6081 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006082 const cricket::ContentGroup* bundle_group = nullptr;
6083 if (configuration_.bundle_policy ==
6084 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006085 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006086 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006087 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6088 "max-bundle configured but session description "
6089 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006090 }
6091 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006092 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006093}
6094
6095RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006096 // Creating the media channels. Transports should already have been created
6097 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006098 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006099 if (voice && !voice->rejected &&
6100 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006101 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006102 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006103 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6104 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006105 }
6106 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6107 }
6108
Steve Antondcc3c022017-12-22 16:02:54 -08006109 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006110 if (video && !video->rejected &&
6111 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006112 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006113 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6115 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006116 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006117 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006118 }
6119
Steve Antondcc3c022017-12-22 16:02:54 -08006120 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006121 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006122 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006123 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006124 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6125 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006126 }
6127 }
6128
Steve Anton8a006912017-12-04 15:25:56 -08006129 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006130}
6131
Steve Anton4171afb2017-11-20 10:20:22 -08006132// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006133cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006134 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006135 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006136 MediaTransportInterface* media_transport = nullptr;
6137 if (configuration_.use_media_transport) {
6138 media_transport = GetMediaTransport(mid);
6139 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006140
Steve Anton75737c02017-11-06 10:37:17 -08006141 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006142 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006143 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006144 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006145 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006146 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006147 }
Steve Anton75737c02017-11-06 10:37:17 -08006148 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6149 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006150 voice_channel->SignalSentPacket.connect(this,
6151 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006152 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006153
Steve Antoneda6ccd2017-12-04 10:21:55 -08006154 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006155}
6156
Steve Anton4171afb2017-11-20 10:20:22 -08006157// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006158cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006159 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006160 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006161 MediaTransportInterface* media_transport = nullptr;
6162 if (configuration_.use_media_transport) {
6163 media_transport = GetMediaTransport(mid);
6164 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006165
Steve Anton75737c02017-11-06 10:37:17 -08006166 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006167 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006168 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006169 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006170 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006171 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006172 }
Steve Anton75737c02017-11-06 10:37:17 -08006173 video_channel->SignalDtlsSrtpSetupFailure.connect(
6174 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006175 video_channel->SignalSentPacket.connect(this,
6176 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006177 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006178
Steve Antoneda6ccd2017-12-04 10:21:55 -08006179 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006180}
6181
Zhi Huange830e682018-03-30 10:48:35 -07006182bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006183 switch (data_channel_type_) {
6184 case cricket::DCT_MEDIA_TRANSPORT:
6185 if (network_thread()->Invoke<bool>(
6186 RTC_FROM_HERE,
6187 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6188 this, mid))) {
6189 for (const auto& channel : sctp_data_channels_) {
6190 channel->OnTransportChannelCreated();
6191 }
6192 return true;
6193 }
Steve Anton75737c02017-11-06 10:37:17 -08006194 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006195 case cricket::DCT_SCTP:
6196 if (!sctp_factory_) {
6197 RTC_LOG(LS_ERROR)
6198 << "Trying to create SCTP transport, but didn't compile with "
6199 "SCTP support (HAVE_SCTP)";
6200 return false;
6201 }
6202 if (!network_thread()->Invoke<bool>(
6203 RTC_FROM_HERE,
6204 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6205 return false;
6206 }
6207 for (const auto& channel : sctp_data_channels_) {
6208 channel->OnTransportChannelCreated();
6209 }
6210 return true;
6211 case cricket::DCT_RTP:
6212 default:
6213 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6214 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6215 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006216 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006217 if (!rtp_data_channel_) {
6218 return false;
6219 }
6220 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6221 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6222 rtp_data_channel_->SignalSentPacket.connect(
6223 this, &PeerConnection::OnSentPacket_w);
6224 rtp_data_channel_->SetRtpTransport(rtp_transport);
6225 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006226 }
6227
Steve Anton75737c02017-11-06 10:37:17 -08006228 return true;
6229}
6230
6231Call::Stats PeerConnection::GetCallStats() {
6232 if (!worker_thread()->IsCurrent()) {
6233 return worker_thread()->Invoke<Call::Stats>(
6234 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6235 }
6236 if (call_) {
6237 return call_->GetStats();
6238 } else {
6239 return Call::Stats();
6240 }
6241}
6242
Zhi Huange830e682018-03-30 10:48:35 -07006243bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006244 RTC_DCHECK(network_thread()->IsCurrent());
6245 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006246 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006247 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006248 RTC_DCHECK(dtls_transport);
6249 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006250 RTC_DCHECK(sctp_transport_);
6251 sctp_invoker_.reset(new rtc::AsyncInvoker());
6252 sctp_transport_->SignalReadyToSendData.connect(
6253 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6254 sctp_transport_->SignalDataReceived.connect(
6255 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006256 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6257 // another thread. Would be nice if there was a helper class similar to
6258 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6259 // code.
6260 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6261 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6262 sctp_transport_->SignalClosingProcedureComplete.connect(
6263 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006264 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006265 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006266 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006267}
6268
6269void PeerConnection::DestroySctpTransport_n() {
6270 RTC_DCHECK(network_thread()->IsCurrent());
6271 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006272 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006273 sctp_invoker_.reset(nullptr);
6274 sctp_ready_to_send_data_ = false;
6275}
6276
6277void PeerConnection::OnSctpTransportReadyToSendData_n() {
6278 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6279 RTC_DCHECK(network_thread()->IsCurrent());
6280 // Note: Cannot use rtc::Bind here because it will grab a reference to
6281 // PeerConnection and potentially cause PeerConnection to live longer than
6282 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6283 // be destroyed before PeerConnection is destroyed, and at that point all
6284 // pending tasks will be cleared.
6285 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6286 OnSctpTransportReadyToSendData_s(true);
6287 });
6288}
6289
6290void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6291 RTC_DCHECK(signaling_thread()->IsCurrent());
6292 sctp_ready_to_send_data_ = ready;
6293 SignalSctpReadyToSendData(ready);
6294}
6295
6296void PeerConnection::OnSctpTransportDataReceived_n(
6297 const cricket::ReceiveDataParams& params,
6298 const rtc::CopyOnWriteBuffer& payload) {
6299 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6300 RTC_DCHECK(network_thread()->IsCurrent());
6301 // Note: Cannot use rtc::Bind here because it will grab a reference to
6302 // PeerConnection and potentially cause PeerConnection to live longer than
6303 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6304 // be destroyed before PeerConnection is destroyed, and at that point all
6305 // pending tasks will be cleared.
6306 sctp_invoker_->AsyncInvoke<void>(
6307 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6308 OnSctpTransportDataReceived_s(params, payload);
6309 });
6310}
6311
6312void PeerConnection::OnSctpTransportDataReceived_s(
6313 const cricket::ReceiveDataParams& params,
6314 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006315 RTC_DCHECK_RUN_ON(signaling_thread());
6316 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006317 SignalSctpDataReceived(params, payload);
6318 }
6319}
6320
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006321void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006322 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6323 RTC_DCHECK(network_thread()->IsCurrent());
6324 sctp_invoker_->AsyncInvoke<void>(
6325 RTC_FROM_HERE, signaling_thread(),
6326 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006327 &SignalSctpClosingProcedureStartedRemotely, sid));
6328}
6329
6330void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6331 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6332 RTC_DCHECK(network_thread()->IsCurrent());
6333 sctp_invoker_->AsyncInvoke<void>(
6334 RTC_FROM_HERE, signaling_thread(),
6335 rtc::Bind(&sigslot::signal1<int>::operator(),
6336 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006337}
6338
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006339bool PeerConnection::SetupMediaTransportForDataChannels_n(
6340 const std::string& mid) {
6341 media_transport_ = transport_controller_->GetMediaTransport(mid);
6342 if (!media_transport_) {
6343 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6344 return false;
6345 }
6346
6347 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6348 media_transport_->SetDataSink(this);
6349 media_transport_data_mid_ = mid;
6350 transport_controller_->SignalMediaTransportStateChanged.connect(
6351 this, &PeerConnection::OnMediaTransportStateChanged_n);
6352 // Check the initial state right away, in case transport is already writable.
6353 OnMediaTransportStateChanged_n();
6354 return true;
6355}
6356
6357void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6358 if (!media_transport_) {
6359 return;
6360 }
6361 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6362 media_transport_data_mid_.reset();
6363 media_transport_->SetDataSink(nullptr);
6364 media_transport_invoker_ = nullptr;
6365 media_transport_ = nullptr;
6366}
6367
6368void PeerConnection::OnMediaTransportStateChanged_n() {
6369 if (!media_transport_data_mid_ ||
6370 transport_controller_->GetMediaTransportState(
6371 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6372 return;
6373 }
6374 media_transport_invoker_->AsyncInvoke<void>(
6375 RTC_FROM_HERE, signaling_thread(), [this] {
6376 RTC_DCHECK_RUN_ON(signaling_thread());
6377 media_transport_ready_to_send_data_ = true;
6378 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6379 });
6380}
6381
Steve Anton75737c02017-11-06 10:37:17 -08006382// Returns false if bundle is enabled and rtcp_mux is disabled.
6383bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6384 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6385 if (!bundle_enabled)
6386 return true;
6387
6388 const cricket::ContentGroup* bundle_group =
6389 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6390 RTC_DCHECK(bundle_group != NULL);
6391
6392 const cricket::ContentInfos& contents = desc->contents();
6393 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6394 citer != contents.end(); ++citer) {
6395 const cricket::ContentInfo* content = (&*citer);
6396 RTC_DCHECK(content != NULL);
6397 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006398 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006399 if (!HasRtcpMuxEnabled(content))
6400 return false;
6401 }
6402 }
6403 // RTCP-MUX is enabled in all the contents.
6404 return true;
6405}
6406
6407bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006408 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006409}
6410
Steve Anton06817cd2018-12-18 15:55:30 -08006411static RTCError ValidateMids(const cricket::SessionDescription& description) {
6412 std::set<std::string> mids;
6413 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006414 if (content.name.empty()) {
6415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6416 "A media section is missing a MID attribute.");
6417 }
Steve Anton06817cd2018-12-18 15:55:30 -08006418 if (!mids.insert(content.name).second) {
6419 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6420 "Duplicate a=mid value '" + content.name + "'.");
6421 }
6422 }
6423 return RTCError::OK();
6424}
6425
Steve Anton8a006912017-12-04 15:25:56 -08006426RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006427 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006428 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006429 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006430 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006431 }
6432
6433 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006434 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006435 }
6436
Steve Anton3828c062017-12-06 10:34:51 -08006437 SdpType type = sdesc->GetType();
6438 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6439 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006440 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006441 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006442 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006443 }
6444
Steve Anton06817cd2018-12-18 15:55:30 -08006445 RTCError error = ValidateMids(*sdesc->description());
6446 if (!error.ok()) {
6447 return error;
6448 }
6449
Steve Anton75737c02017-11-06 10:37:17 -08006450 // Verify crypto settings.
6451 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006452 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6453 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006454 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006455 if (!crypto_error.ok()) {
6456 return crypto_error;
6457 }
Steve Anton75737c02017-11-06 10:37:17 -08006458 }
6459
6460 // Verify ice-ufrag and ice-pwd.
6461 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006462 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6463 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006464 }
6465
6466 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006467 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6468 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006469 }
6470
6471 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6472 // m-lines that do not rtcp-mux enabled.
6473
6474 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006475 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006476 // With an answer we want to compare the new answer session description with
6477 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006478 const cricket::SessionDescription* offer_desc =
6479 (source == cricket::CS_LOCAL) ? remote_description()->description()
6480 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006481 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6482 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6483 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006484 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6485 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006486 }
6487 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006488 // The re-offers should respect the order of m= sections in current
6489 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006490 // With a re-offer, either the current local or current remote descriptions
6491 // could be the most up to date, so we would like to check against both of
6492 // them if they exist. It could be the case that one of them has a 0 port
6493 // for a media section, but the other does not. This is important to check
6494 // against in the case that we are recycling an m= section.
6495 const cricket::SessionDescription* current_desc = nullptr;
6496 const cricket::SessionDescription* secondary_current_desc = nullptr;
6497 if (local_description()) {
6498 current_desc = local_description()->description();
6499 if (remote_description()) {
6500 secondary_current_desc = remote_description()->description();
6501 }
6502 } else if (remote_description()) {
6503 current_desc = remote_description()->description();
6504 }
Steve Anton75737c02017-11-06 10:37:17 -08006505 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006506 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6507 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006508 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6509 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006510 }
6511 }
6512
Steve Antonba42e992018-04-09 14:10:01 -07006513 if (IsUnifiedPlan()) {
6514 // Ensure that each audio and video media section has at most one
6515 // "StreamParams". This will return an error if receiving a session
6516 // description from a "Plan B" endpoint which adds multiple tracks of the
6517 // same type. With Unified Plan, there can only be at most one track per
6518 // media section.
6519 for (const ContentInfo& content : sdesc->description()->contents()) {
6520 const MediaContentDescription& desc = *content.description;
6521 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6522 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6523 desc.streams().size() > 1u) {
6524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6525 "Media section has more than one track specified "
6526 "with a=ssrc lines which is not supported with "
6527 "Unified Plan.");
6528 }
6529 }
6530 }
6531
Steve Anton8a006912017-12-04 15:25:56 -08006532 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006533}
6534
Steve Anton3828c062017-12-06 10:34:51 -08006535bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006536 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006537 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006538 return (state == PeerConnectionInterface::kStable) ||
6539 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006540 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006541 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006542 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6543 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6544 }
6545}
6546
Steve Anton3828c062017-12-06 10:34:51 -08006547bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006548 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006549 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006550 return (state == PeerConnectionInterface::kStable) ||
6551 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006552 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006553 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006554 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6555 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6556 }
6557}
6558
Steve Antonf8470812017-12-04 10:46:21 -08006559const char* PeerConnection::SessionErrorToString(SessionError error) const {
6560 switch (error) {
6561 case SessionError::kNone:
6562 return "ERROR_NONE";
6563 case SessionError::kContent:
6564 return "ERROR_CONTENT";
6565 case SessionError::kTransport:
6566 return "ERROR_TRANSPORT";
6567 }
6568 RTC_NOTREACHED();
6569 return "";
6570}
6571
Steve Anton75737c02017-11-06 10:37:17 -08006572std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006573 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006574 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6575 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006576 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006577}
6578
Steve Anton8e20f172018-03-06 10:55:04 -08006579void PeerConnection::ReportSdpFormatReceived(
6580 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006581 int num_audio_mlines = 0;
6582 int num_video_mlines = 0;
6583 int num_audio_tracks = 0;
6584 int num_video_tracks = 0;
6585 for (const ContentInfo& content : remote_offer.description()->contents()) {
6586 cricket::MediaType media_type = content.media_description()->type();
6587 int num_tracks = std::max(
6588 1, static_cast<int>(content.media_description()->streams().size()));
6589 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6590 num_audio_mlines += 1;
6591 num_audio_tracks += num_tracks;
6592 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6593 num_video_mlines += 1;
6594 num_video_tracks += num_tracks;
6595 }
6596 }
6597 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6598 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6599 format = kSdpFormatReceivedComplexUnifiedPlan;
6600 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6601 format = kSdpFormatReceivedComplexPlanB;
6602 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6603 format = kSdpFormatReceivedSimple;
6604 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006605 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6606 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006607}
6608
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006609void PeerConnection::NoteUsageEvent(UsageEvent event) {
6610 RTC_DCHECK_RUN_ON(signaling_thread());
6611 usage_event_accumulator_ |= static_cast<int>(event);
6612}
6613
6614void PeerConnection::ReportUsagePattern() const {
6615 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006616 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6617 usage_event_accumulator_,
6618 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006619 const int bad_bits =
6620 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6621 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6622 const int good_bits =
6623 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6624 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6625 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6626 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6627 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006628 // If called after close(), we can't report, because observer may have
6629 // been deallocated, and therefore pointer is null. Write to log instead.
6630 if (observer_) {
6631 Observer()->OnInterestingUsage(usage_event_accumulator_);
6632 } else {
6633 RTC_LOG(LS_INFO) << "Interesting usage signature "
6634 << usage_event_accumulator_
6635 << " observed after observer shutdown";
6636 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006637 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006638}
6639
Steve Anton0ffaaa22018-02-23 10:31:30 -08006640void PeerConnection::ReportNegotiatedSdpSemantics(
6641 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006642 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006643 switch (answer.description()->msid_signaling()) {
6644 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006645 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006646 break;
6647 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006648 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006649 break;
6650 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006651 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006652 break;
6653 case cricket::kMsidSignalingMediaSection |
6654 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006655 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006656 break;
6657 default:
6658 RTC_NOTREACHED();
6659 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006660 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6661 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006662}
6663
Steve Anton75737c02017-11-06 10:37:17 -08006664// We need to check the local/remote description for the Transport instead of
6665// the session, because a new Transport added during renegotiation may have
6666// them unset while the session has them set from the previous negotiation.
6667// Not doing so may trigger the auto generation of transport description and
6668// mess up DTLS identity information, ICE credential, etc.
6669bool PeerConnection::ReadyToUseRemoteCandidate(
6670 const IceCandidateInterface* candidate,
6671 const SessionDescriptionInterface* remote_desc,
6672 bool* valid) {
6673 *valid = true;
6674
6675 const SessionDescriptionInterface* current_remote_desc =
6676 remote_desc ? remote_desc : remote_description();
6677
6678 if (!current_remote_desc) {
6679 return false;
6680 }
6681
6682 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6683 size_t remote_content_size =
6684 current_remote_desc->description()->contents().size();
6685 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006686 RTC_LOG(LS_ERROR)
6687 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6688 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006689
6690 *valid = false;
6691 return false;
6692 }
6693
6694 cricket::ContentInfo content =
6695 current_remote_desc->description()->contents()[mediacontent_index];
6696
6697 const std::string transport_name = GetTransportName(content.name);
6698 if (transport_name.empty()) {
6699 return false;
6700 }
Zhi Huange830e682018-03-30 10:48:35 -07006701 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006702}
6703
6704bool PeerConnection::SrtpRequired() const {
6705 return dtls_enabled_ ||
6706 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6707}
6708
6709void PeerConnection::OnTransportControllerGatheringState(
6710 cricket::IceGatheringState state) {
6711 RTC_DCHECK(signaling_thread()->IsCurrent());
6712 if (state == cricket::kIceGatheringGathering) {
6713 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6714 } else if (state == cricket::kIceGatheringComplete) {
6715 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6716 }
6717}
6718
6719void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006720 std::map<std::string, std::set<cricket::MediaType>>
6721 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006722 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006723 if (transceiver->internal()->channel()) {
6724 const std::string& transport_name =
6725 transceiver->internal()->channel()->transport_name();
6726 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006727 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006728 }
Steve Anton75737c02017-11-06 10:37:17 -08006729 }
6730 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006731 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6732 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006733 }
Zhi Huange830e682018-03-30 10:48:35 -07006734
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006735 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006736 if (transport_name) {
6737 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006738 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006739 }
Zhi Huange830e682018-03-30 10:48:35 -07006740
Steve Antonc7b964c2018-02-01 14:39:45 -08006741 for (const auto& entry : media_types_by_transport_name) {
6742 const std::string& transport_name = entry.first;
6743 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006744 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006745 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006746 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006747 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006748 }
6749 }
6750}
6751// Walk through the ConnectionInfos to gather best connection usage
6752// for IPv4 and IPv6.
6753void PeerConnection::ReportBestConnectionState(
6754 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006755 for (const cricket::TransportChannelStats& channel_stats :
6756 stats.channel_stats) {
6757 for (const cricket::ConnectionInfo& connection_info :
6758 channel_stats.connection_infos) {
6759 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006760 continue;
6761 }
6762
Steve Antonc7b964c2018-02-01 14:39:45 -08006763 const cricket::Candidate& local = connection_info.local_candidate;
6764 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006765
6766 // Increment the counter for IceCandidatePairType.
6767 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6768 (local.type() == RELAY_PORT_TYPE &&
6769 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006770 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6771 GetIceCandidatePairCounter(local, remote),
6772 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006773 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006774 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6775 GetIceCandidatePairCounter(local, remote),
6776 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006777 } else {
6778 RTC_CHECK(0);
6779 }
Steve Anton75737c02017-11-06 10:37:17 -08006780
6781 // Increment the counter for IP type.
6782 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006783 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6784 kBestConnections_IPv4,
6785 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006786 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006787 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6788 kBestConnections_IPv6,
6789 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006790 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006791 RTC_CHECK(!local.address().hostname().empty() &&
6792 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006793 }
6794
6795 return;
6796 }
6797 }
6798}
6799
6800void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006801 const cricket::TransportStats& stats,
6802 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006803 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6804 return;
6805 }
6806
6807 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6808 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6809 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6810 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6811 return;
6812 }
6813
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006814 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6815 for (cricket::MediaType media_type : media_types) {
6816 switch (media_type) {
6817 case cricket::MEDIA_TYPE_AUDIO:
6818 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6819 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6820 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6821 break;
6822 case cricket::MEDIA_TYPE_VIDEO:
6823 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6824 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6825 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6826 break;
6827 case cricket::MEDIA_TYPE_DATA:
6828 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6829 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6830 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6831 break;
6832 default:
6833 RTC_NOTREACHED();
6834 continue;
6835 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006836 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006837 }
6838
6839 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6840 for (cricket::MediaType media_type : media_types) {
6841 switch (media_type) {
6842 case cricket::MEDIA_TYPE_AUDIO:
6843 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6844 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6845 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6846 break;
6847 case cricket::MEDIA_TYPE_VIDEO:
6848 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6849 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6850 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6851 break;
6852 case cricket::MEDIA_TYPE_DATA:
6853 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6854 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6855 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6856 break;
6857 default:
6858 RTC_NOTREACHED();
6859 continue;
6860 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006861 }
Steve Anton75737c02017-11-06 10:37:17 -08006862 }
6863}
6864
6865void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6866 RTC_DCHECK(worker_thread()->IsCurrent());
6867 RTC_DCHECK(call_);
6868 call_->OnSentPacket(sent_packet);
6869}
6870
6871const std::string PeerConnection::GetTransportName(
6872 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006873 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006874 if (channel) {
6875 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006876 }
Steve Anton6fec8802017-12-04 10:37:29 -08006877 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006878 RTC_DCHECK(sctp_mid_);
6879 if (content_name == *sctp_mid_) {
6880 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006881 }
6882 }
6883 // Return an empty string if failed to retrieve the transport name.
6884 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006885}
6886
Steve Anton6fec8802017-12-04 10:37:29 -08006887void PeerConnection::DestroyTransceiverChannel(
6888 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6889 transceiver) {
6890 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006891
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006892 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006893 if (channel) {
6894 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006895 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006896 }
6897}
6898
6899void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006900 if (rtp_data_channel_) {
6901 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006902 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006903 rtp_data_channel_ = nullptr;
6904 }
6905
6906 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6907 // grab a reference to this PeerConnection. If this is called from the
6908 // PeerConnection destructor, the RefCountedObject vtable will have already
6909 // been destroyed (since it is a subclass of PeerConnection) and using
6910 // rtc::Bind will cause "Pure virtual function called" error to appear.
6911
6912 if (sctp_transport_) {
6913 OnDataChannelDestroyed();
6914 network_thread()->Invoke<void>(RTC_FROM_HERE,
6915 [this] { DestroySctpTransport_n(); });
6916 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006917
6918 if (media_transport_) {
6919 OnDataChannelDestroyed();
6920 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6921 RTC_DCHECK_RUN_ON(network_thread());
6922 TeardownMediaTransportForDataChannels_n();
6923 });
6924 }
Steve Anton6fec8802017-12-04 10:37:29 -08006925}
6926
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006927void PeerConnection::DestroyChannelInterface(
6928 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006929 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006930 switch (channel->media_type()) {
6931 case cricket::MEDIA_TYPE_AUDIO:
6932 channel_manager()->DestroyVoiceChannel(
6933 static_cast<cricket::VoiceChannel*>(channel));
6934 break;
6935 case cricket::MEDIA_TYPE_VIDEO:
6936 channel_manager()->DestroyVideoChannel(
6937 static_cast<cricket::VideoChannel*>(channel));
6938 break;
6939 case cricket::MEDIA_TYPE_DATA:
6940 channel_manager()->DestroyRtpDataChannel(
6941 static_cast<cricket::RtpDataChannel*>(channel));
6942 break;
6943 default:
6944 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6945 break;
6946 }
Zhi Huange830e682018-03-30 10:48:35 -07006947}
Steve Anton6fec8802017-12-04 10:37:29 -08006948
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006949bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006950 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006951 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006952 cricket::DtlsTransportInternal* dtls_transport,
6953 MediaTransportInterface* media_transport) {
Karl Wiberg5966c502019-02-21 23:55:09 +01006954 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006955 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006956 auto base_channel = GetChannel(mid);
6957 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006958 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006959 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006960 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006961 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006962 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006963
Karl Wiberg5966c502019-02-21 23:55:09 +01006964 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006965 // Only pass media transport to call object if media transport is used
6966 // for media (and not data channel).
6967 call_->MediaTransportChange(media_transport);
6968 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006969
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006970 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006971}
6972
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006973PeerConnectionObserver* PeerConnection::Observer() const {
6974 // In earlier production code, the pointer was not cleared on close,
6975 // which might have led to undefined behavior if the observer was not
6976 // deallocated, or strange crashes if it was.
6977 // We use CHECK in order to catch such behavior if it exists.
6978 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6979 RTC_CHECK(observer_);
6980 return observer_;
6981}
6982
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006983CryptoOptions PeerConnection::GetCryptoOptions() {
6984 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6985 // after it has been removed.
6986 return configuration_.crypto_options.has_value()
6987 ? *configuration_.crypto_options
6988 : factory_->options().crypto_options;
6989}
6990
Harald Alvestrand89061872018-01-02 14:08:34 +01006991void PeerConnection::ClearStatsCache() {
6992 if (stats_collector_) {
6993 stats_collector_->ClearCachedStatsReport();
6994 }
6995}
6996
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006997void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006998 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6999 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007000}
7001
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007002} // namespace webrtc