blob: 10aa21e902feee3dbb7bfce947cf2394d84c8d17 [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());
Peter Boström1a9d6152015-12-08 22:15:17 +0100903 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700904
905 RTCError config_error = ValidateConfiguration(configuration);
906 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700908 return false;
909 }
910
Benjamin Wrightcab58882018-05-02 15:12:47 -0700911 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR)
913 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100914 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800915 return false;
916 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200917
Benjamin Wrightcab58882018-05-02 15:12:47 -0700918 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800919 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100920 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100921 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800922 return false;
923 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700924
Benjamin Wrightcab58882018-05-02 15:12:47 -0700925 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700926 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700927 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700928 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800929
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200930 cricket::ServerAddresses stun_servers;
931 std::vector<cricket::RelayServerConfig> turn_servers;
932
933 RTCErrorType parse_error =
934 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
935 if (parse_error != RTCErrorType::NONE) {
936 return false;
937 }
938
deadbeef91dd5672016-05-18 16:55:30 -0700939 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700940 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700941 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200942 RTC_FROM_HERE,
943 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
944 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 return false;
946 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200947 // If initialization was successful, note if STUN or TURN servers
948 // were supplied.
949 if (!stun_servers.empty()) {
950 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
951 }
952 if (!turn_servers.empty()) {
953 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
954 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700956 // Send information about IPv4/IPv6 status.
957 PeerConnectionAddressFamilyCounter address_family;
958 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
959 address_family = kPeerConnection_IPv6;
960 } else {
961 address_family = kPeerConnection_IPv4;
962 }
963 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
964 kPeerConnectionAddressFamilyCounter_Max);
965
Zhi Huange830e682018-03-30 10:48:35 -0700966 const PeerConnectionFactoryInterface::Options& options = factory_->options();
967
Steve Anton75737c02017-11-06 10:37:17 -0800968 // RFC 3264: The numeric value of the session id and version in the
969 // o line MUST be representable with a "64 bit signed integer".
970 // Due to this constraint session id |session_id_| is max limited to
971 // LLONG_MAX.
972 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700973 JsepTransportController::Config config;
974 config.redetermine_role_on_ice_restart =
975 configuration.redetermine_role_on_ice_restart;
976 config.ssl_max_version = factory_->options().ssl_max_version;
977 config.disable_encryption = options.disable_encryption;
978 config.bundle_policy = configuration.bundle_policy;
979 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700980 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
981 // stub.
982 config.crypto_options = configuration.crypto_options.has_value()
983 ? *configuration.crypto_options
984 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700985 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +0100986 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -0700987#if defined(ENABLE_EXTERNAL_AUTH)
988 config.enable_external_auth = true;
989#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700990 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700991
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700992 if (configuration.use_media_transport ||
993 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700994 if (!factory_->media_transport_factory()) {
995 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700996 << "PeerConnecton is initialized with use_media_transport = true or "
997 << "use_media_transport_for_data_channels = true "
998 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700999 return false;
1000 }
1001
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001002 config.use_media_transport_for_media = configuration.use_media_transport;
1003 config.use_media_transport_for_data_channels =
1004 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001005 config.media_transport_factory = factory_->media_transport_factory();
1006 }
1007
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001009 signaling_thread(), network_thread(), port_allocator_.get(),
1010 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001011 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001012 this, &PeerConnection::OnTransportControllerConnectionState);
1013 transport_controller_->SignalStandardizedIceConnectionState.connect(
1014 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001015 transport_controller_->SignalConnectionState.connect(
1016 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001017 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001018 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001021 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001022 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1023 transport_controller_->SignalDtlsHandshakeError.connect(
1024 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1025
1026 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001027
deadbeefab9b2d12015-10-14 11:33:11 -07001028 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001029 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
Steve Antonba818672017-11-06 10:21:57 -08001031 configuration_ = configuration;
1032
Steve Anton75737c02017-11-06 10:37:17 -08001033 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1034 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1035 if (!configuration.certificates.empty()) {
1036 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1037 // just picking the first one. The decision should be made based on the DTLS
1038 // handshake. The DTLS negotiations need to know about all certificates.
1039 certificate = configuration.certificates[0];
1040 }
1041
Steve Antond25da372017-11-06 14:50:29 -08001042 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001043
1044 if (options.disable_encryption) {
1045 dtls_enabled_ = false;
1046 } else {
1047 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001048 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001049 // |configuration| can override the default |dtls_enabled_| value.
1050 if (configuration.enable_dtls_srtp) {
1051 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1052 }
1053 }
1054
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001055 if (configuration.use_media_transport_for_data_channels) {
1056 if (configuration.enable_rtp_data_channel) {
1057 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1058 "use_media_transport_for_data_channels are "
1059 "incompatible and cannot both be set to true";
1060 return false;
1061 }
1062 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1063 } else if (configuration.enable_rtp_data_channel) {
1064 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1065 // set. It takes precendence over the disable_sctp_data_channels
1066 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001067 data_channel_type_ = cricket::DCT_RTP;
1068 } else {
1069 // DTLS has to be enabled to use SCTP.
1070 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1071 data_channel_type_ = cricket::DCT_SCTP;
1072 }
1073 }
1074
1075 video_options_.screencast_min_bitrate_kbps =
1076 configuration.screencast_min_bitrate;
1077 audio_options_.combined_audio_video_bwe =
1078 configuration.combined_audio_video_bwe;
1079
1080 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001081 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001082
1083 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001084 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001085
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001086 audio_options_.audio_jitter_buffer_min_delay_ms =
1087 configuration.audio_jitter_buffer_min_delay_ms;
1088
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001089 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1090 configuration.audio_jitter_buffer_enable_rtx_handling;
1091
Steve Anton75737c02017-11-06 10:37:17 -08001092 // Whether the certificate generator/certificate is null or not determines
1093 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1094 // the right instructions by clearing the variables if needed.
1095 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001096 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001097 certificate = nullptr;
1098 } else if (certificate) {
1099 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001100 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001101 }
1102
1103 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1104 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001105 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001106 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1107 this, &PeerConnection::OnCertificateReady);
1108
1109 if (options.disable_encryption) {
1110 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1111 }
1112
1113 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001114 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001115 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116
Steve Anton4171afb2017-11-20 10:20:22 -08001117 // Add default audio/video transceivers for Plan B SDP.
1118 if (!IsUnifiedPlan()) {
1119 transceivers_.push_back(
1120 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1121 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1122 transceivers_.push_back(
1123 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1124 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1125 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001126 int delay_ms =
1127 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001128 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1129 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 return true;
1131}
1132
Steve Anton038834f2017-07-14 15:59:59 -07001133RTCError PeerConnection::ValidateConfiguration(
1134 const RTCConfiguration& config) const {
1135 if (config.ice_regather_interval_range &&
1136 config.continual_gathering_policy == GATHER_ONCE) {
1137 return RTCError(RTCErrorType::INVALID_PARAMETER,
1138 "ice_regather_interval_range specified but continual "
1139 "gathering policy is GATHER_ONCE");
1140 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001141 auto result =
1142 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1143 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001144}
1145
Yves Gerey665174f2018-06-19 15:03:05 +02001146rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001147 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1148 "Plan SdpSemantics. Please use GetSenders "
1149 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001150 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151}
1152
Yves Gerey665174f2018-06-19 15:03:05 +02001153rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001154 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1155 "Plan SdpSemantics. Please use GetReceivers "
1156 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001157 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158}
1159
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001160bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001161 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001162 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1163 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001164 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 if (IsClosed()) {
1166 return false;
1167 }
deadbeefab9b2d12015-10-14 11:33:11 -07001168 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 return false;
1170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171
1172 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001173 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1174 observer->SignalAudioTrackAdded.connect(this,
1175 &PeerConnection::OnAudioTrackAdded);
1176 observer->SignalAudioTrackRemoved.connect(
1177 this, &PeerConnection::OnAudioTrackRemoved);
1178 observer->SignalVideoTrackAdded.connect(this,
1179 &PeerConnection::OnVideoTrackAdded);
1180 observer->SignalVideoTrackRemoved.connect(
1181 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001182 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001183
deadbeefab9b2d12015-10-14 11:33:11 -07001184 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001185 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001186 }
1187 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001188 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001189 }
1190
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001191 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001192 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 return true;
1194}
1195
1196void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001197 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001198 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1199 "Plan SdpSemantics. Please use RemoveTrack "
1200 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001201 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001202 if (!IsClosed()) {
1203 for (const auto& track : local_stream->GetAudioTracks()) {
1204 RemoveAudioTrack(track.get(), local_stream);
1205 }
1206 for (const auto& track : local_stream->GetVideoTracks()) {
1207 RemoveVideoTrack(track.get(), local_stream);
1208 }
deadbeefab9b2d12015-10-14 11:33:11 -07001209 }
deadbeefab9b2d12015-10-14 11:33:11 -07001210 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001211 stream_observers_.erase(
1212 std::remove_if(
1213 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001214 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001215 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001216 }),
1217 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219 if (IsClosed()) {
1220 return;
1221 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001222 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223}
1224
Steve Anton2d6c76a2018-01-05 17:10:52 -08001225RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001228 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001229 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001230 if (!track) {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1232 }
1233 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1234 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1236 "Track has invalid kind: " + track->kind());
1237 }
Steve Antonf9381f02017-12-14 10:23:57 -08001238 if (IsClosed()) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1240 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001241 }
Steve Anton4171afb2017-11-20 10:20:22 -08001242 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001243 LOG_AND_RETURN_ERROR(
1244 RTCErrorType::INVALID_PARAMETER,
1245 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001246 }
Steve Antonf9381f02017-12-14 10:23:57 -08001247 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001248 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1249 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001250 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001251 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001252 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001253 }
1254 return sender_or_error;
1255}
deadbeefe1f9d832016-01-14 15:35:42 -08001256
Steve Antonf9381f02017-12-14 10:23:57 -08001257RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1258PeerConnection::AddTrackPlanB(
1259 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001260 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001261 if (stream_ids.size() > 1u) {
1262 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1263 "AddTrack with more than one stream is not "
1264 "supported with Plan B semantics.");
1265 }
1266 std::vector<std::string> adjusted_stream_ids = stream_ids;
1267 if (adjusted_stream_ids.empty()) {
1268 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1269 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001270 cricket::MediaType media_type =
1271 (track->kind() == MediaStreamTrackInterface::kAudioKind
1272 ? cricket::MEDIA_TYPE_AUDIO
1273 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001274 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001275 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001276 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001277 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001278 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001279 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001280 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001281 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001282 if (sender_info) {
1283 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001284 }
Steve Antonf9381f02017-12-14 10:23:57 -08001285 } else {
1286 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001287 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001288 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001289 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001290 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001291 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001292 if (sender_info) {
1293 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001294 }
deadbeefe1f9d832016-01-14 15:35:42 -08001295 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001296 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001297}
deadbeefe1f9d832016-01-14 15:35:42 -08001298
Steve Antonf9381f02017-12-14 10:23:57 -08001299RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1300PeerConnection::AddTrackUnifiedPlan(
1301 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001302 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001303 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1304 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001305 RTC_LOG(LS_INFO) << "Reusing an existing "
1306 << cricket::MediaTypeToString(transceiver->media_type())
1307 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001309 transceiver->internal()->set_direction(
1310 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(
1313 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001314 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001315 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001316 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001317 } else {
1318 cricket::MediaType media_type =
1319 (track->kind() == MediaStreamTrackInterface::kAudioKind
1320 ? cricket::MEDIA_TYPE_AUDIO
1321 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001322 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1323 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001324 std::string sender_id = track->id();
1325 // Avoid creating a sender with an existing ID by generating a random ID.
1326 // This can happen if this is the second time AddTrack has created a sender
1327 // for this track.
1328 if (FindSenderById(sender_id)) {
1329 sender_id = rtc::CreateRandomUuid();
1330 }
Florent Castelli892acf02018-10-01 22:47:20 +02001331 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001332 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1333 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001334 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001335 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001336 }
Steve Antonf9381f02017-12-14 10:23:57 -08001337 return transceiver->sender();
1338}
1339
1340rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1341PeerConnection::FindFirstTransceiverForAddedTrack(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1343 RTC_DCHECK(track);
1344 for (auto transceiver : transceivers_) {
1345 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001346 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001347 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001348 !transceiver->internal()->has_ever_been_used_to_send() &&
1349 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001350 return transceiver;
1351 }
1352 }
1353 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001354}
1355
1356bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1357 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001358 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001359}
1360
Steve Anton24db5732018-07-23 10:27:33 -07001361RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001362 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001363 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001364 if (!sender) {
1365 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1366 }
deadbeefe1f9d832016-01-14 15:35:42 -08001367 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001368 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1369 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001370 }
Steve Antonf9381f02017-12-14 10:23:57 -08001371 if (IsUnifiedPlan()) {
1372 auto transceiver = FindTransceiverBySender(sender);
1373 if (!transceiver || !sender->track()) {
1374 return RTCError::OK();
1375 }
1376 sender->SetTrack(nullptr);
1377 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001378 transceiver->internal()->set_direction(
1379 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001381 transceiver->internal()->set_direction(
1382 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 }
Steve Anton4171afb2017-11-20 10:20:22 -08001384 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001385 bool removed;
1386 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1387 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1388 } else {
1389 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1390 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1391 }
1392 if (!removed) {
1393 LOG_AND_RETURN_ERROR(
1394 RTCErrorType::INVALID_PARAMETER,
1395 "Couldn't find sender " + sender->id() + " to remove.");
1396 }
Steve Anton4171afb2017-11-20 10:20:22 -08001397 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001398 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001399 return RTCError::OK();
1400}
1401
1402rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1403PeerConnection::FindTransceiverBySender(
1404 rtc::scoped_refptr<RtpSenderInterface> sender) {
1405 for (auto transceiver : transceivers_) {
1406 if (transceiver->sender() == sender) {
1407 return transceiver;
1408 }
1409 }
1410 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001411}
1412
Steve Anton9158ef62017-11-27 13:01:52 -08001413RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1414PeerConnection::AddTransceiver(
1415 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1416 return AddTransceiver(track, RtpTransceiverInit());
1417}
1418
1419RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1420PeerConnection::AddTransceiver(
1421 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1422 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001423 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001424 RTC_CHECK(IsUnifiedPlan())
1425 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (!track) {
1427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1428 }
1429 cricket::MediaType media_type;
1430 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1431 media_type = cricket::MEDIA_TYPE_AUDIO;
1432 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1433 media_type = cricket::MEDIA_TYPE_VIDEO;
1434 } else {
1435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1436 "Track kind is not audio or video");
1437 }
1438 return AddTransceiver(media_type, track, init);
1439}
1440
1441RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1442PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1443 return AddTransceiver(media_type, RtpTransceiverInit());
1444}
1445
1446RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1447PeerConnection::AddTransceiver(cricket::MediaType media_type,
1448 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001449 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001450 RTC_CHECK(IsUnifiedPlan())
1451 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001452 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1453 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1455 "media type is not audio or video");
1456 }
1457 return AddTransceiver(media_type, nullptr, init);
1458}
1459
1460RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1461PeerConnection::AddTransceiver(
1462 cricket::MediaType media_type,
1463 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001464 const RtpTransceiverInit& init,
1465 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001466 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1467 media_type == cricket::MEDIA_TYPE_VIDEO));
1468 if (track) {
1469 RTC_DCHECK_EQ(media_type,
1470 (track->kind() == MediaStreamTrackInterface::kAudioKind
1471 ? cricket::MEDIA_TYPE_AUDIO
1472 : cricket::MEDIA_TYPE_VIDEO));
1473 }
1474
Amit Hilbuchaa584152019-02-06 17:09:52 -08001475 size_t num_rids = absl::c_count_if(init.send_encodings,
1476 [](const RtpEncodingParameters& encoding) {
1477 return !encoding.rid.empty();
1478 });
1479 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001480 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001481 RTCErrorType::INVALID_PARAMETER,
1482 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001483 }
1484
Amit Hilbuchaa584152019-02-06 17:09:52 -08001485 if (absl::c_any_of(init.send_encodings,
1486 [](const RtpEncodingParameters& encoding) {
1487 return encoding.ssrc.has_value();
1488 })) {
1489 LOG_AND_RETURN_ERROR(
1490 RTCErrorType::UNSUPPORTED_PARAMETER,
1491 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001492 }
1493
1494 RtpParameters parameters;
1495 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001496
1497 // Encodings are dropped from the tail if too many are provided.
1498 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1499 parameters.encodings.erase(
1500 parameters.encodings.begin() + kMaxSimulcastStreams,
1501 parameters.encodings.end());
1502 }
1503
1504 // Single RID should be removed.
1505 if (parameters.encodings.size() == 1 &&
1506 !parameters.encodings[0].rid.empty()) {
1507 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1508 parameters.encodings[0].rid.clear();
1509 }
1510
1511 // If RIDs were not provided, they are generated for simulcast scenario.
1512 if (parameters.encodings.size() > 1 && num_rids == 0) {
1513 rtc::UniqueStringGenerator rid_generator;
1514 for (RtpEncodingParameters& encoding : parameters.encodings) {
1515 encoding.rid = rid_generator();
1516 }
1517 }
1518
Florent Castelli892acf02018-10-01 22:47:20 +02001519 if (UnimplementedRtpParameterHasValue(parameters)) {
1520 LOG_AND_RETURN_ERROR(
1521 RTCErrorType::UNSUPPORTED_PARAMETER,
1522 "Attempted to set an unimplemented parameter of RtpParameters.");
1523 }
Steve Anton9158ef62017-11-27 13:01:52 -08001524
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001525 auto result = cricket::CheckRtpParametersValues(parameters);
1526 if (!result.ok()) {
1527 LOG_AND_RETURN_ERROR(result.type(), result.message());
1528 }
1529
Steve Anton3d954a62018-04-02 11:27:23 -07001530 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1531 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001532 // Set the sender ID equal to the track ID if the track is specified unless
1533 // that sender ID is already in use.
1534 std::string sender_id =
1535 (track && !FindSenderById(track->id()) ? track->id()
1536 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001537 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001538 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1540 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1541 transceiver->internal()->set_direction(init.direction);
1542
Steve Anton22da89f2018-01-25 13:58:07 -08001543 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001544 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001545 }
Steve Antonf9381f02017-12-14 10:23:57 -08001546
1547 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1548}
1549
Steve Anton02ee47c2018-01-10 16:26:06 -08001550rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1551PeerConnection::CreateSender(
1552 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001553 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001555 const std::vector<std::string>& stream_ids,
1556 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001557 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1559 RTC_DCHECK(!track ||
1560 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1561 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1562 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001563 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001564 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001565 } else {
1566 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1567 RTC_DCHECK(!track ||
1568 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1569 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001570 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001571 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001572 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001573 bool set_track_succeeded = sender->SetTrack(track);
1574 RTC_DCHECK(set_track_succeeded);
1575 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001576 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001577 return sender;
1578}
1579
1580rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1581PeerConnection::CreateReceiver(cricket::MediaType media_type,
1582 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001583 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1584 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001585 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001586 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001587 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1588 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001589 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001590 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001591 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001592 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001593 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1594 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001595 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001596 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001597 return receiver;
1598}
1599
1600rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1601PeerConnection::CreateAndAddTransceiver(
1602 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1603 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1604 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001605 // Ensure that the new sender does not have an ID that is already in use by
1606 // another sender.
1607 // Allow receiver IDs to conflict since those come from remote SDP (which
1608 // could be invalid, but should not cause a crash).
1609 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001610 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1611 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001612 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001613 transceiver->internal()->SignalNegotiationNeeded.connect(
1614 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001615 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001616}
1617
Steve Anton52d86772018-02-20 15:48:12 -08001618void PeerConnection::OnNegotiationNeeded() {
1619 RTC_DCHECK_RUN_ON(signaling_thread());
1620 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001621 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001622}
1623
deadbeeffac06552015-11-25 11:26:01 -08001624rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001625 const std::string& kind,
1626 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001627 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1628 "Plan SdpSemantics. Please use AddTransceiver "
1629 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001630 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001631 if (IsClosed()) {
1632 return nullptr;
1633 }
Steve Anton4171afb2017-11-20 10:20:22 -08001634
Seth Hampson5b4f0752018-04-02 16:31:36 -07001635 // Internally we need to have one stream with Plan B semantics, so we
1636 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001637 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001638 if (stream_id.empty()) {
1639 stream_ids.push_back(rtc::CreateRandomUuid());
1640 RTC_LOG(LS_INFO)
1641 << "No stream_id specified for sender. Generated stream ID: "
1642 << stream_ids[0];
1643 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001644 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001645 }
1646
Steve Anton4171afb2017-11-20 10:20:22 -08001647 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001648 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001649 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001650 auto* audio_sender = new AudioRtpSender(
1651 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001652 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001653 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001654 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001655 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001656 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001657 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001658 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001659 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001660 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001661 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001662 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001663 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001665 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001666 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001667 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001668
deadbeefe1f9d832016-01-14 15:35:42 -08001669 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001670}
1671
deadbeef70ab1a12015-09-28 16:53:55 -07001672std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1673 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001674 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001675 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001676 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001677 }
1678 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001679}
1680
Steve Anton4171afb2017-11-20 10:20:22 -08001681std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1682PeerConnection::GetSendersInternal() const {
1683 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1684 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001685 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001686 auto senders = transceiver->internal()->senders();
1687 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1688 }
1689 return all_senders;
1690}
1691
deadbeef70ab1a12015-09-28 16:53:55 -07001692std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1693PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001694 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001695 for (const auto& receiver : GetReceiversInternal()) {
1696 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001697 }
1698 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001699}
1700
Steve Anton4171afb2017-11-20 10:20:22 -08001701std::vector<
1702 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1703PeerConnection::GetReceiversInternal() const {
1704 std::vector<
1705 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1706 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001707 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001708 auto receivers = transceiver->internal()->receivers();
1709 all_receivers.insert(all_receivers.end(), receivers.begin(),
1710 receivers.end());
1711 }
1712 return all_receivers;
1713}
1714
Steve Anton9158ef62017-11-27 13:01:52 -08001715std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1716PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001717 RTC_CHECK(IsUnifiedPlan())
1718 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001719 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001720 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001721 all_transceivers.push_back(transceiver);
1722 }
1723 return all_transceivers;
1724}
1725
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001726bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001727 MediaStreamTrackInterface* track,
1728 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001729 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001730 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001731 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001732 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733 return false;
1734 }
1735
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001736 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001737 // The StatsCollector is used to tell if a track is valid because it may
1738 // remember tracks that the PeerConnection previously removed.
1739 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1741 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001742 return false;
1743 }
Steve Antonad182762018-09-05 20:22:40 +00001744 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1745 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 return true;
1747}
1748
hbos74e1a4f2016-09-15 23:33:01 -07001749void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001750 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001751 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001752 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001753 stats_collector_->GetStatsReport(callback);
1754}
1755
Henrik Boström1df1bf82018-03-20 13:24:20 +01001756void PeerConnection::GetStats(
1757 rtc::scoped_refptr<RtpSenderInterface> selector,
1758 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1759 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1760 RTC_DCHECK(callback);
1761 RTC_DCHECK(stats_collector_);
1762 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1763 if (selector) {
1764 for (const auto& proxy_transceiver : transceivers_) {
1765 for (const auto& proxy_sender :
1766 proxy_transceiver->internal()->senders()) {
1767 if (proxy_sender == selector) {
1768 internal_sender = proxy_sender->internal();
1769 break;
1770 }
1771 }
1772 if (internal_sender)
1773 break;
1774 }
1775 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001776 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001777 // belong to the PeerConnection (in Plan B, senders can be removed from the
1778 // PeerConnection). This means that "all the stats objects representing the
1779 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1780 // produces an empty stats report.
1781 stats_collector_->GetStatsReport(internal_sender, callback);
1782}
1783
1784void PeerConnection::GetStats(
1785 rtc::scoped_refptr<RtpReceiverInterface> selector,
1786 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1787 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1788 RTC_DCHECK(callback);
1789 RTC_DCHECK(stats_collector_);
1790 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1791 if (selector) {
1792 for (const auto& proxy_transceiver : transceivers_) {
1793 for (const auto& proxy_receiver :
1794 proxy_transceiver->internal()->receivers()) {
1795 if (proxy_receiver == selector) {
1796 internal_receiver = proxy_receiver->internal();
1797 break;
1798 }
1799 }
1800 if (internal_receiver)
1801 break;
1802 }
1803 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001804 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001805 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1806 // the PeerConnection). This means that "all the stats objects representing
1807 // the selector" is an empty set. Invoking GetStatsReport() with a null
1808 // selector produces an empty stats report.
1809 stats_collector_->GetStatsReport(internal_receiver, callback);
1810}
1811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001813 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 return signaling_state_;
1815}
1816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817PeerConnectionInterface::IceConnectionState
1818PeerConnection::ice_connection_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 ice_connection_state_;
1821}
1822
Alex Loiko9289eda2018-11-23 16:18:59 +00001823PeerConnectionInterface::IceConnectionState
1824PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001825 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001826 return standardized_ice_connection_state_;
1827}
1828
Jonas Olsson635474e2018-10-18 15:58:17 +02001829PeerConnectionInterface::PeerConnectionState
1830PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001831 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001832 return connection_state_;
1833}
1834
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835PeerConnectionInterface::IceGatheringState
1836PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001837 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 return ice_gathering_state_;
1839}
1840
Yves Gerey665174f2018-06-19 15:03:05 +02001841rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842 const std::string& label,
1843 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001844 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001845 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001846
deadbeefab9b2d12015-10-14 11:33:11 -07001847 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001848
kwibergd1fe2812016-04-27 06:47:29 -07001849 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001850 if (config) {
1851 internal_config.reset(new InternalDataChannelInit(*config));
1852 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001853 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001854 InternalCreateDataChannel(label, internal_config.get()));
1855 if (!channel.get()) {
1856 return nullptr;
1857 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001859 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1860 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001861 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001862 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001863 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001864 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 return DataChannelProxy::Create(signaling_thread(), channel.get());
1866}
1867
1868void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001869 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001870 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001871
nisse7ce109a2017-01-31 00:57:56 -08001872 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001873 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001874 return;
1875 }
deadbeefab9b2d12015-10-14 11:33:11 -07001876
Steve Anton8d3444d2017-10-20 15:30:51 -07001877 if (IsClosed()) {
1878 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001879 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001880 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001881 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001882 return;
1883 }
1884
zhihuang1c378ed2017-08-17 14:10:50 -07001885 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001886 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001887 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001888 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001889 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001890 return;
1891 }
1892
Steve Anton22da89f2018-01-25 13:58:07 -08001893 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1894 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1895 if (IsUnifiedPlan()) {
1896 RTCError error = HandleLegacyOfferOptions(options);
1897 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001898 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001899 return;
1900 }
1901 }
1902
zhihuang1c378ed2017-08-17 14:10:50 -07001903 cricket::MediaSessionOptions session_options;
1904 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001905 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906}
1907
Steve Anton22da89f2018-01-25 13:58:07 -08001908RTCError PeerConnection::HandleLegacyOfferOptions(
1909 const RTCOfferAnswerOptions& options) {
1910 RTC_DCHECK(IsUnifiedPlan());
1911
1912 if (options.offer_to_receive_audio == 0) {
1913 RemoveRecvDirectionFromReceivingTransceiversOfType(
1914 cricket::MEDIA_TYPE_AUDIO);
1915 } else if (options.offer_to_receive_audio == 1) {
1916 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1917 } else if (options.offer_to_receive_audio > 1) {
1918 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1919 "offer_to_receive_audio > 1 is not supported.");
1920 }
1921
1922 if (options.offer_to_receive_video == 0) {
1923 RemoveRecvDirectionFromReceivingTransceiversOfType(
1924 cricket::MEDIA_TYPE_VIDEO);
1925 } else if (options.offer_to_receive_video == 1) {
1926 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1927 } else if (options.offer_to_receive_video > 1) {
1928 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1929 "offer_to_receive_video > 1 is not supported.");
1930 }
1931
1932 return RTCError::OK();
1933}
1934
1935void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1936 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001937 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001938 RtpTransceiverDirection new_direction =
1939 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1940 if (new_direction != transceiver->direction()) {
1941 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1942 << " transceiver (MID="
1943 << transceiver->mid().value_or("<not set>") << ") from "
1944 << RtpTransceiverDirectionToString(
1945 transceiver->direction())
1946 << " to "
1947 << RtpTransceiverDirectionToString(new_direction)
1948 << " since CreateOffer specified offer_to_receive=0";
1949 transceiver->internal()->set_direction(new_direction);
1950 }
Steve Anton22da89f2018-01-25 13:58:07 -08001951 }
1952}
1953
1954void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1955 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001956 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08001957 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001958 RTC_LOG(LS_INFO)
1959 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1960 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001961 RtpTransceiverInit init;
1962 init.direction = RtpTransceiverDirection::kRecvOnly;
1963 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1964 }
1965}
1966
1967std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1968PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1969 std::vector<
1970 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1971 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001972 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001973 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001974 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1975 receiving_transceivers.push_back(transceiver);
1976 }
1977 }
1978 return receiving_transceivers;
1979}
1980
htaa2a49d92016-03-04 02:51:39 -08001981void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1982 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001983 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08001984 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001985 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001986 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001987 return;
1988 }
1989
Steve Antondffead82018-02-06 10:31:29 -08001990 if (!(signaling_state_ == kHaveRemoteOffer ||
1991 signaling_state_ == kHaveLocalPrAnswer)) {
1992 std::string error =
1993 "PeerConnection cannot create an answer in a state other than "
1994 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001995 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001996 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001997 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001998 return;
1999 }
2000
Steve Antondffead82018-02-06 10:31:29 -08002001 // The remote description should be set if we're in the right state.
2002 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002003
Steve Anton22da89f2018-01-25 13:58:07 -08002004 if (IsUnifiedPlan()) {
2005 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2006 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2007 "supported with Unified Plan semantics. Use the "
2008 "RtpTransceiver API instead.";
2009 }
2010 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2011 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2012 "supported with Unified Plan semantics. Use the "
2013 "RtpTransceiver API instead.";
2014 }
2015 }
2016
htaa2a49d92016-03-04 02:51:39 -08002017 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002018 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002019
Steve Antond25da372017-11-06 14:50:29 -08002020 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021}
2022
2023void PeerConnection::SetLocalDescription(
2024 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002025 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002026 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002027
Steve Anton80dd7b52018-02-16 17:08:42 -08002028 // The SetLocalDescription contract is that we take ownership of the session
2029 // description regardless of the outcome, so wrap it in a unique_ptr right
2030 // away. Ideally, SetLocalDescription's signature will be changed to take the
2031 // description as a unique_ptr argument to formalize this agreement.
2032 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2033
nisse7ce109a2017-01-31 00:57:56 -08002034 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002035 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 return;
2037 }
Steve Anton8a006912017-12-04 15:25:56 -08002038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002040 PostSetSessionDescriptionFailure(
2041 observer,
2042 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043 return;
2044 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002045
Steve Anton80dd7b52018-02-16 17:08:42 -08002046 // If a session error has occurred the PeerConnection is in a possibly
2047 // inconsistent state so fail right away.
2048 if (session_error() != SessionError::kNone) {
2049 std::string error_message = GetSessionErrorMsg();
2050 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002051 PostSetSessionDescriptionFailure(
2052 observer,
2053 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002054 return;
2055 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002056
Steve Anton80dd7b52018-02-16 17:08:42 -08002057 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2058 if (!error.ok()) {
2059 std::string error_message = GetSetDescriptionErrorMessage(
2060 cricket::CS_LOCAL, desc->GetType(), error);
2061 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002062 PostSetSessionDescriptionFailure(
2063 observer,
2064 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002065 return;
2066 }
2067
2068 // Grab the description type before moving ownership to ApplyLocalDescription,
2069 // which may destroy it before returning.
2070 const SdpType type = desc->GetType();
2071
2072 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002073 // |desc| may be destroyed at this point.
2074
2075 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002076 // If ApplyLocalDescription fails, the PeerConnection could be in an
2077 // inconsistent state, so act conservatively here and set the session error
2078 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2079 SetSessionError(SessionError::kContent, error.message());
2080 std::string error_message =
2081 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2082 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002083 PostSetSessionDescriptionFailure(
2084 observer,
2085 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002086 return;
2087 }
Steve Anton8a006912017-12-04 15:25:56 -08002088 RTC_DCHECK(local_description());
2089
2090 PostSetSessionDescriptionSuccess(observer);
2091
Steve Antonad182762018-09-05 20:22:40 +00002092 // MaybeStartGathering needs to be called after posting
2093 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2094 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002095 transport_controller_->MaybeStartGathering();
2096
Steve Antona3a92c22017-12-07 10:27:41 -08002097 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002098 // TODO(deadbeef): We already had to hop to the network thread for
2099 // MaybeStartGathering...
2100 network_thread()->Invoke<void>(
2101 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2102 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002103 // Make UMA notes about what was agreed to.
2104 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002105 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002106 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002107}
2108
2109RTCError PeerConnection::ApplyLocalDescription(
2110 std::unique_ptr<SessionDescriptionInterface> desc) {
2111 RTC_DCHECK_RUN_ON(signaling_thread());
2112 RTC_DCHECK(desc);
2113
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 // Update stats here so that we have the most recent stats for tracks and
2115 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002116 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002117
Steve Antondcc3c022017-12-22 16:02:54 -08002118 // Take a reference to the old local description since it's used below to
2119 // compare against the new local description. When setting the new local
2120 // description, grab ownership of the replaced session description in case it
2121 // is the same as |old_local_description|, to keep it alive for the duration
2122 // of the method.
2123 const SessionDescriptionInterface* old_local_description =
2124 local_description();
2125 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002126 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002127 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002128 replaced_local_description = pending_local_description_
2129 ? std::move(pending_local_description_)
2130 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002131 current_local_description_ = std::move(desc);
2132 pending_local_description_ = nullptr;
2133 current_remote_description_ = std::move(pending_remote_description_);
2134 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002135 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002136 pending_local_description_ = std::move(desc);
2137 }
2138 // The session description to apply now must be accessed by
2139 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002140 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002141
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002142 if (!is_caller_) {
2143 if (remote_description()) {
2144 // Remote description was applied first, so this PC is the callee.
2145 is_caller_ = false;
2146 } else {
2147 // Local description is applied first, so this PC is the caller.
2148 is_caller_ = true;
2149 }
2150 }
2151
Zhi Huange830e682018-03-30 10:48:35 -07002152 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2153 if (!error.ok()) {
2154 return error;
2155 }
2156
Steve Antondcc3c022017-12-22 16:02:54 -08002157 if (IsUnifiedPlan()) {
2158 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002159 cricket::CS_LOCAL, *local_description(), old_local_description,
2160 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002161 if (!error.ok()) {
2162 return error;
2163 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002164 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2165 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002166 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002167 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2168 // Note that code paths that don't set MID won't be able to use
2169 // information about DTLS transports.
2170 if (transceiver->mid()) {
2171 auto dtls_transport =
2172 LookupDtlsTransportByMidInternal(*transceiver->mid());
2173 transceiver->internal()->sender_internal()->set_transport(
2174 dtls_transport);
2175 transceiver->internal()->receiver_internal()->set_transport(
2176 dtls_transport);
2177 }
2178
Steve Antondcc3c022017-12-22 16:02:54 -08002179 const ContentInfo* content =
2180 FindMediaSectionForTransceiver(transceiver, local_description());
2181 if (!content) {
2182 continue;
2183 }
2184 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002185 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2186 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002187 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002188 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2189 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2190 // "recvonly", process the removal of a remote track for the media
2191 // description, given transceiver, removeList, and muteTracks.
2192 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2193 (transceiver->internal()->fired_direction() &&
2194 RtpTransceiverDirectionHasRecv(
2195 *transceiver->internal()->fired_direction()))) {
2196 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2197 &removed_streams);
2198 }
2199 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2200 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002201 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002202 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002203 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002204 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002205 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002206 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002207 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002208 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002209 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002210 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002211 }
2212 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002213 // Media channels will be created only when offer is set. These may use new
2214 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002215 if (type == SdpType::kOffer) {
2216 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2217 // description is applied. Restore back to old description.
2218 RTCError error = CreateChannels(*local_description()->description());
2219 if (!error.ok()) {
2220 return error;
2221 }
2222 }
Steve Antondcc3c022017-12-22 16:02:54 -08002223 // Remove unused channels if MediaContentDescription is rejected.
2224 RemoveUnusedChannels(local_description()->description());
2225 }
Steve Anton8a006912017-12-04 15:25:56 -08002226
Zhi Huange830e682018-03-30 10:48:35 -07002227 error = UpdateSessionState(type, cricket::CS_LOCAL,
2228 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002229 if (!error.ok()) {
2230 return error;
2231 }
Steve Antondcc3c022017-12-22 16:02:54 -08002232
Steve Anton8a006912017-12-04 15:25:56 -08002233 if (remote_description()) {
2234 // Now that we have a local description, we can push down remote candidates.
2235 UseCandidatesInSessionDescription(remote_description());
2236 }
2237
2238 pending_ice_restarts_.clear();
2239 if (session_error() != SessionError::kNone) {
2240 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2241 }
2242
deadbeefab9b2d12015-10-14 11:33:11 -07002243 // If setting the description decided our SSL role, allocate any necessary
2244 // SCTP sids.
2245 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002246 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002247 AllocateSctpSids(role);
2248 }
2249
Steve Antond3679212018-01-17 17:41:02 -08002250 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002251 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002252 const ContentInfo* content =
2253 FindMediaSectionForTransceiver(transceiver, local_description());
2254 if (!content) {
2255 continue;
2256 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002257 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2258 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002259 // 0 is a special value meaning "this sender has no associated send
2260 // stream". Need to call this so the sender won't attempt to configure
2261 // a no longer existing stream and run into DCHECKs in the lower
2262 // layers.
2263 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002264 } else {
2265 // Get the StreamParams from the channel which could generate SSRCs.
2266 const std::vector<StreamParams>& streams = channel->local_streams();
2267 transceiver->internal()->sender_internal()->set_stream_ids(
2268 streams[0].stream_ids());
2269 transceiver->internal()->sender_internal()->SetSsrc(
2270 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002271 }
2272 }
2273 } else {
2274 // Plan B semantics.
2275
Steve Antondcc3c022017-12-22 16:02:54 -08002276 // Update state and SSRC of local MediaStreams and DataChannels based on the
2277 // local session description.
2278 const cricket::ContentInfo* audio_content =
2279 GetFirstAudioContent(local_description()->description());
2280 if (audio_content) {
2281 if (audio_content->rejected) {
2282 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2283 } else {
2284 const cricket::AudioContentDescription* audio_desc =
2285 audio_content->media_description()->as_audio();
2286 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2287 }
deadbeeffaac4972015-11-12 15:33:07 -08002288 }
deadbeefab9b2d12015-10-14 11:33:11 -07002289
Steve Antondcc3c022017-12-22 16:02:54 -08002290 const cricket::ContentInfo* video_content =
2291 GetFirstVideoContent(local_description()->description());
2292 if (video_content) {
2293 if (video_content->rejected) {
2294 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2295 } else {
2296 const cricket::VideoContentDescription* video_desc =
2297 video_content->media_description()->as_video();
2298 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2299 }
deadbeeffaac4972015-11-12 15:33:07 -08002300 }
deadbeefab9b2d12015-10-14 11:33:11 -07002301 }
2302
2303 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002304 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002305 if (data_content) {
2306 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002307 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002308 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002309 cricket::kMediaProtocolRtpPrefix)) {
2310 UpdateLocalRtpDataChannels(data_desc->streams());
2311 }
2312 }
2313
Steve Anton8a006912017-12-04 15:25:56 -08002314 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315}
2316
Steve Anton06817cd2018-12-18 15:55:30 -08002317// The SDP parser used to populate these values by default for the 'content
2318// name' if an a=mid line was absent.
2319static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2320 switch (media_type) {
2321 case cricket::MEDIA_TYPE_AUDIO:
2322 return cricket::CN_AUDIO;
2323 case cricket::MEDIA_TYPE_VIDEO:
2324 return cricket::CN_VIDEO;
2325 case cricket::MEDIA_TYPE_DATA:
2326 return cricket::CN_DATA;
2327 }
2328 RTC_NOTREACHED();
2329 return "";
2330}
2331
2332void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002333 cricket::SessionDescription* new_remote_description) {
2334 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002335 const cricket::ContentInfos& local_contents =
2336 (local_description() ? local_description()->description()->contents()
2337 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002338 const cricket::ContentInfos& remote_contents =
2339 (remote_description() ? remote_description()->description()->contents()
2340 : cricket::ContentInfos());
2341 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2342 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002343 if (!content.name.empty()) {
2344 continue;
2345 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002346 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002347 absl::string_view source_explanation;
2348 if (IsUnifiedPlan()) {
2349 if (i < local_contents.size()) {
2350 new_mid = local_contents[i].name;
2351 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002352 } else if (i < remote_contents.size()) {
2353 new_mid = remote_contents[i].name;
2354 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002355 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002356 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002357 source_explanation = "generated just now";
2358 }
2359 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002360 new_mid = std::string(
2361 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002362 source_explanation = "to match pre-existing behavior";
2363 }
Steve Antond7180cc2019-02-07 10:44:53 -08002364 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002365 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002366 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002367 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2368 << " is missing an a=mid line. Filling in the value '"
2369 << new_mid << "' " << source_explanation << ".";
2370 }
2371}
2372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002374 SetSessionDescriptionObserver* observer,
2375 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002376 SetRemoteDescription(
2377 std::unique_ptr<SessionDescriptionInterface>(desc),
2378 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2379 new SetRemoteDescriptionObserverAdapter(this, observer)));
2380}
2381
2382void PeerConnection::SetRemoteDescription(
2383 std::unique_ptr<SessionDescriptionInterface> desc,
2384 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002385 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002386
nisse7ce109a2017-01-31 00:57:56 -08002387 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002388 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389 return;
2390 }
Steve Anton8a006912017-12-04 15:25:56 -08002391
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002393 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002394 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395 return;
2396 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002397
Steve Anton80dd7b52018-02-16 17:08:42 -08002398 // If a session error has occurred the PeerConnection is in a possibly
2399 // inconsistent state so fail right away.
2400 if (session_error() != SessionError::kNone) {
2401 std::string error_message = GetSessionErrorMsg();
2402 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2403 observer->OnSetRemoteDescriptionComplete(
2404 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2405 return;
2406 }
Steve Anton71439a62018-02-15 11:53:06 -08002407
Steve Antonba42e992018-04-09 14:10:01 -07002408 if (desc->GetType() == SdpType::kOffer) {
2409 // Report to UMA the format of the received offer.
2410 ReportSdpFormatReceived(*desc);
2411 }
2412
Steve Anton06817cd2018-12-18 15:55:30 -08002413 // Handle remote descriptions missing a=mid lines for interop with legacy end
2414 // points.
2415 FillInMissingRemoteMids(desc->description());
2416
Steve Anton80dd7b52018-02-16 17:08:42 -08002417 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002418 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002419 std::string error_message = GetSetDescriptionErrorMessage(
2420 cricket::CS_REMOTE, desc->GetType(), error);
2421 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002422 observer->OnSetRemoteDescriptionComplete(
2423 RTCError(error.type(), std::move(error_message)));
2424 return;
2425 }
Steve Anton71439a62018-02-15 11:53:06 -08002426
Steve Anton80dd7b52018-02-16 17:08:42 -08002427 // Grab the description type before moving ownership to
2428 // ApplyRemoteDescription, which may destroy it before returning.
2429 const SdpType type = desc->GetType();
2430
2431 error = ApplyRemoteDescription(std::move(desc));
2432 // |desc| may be destroyed at this point.
2433
2434 if (!error.ok()) {
2435 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2436 // inconsistent state, so act conservatively here and set the session error
2437 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2438 SetSessionError(SessionError::kContent, error.message());
2439 std::string error_message =
2440 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2441 RTC_LOG(LS_ERROR) << error_message;
2442 observer->OnSetRemoteDescriptionComplete(
2443 RTCError(error.type(), std::move(error_message)));
2444 return;
2445 }
2446 RTC_DCHECK(remote_description());
2447
2448 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002449 // TODO(deadbeef): We already had to hop to the network thread for
2450 // MaybeStartGathering...
2451 network_thread()->Invoke<void>(
2452 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2453 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002454 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002455 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002456 }
2457
2458 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002459 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002460}
2461
2462RTCError PeerConnection::ApplyRemoteDescription(
2463 std::unique_ptr<SessionDescriptionInterface> desc) {
2464 RTC_DCHECK_RUN_ON(signaling_thread());
2465 RTC_DCHECK(desc);
2466
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002467 // Update stats here so that we have the most recent stats for tracks and
2468 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002469 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002470
Steve Antondcc3c022017-12-22 16:02:54 -08002471 // Take a reference to the old remote description since it's used below to
2472 // compare against the new remote description. When setting the new remote
2473 // description, grab ownership of the replaced session description in case it
2474 // is the same as |old_remote_description|, to keep it alive for the duration
2475 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002476 const SessionDescriptionInterface* old_remote_description =
2477 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002478 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002479 SdpType type = desc->GetType();
2480 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002481 replaced_remote_description = pending_remote_description_
2482 ? std::move(pending_remote_description_)
2483 : std::move(current_remote_description_);
2484 current_remote_description_ = std::move(desc);
2485 pending_remote_description_ = nullptr;
2486 current_local_description_ = std::move(pending_local_description_);
2487 } else {
2488 replaced_remote_description = std::move(pending_remote_description_);
2489 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 }
Steve Anton8a006912017-12-04 15:25:56 -08002491 // The session description to apply now must be accessed by
2492 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002493 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494
Zhi Huange830e682018-03-30 10:48:35 -07002495 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2496 if (!error.ok()) {
2497 return error;
2498 }
Steve Anton8a006912017-12-04 15:25:56 -08002499 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002500 if (IsUnifiedPlan()) {
2501 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002502 cricket::CS_REMOTE, *remote_description(), local_description(),
2503 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002504 if (!error.ok()) {
2505 return error;
2506 }
Steve Antondcc3c022017-12-22 16:02:54 -08002507 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002508 // Media channels will be created only when offer is set. These may use new
2509 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002510 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002511 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // description is applied. Restore back to old description.
2513 RTCError error = CreateChannels(*remote_description()->description());
2514 if (!error.ok()) {
2515 return error;
2516 }
2517 }
Steve Antondcc3c022017-12-22 16:02:54 -08002518 // Remove unused channels if MediaContentDescription is rejected.
2519 RemoveUnusedChannels(remote_description()->description());
2520 }
Steve Anton8a006912017-12-04 15:25:56 -08002521
Zhi Huange830e682018-03-30 10:48:35 -07002522 // NOTE: Candidates allocation will be initiated only when
2523 // SetLocalDescription is called.
2524 error = UpdateSessionState(type, cricket::CS_REMOTE,
2525 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002526 if (!error.ok()) {
2527 return error;
2528 }
2529
2530 if (local_description() &&
2531 !UseCandidatesInSessionDescription(remote_description())) {
2532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2533 }
2534
2535 if (old_remote_description) {
2536 for (const cricket::ContentInfo& content :
2537 old_remote_description->description()->contents()) {
2538 // Check if this new SessionDescription contains new ICE ufrag and
2539 // password that indicates the remote peer requests an ICE restart.
2540 // TODO(deadbeef): When we start storing both the current and pending
2541 // remote description, this should reset pending_ice_restarts and compare
2542 // against the current description.
2543 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2544 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002545 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002546 pending_ice_restarts_.insert(content.name);
2547 }
2548 } else {
2549 // We retain all received candidates only if ICE is not restarted.
2550 // When ICE is restarted, all previous candidates belong to an old
2551 // generation and should not be kept.
2552 // TODO(deadbeef): This goes against the W3C spec which says the remote
2553 // description should only contain candidates from the last set remote
2554 // description plus any candidates added since then. We should remove
2555 // this once we're sure it won't break anything.
2556 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2557 old_remote_description, content.name, mutable_remote_description());
2558 }
2559 }
2560 }
2561
2562 if (session_error() != SessionError::kNone) {
2563 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2564 }
2565
2566 // Set the the ICE connection state to connecting since the connection may
2567 // become writable with peer reflexive candidates before any remote candidate
2568 // is signaled.
2569 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2570 // is to have a new signal the indicates a change in checking state from the
2571 // transport and expose a new checking() member from transport that can be
2572 // read to determine the current checking state. The existing SignalConnecting
2573 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002574 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002575 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002576 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2577 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2578 }
2579
deadbeefab9b2d12015-10-14 11:33:11 -07002580 // If setting the description decided our SSL role, allocate any necessary
2581 // SCTP sids.
2582 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002583 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002584 AllocateSctpSids(role);
2585 }
2586
Steve Antondcc3c022017-12-22 16:02:54 -08002587 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002588 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002589 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002590 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002591 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002592 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002593 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002594 const ContentInfo* content =
2595 FindMediaSectionForTransceiver(transceiver, remote_description());
2596 if (!content) {
2597 continue;
2598 }
2599 const MediaContentDescription* media_desc = content->media_description();
2600 RtpTransceiverDirection local_direction =
2601 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002602 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2603 // RTCSessionDescription: Set the associated remote streams given
2604 // transceiver.[[Receiver]], msids, addList, and removeList".
2605 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2606 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2607 std::vector<std::string> stream_ids;
2608 if (!media_desc->streams().empty()) {
2609 // The remote description has signaled the stream IDs.
2610 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002611 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002612 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2613 << " (" << GetStreamIdsString(stream_ids) << ").";
2614 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2615 stream_ids, &added_streams,
2616 &removed_streams);
2617 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2618 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2619 // and transceiver's current direction is neither sendrecv nor recvonly,
2620 // process the addition of a remote track for the media description.
2621 if (!transceiver->fired_direction() ||
2622 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2623 RTC_LOG(LS_INFO)
2624 << "Processing the addition of a remote track for MID="
2625 << content->name << ".";
2626 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002627 }
Steve Antondcc3c022017-12-22 16:02:54 -08002628 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002629 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002630 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2631 // removal of a remote track for the media description, given transceiver,
2632 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002633 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002634 (transceiver->fired_direction() &&
2635 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2636 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2637 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002638 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002639 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002640 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002641 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002642 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002643 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002644 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002645 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002646 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002647 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2648 if (transceiver->mid()) {
2649 auto dtls_transport =
2650 LookupDtlsTransportByMidInternal(*transceiver->mid());
2651 transceiver->internal()->sender_internal()->set_transport(
2652 dtls_transport);
2653 transceiver->internal()->receiver_internal()->set_transport(
2654 dtls_transport);
2655 }
Steve Antondcc3c022017-12-22 16:02:54 -08002656 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002657 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002658 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002659 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002660 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2661 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002662 transceiver->Stop();
2663 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002664 if (!content->rejected &&
2665 RtpTransceiverDirectionHasRecv(local_direction)) {
2666 // Set ssrc to 0 in the case of an unsignalled ssrc.
2667 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002668 if (!media_desc->streams().empty() &&
2669 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002670 ssrc = media_desc->streams()[0].first_ssrc();
2671 }
2672 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002673 }
Steve Antondcc3c022017-12-22 16:02:54 -08002674 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002675 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002676 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002677 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002678 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002679 observer->OnTrack(transceiver);
2680 observer->OnAddTrack(transceiver->receiver(),
2681 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002682 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002683 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002684 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002685 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002686 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002687 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002688 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002689 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002690 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002691 }
Steve Antondcc3c022017-12-22 16:02:54 -08002692 }
2693
Henrik Boströmfdb92012017-11-09 19:55:44 +01002694 const cricket::ContentInfo* audio_content =
2695 GetFirstAudioContent(remote_description()->description());
2696 const cricket::ContentInfo* video_content =
2697 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002698 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002699 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002700 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002701 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002702 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002703 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002704
2705 // Check if the descriptions include streams, just in case the peer supports
2706 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002707 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002708 (audio_desc && !audio_desc->streams().empty()) ||
2709 (video_desc && !video_desc->streams().empty())) {
2710 remote_peer_supports_msid_ = true;
2711 }
deadbeefab9b2d12015-10-14 11:33:11 -07002712
2713 // We wait to signal new streams until we finish processing the description,
2714 // since only at that point will new streams have all their tracks.
2715 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2716
Steve Antondcc3c022017-12-22 16:02:54 -08002717 if (!IsUnifiedPlan()) {
2718 // TODO(steveanton): When removing RTP senders/receivers in response to a
2719 // rejected media section, there is some cleanup logic that expects the
2720 // voice/ video channel to still be set. But in this method the voice/video
2721 // channel would have been destroyed by the SetRemoteDescription caller
2722 // above so the cleanup that relies on them fails to run. The RemoveSenders
2723 // calls should be moved to right before the DestroyChannel calls to fix
2724 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002725
Steve Antondcc3c022017-12-22 16:02:54 -08002726 // Find all audio rtp streams and create corresponding remote AudioTracks
2727 // and MediaStreams.
2728 if (audio_content) {
2729 if (audio_content->rejected) {
2730 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2731 } else {
2732 bool default_audio_track_needed =
2733 !remote_peer_supports_msid_ &&
2734 RtpTransceiverDirectionHasSend(audio_desc->direction());
2735 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2736 default_audio_track_needed, audio_desc->type(),
2737 new_streams);
2738 }
deadbeeffaac4972015-11-12 15:33:07 -08002739 }
deadbeefab9b2d12015-10-14 11:33:11 -07002740
Steve Antondcc3c022017-12-22 16:02:54 -08002741 // Find all video rtp streams and create corresponding remote VideoTracks
2742 // and MediaStreams.
2743 if (video_content) {
2744 if (video_content->rejected) {
2745 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2746 } else {
2747 bool default_video_track_needed =
2748 !remote_peer_supports_msid_ &&
2749 RtpTransceiverDirectionHasSend(video_desc->direction());
2750 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2751 default_video_track_needed, video_desc->type(),
2752 new_streams);
2753 }
deadbeeffaac4972015-11-12 15:33:07 -08002754 }
deadbeefab9b2d12015-10-14 11:33:11 -07002755
Steve Antondcc3c022017-12-22 16:02:54 -08002756 // Update the DataChannels with the information from the remote peer.
2757 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002758 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002759 cricket::kMediaProtocolRtpPrefix)) {
2760 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2761 }
deadbeefab9b2d12015-10-14 11:33:11 -07002762 }
deadbeefab9b2d12015-10-14 11:33:11 -07002763
Steve Antondcc3c022017-12-22 16:02:54 -08002764 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002765 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002766 for (size_t i = 0; i < new_streams->count(); ++i) {
2767 MediaStreamInterface* new_stream = new_streams->at(i);
2768 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002769 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002770 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2771 }
deadbeefab9b2d12015-10-14 11:33:11 -07002772
Steve Antondcc3c022017-12-22 16:02:54 -08002773 UpdateEndedRemoteMediaStreams();
2774 }
deadbeefab9b2d12015-10-14 11:33:11 -07002775
Steve Anton8a006912017-12-04 15:25:56 -08002776 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002777}
2778
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002779void PeerConnection::SetAssociatedRemoteStreams(
2780 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2781 const std::vector<std::string>& stream_ids,
2782 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2783 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2784 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2785 for (const std::string& stream_id : stream_ids) {
2786 rtc::scoped_refptr<MediaStreamInterface> stream =
2787 remote_streams_->find(stream_id);
2788 if (!stream) {
2789 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2790 MediaStream::Create(stream_id));
2791 remote_streams_->AddStream(stream);
2792 added_streams->push_back(stream);
2793 }
2794 media_streams.push_back(stream);
2795 }
2796 // Special case: "a=msid" missing, use random stream ID.
2797 if (media_streams.empty() &&
2798 !(remote_description()->description()->msid_signaling() &
2799 cricket::kMsidSignalingMediaSection)) {
2800 if (!missing_msid_default_stream_) {
2801 missing_msid_default_stream_ = MediaStreamProxy::Create(
2802 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2803 added_streams->push_back(missing_msid_default_stream_);
2804 }
2805 media_streams.push_back(missing_msid_default_stream_);
2806 }
2807 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2808 receiver->streams();
2809 // SetStreams() will add/remove the receiver's track to/from the streams. This
2810 // differs from the spec - the spec uses an "addList" and "removeList" to
2811 // update the stream-track relationships in a later step. We do this earlier,
2812 // changing the order of things, but the end-result is the same.
2813 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2814 // instead. https://crbug.com/webrtc/9480
2815 receiver->SetStreams(media_streams);
2816 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2817}
2818
Steve Anton0f5400a2018-07-17 14:25:36 -07002819void PeerConnection::ProcessRemovalOfRemoteTrack(
2820 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2821 transceiver,
2822 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2823 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2824 RTC_DCHECK(transceiver->mid());
2825 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2826 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002827 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002828 transceiver->internal()->receiver_internal()->streams();
2829 // This will remove the remote track from the streams.
2830 transceiver->internal()->receiver_internal()->set_stream_ids({});
2831 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002832 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2833}
2834
2835void PeerConnection::RemoveRemoteStreamsIfEmpty(
2836 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2837 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2838 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2839 // streams, see if the stream was removed by checking if this was the last
2840 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002841 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002842 if (remote_stream->GetAudioTracks().empty() &&
2843 remote_stream->GetVideoTracks().empty()) {
2844 remote_streams_->RemoveStream(remote_stream);
2845 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002846 }
2847 }
2848}
2849
Steve Antondcc3c022017-12-22 16:02:54 -08002850RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2851 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002852 const SessionDescriptionInterface& new_session,
2853 const SessionDescriptionInterface* old_local_description,
2854 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002855 RTC_DCHECK(IsUnifiedPlan());
2856
Steve Anton7464fca2018-01-19 11:10:37 -08002857 const cricket::ContentGroup* bundle_group = nullptr;
2858 if (new_session.GetType() == SdpType::kOffer) {
2859 auto bundle_group_or_error =
2860 GetEarlyBundleGroup(*new_session.description());
2861 if (!bundle_group_or_error.ok()) {
2862 return bundle_group_or_error.MoveError();
2863 }
2864 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002865 }
Steve Antondcc3c022017-12-22 16:02:54 -08002866
Steve Antondcc3c022017-12-22 16:02:54 -08002867 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002868 for (size_t i = 0; i < new_contents.size(); ++i) {
2869 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002870 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002871 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002872 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2873 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002874 const cricket::ContentInfo* old_local_content = nullptr;
2875 if (old_local_description &&
2876 i < old_local_description->description()->contents().size()) {
2877 old_local_content =
2878 &old_local_description->description()->contents()[i];
2879 }
2880 const cricket::ContentInfo* old_remote_content = nullptr;
2881 if (old_remote_description &&
2882 i < old_remote_description->description()->contents().size()) {
2883 old_remote_content =
2884 &old_remote_description->description()->contents()[i];
2885 }
Steve Antondcc3c022017-12-22 16:02:54 -08002886 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002887 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2888 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002889 if (!transceiver_or_error.ok()) {
2890 return transceiver_or_error.MoveError();
2891 }
2892 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002893 RTCError error =
2894 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2895 if (!error.ok()) {
2896 return error;
2897 }
2898 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002899 if (GetDataMid() && new_content.name != *GetDataMid()) {
2900 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002901 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2902 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002903 continue;
2904 }
2905 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2906 if (!error.ok()) {
2907 return error;
2908 }
Steve Antondcc3c022017-12-22 16:02:54 -08002909 } else {
2910 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2911 "Unknown section type.");
2912 }
2913 }
2914
2915 return RTCError::OK();
2916}
2917
2918RTCError PeerConnection::UpdateTransceiverChannel(
2919 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2920 transceiver,
2921 const cricket::ContentInfo& content,
2922 const cricket::ContentGroup* bundle_group) {
2923 RTC_DCHECK(IsUnifiedPlan());
2924 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002925 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002926 if (content.rejected) {
2927 if (channel) {
2928 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002929 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002930 }
2931 } else {
2932 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002933 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002934 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002935 } else {
Steve Anton69470252018-02-09 11:43:08 -08002936 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002937 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002938 }
2939 if (!channel) {
2940 LOG_AND_RETURN_ERROR(
2941 RTCErrorType::INTERNAL_ERROR,
2942 "Failed to create channel for mid=" + content.name);
2943 }
2944 transceiver->internal()->SetChannel(channel);
2945 }
2946 }
2947 return RTCError::OK();
2948}
2949
Steve Antonfa2260d2017-12-28 16:38:23 -08002950RTCError PeerConnection::UpdateDataChannel(
2951 cricket::ContentSource source,
2952 const cricket::ContentInfo& content,
2953 const cricket::ContentGroup* bundle_group) {
2954 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002955 // If data channels are disabled, ignore this media section. CreateAnswer
2956 // will take care of rejecting it.
2957 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002958 }
2959 if (content.rejected) {
2960 DestroyDataChannel();
2961 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002962 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002963 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002964 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2965 "Failed to create data channel.");
2966 }
2967 }
2968 if (source == cricket::CS_REMOTE) {
2969 const MediaContentDescription* data_desc = content.media_description();
2970 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2971 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2972 }
2973 }
2974 }
2975 return RTCError::OK();
2976}
2977
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002978// This method will extract any send encodings that were sent by the remote
2979// connection. This is currently only relevant for Simulcast scenario (where
2980// the number of layers may be communicated by the server).
2981static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2982 const MediaContentDescription& desc) {
2983 if (!desc.HasSimulcast()) {
2984 return {};
2985 }
2986 std::vector<RtpEncodingParameters> result;
2987 const SimulcastDescription& simulcast = desc.simulcast_description();
2988
2989 // This is a remote description, the parameters we are after should appear
2990 // as receive streams.
2991 for (const auto& alternatives : simulcast.receive_layers()) {
2992 RTC_DCHECK(!alternatives.empty());
2993 // There is currently no way to specify or choose from alternatives.
2994 // We will always use the first alternative, which is the most preferred.
2995 const SimulcastLayer& layer = alternatives[0];
2996 RtpEncodingParameters parameters;
2997 parameters.rid = layer.rid;
2998 parameters.active = !layer.is_paused;
2999 result.push_back(parameters);
3000 }
3001
3002 return result;
3003}
3004
3005static RTCError UpdateSimulcastLayerStatusInSender(
3006 const std::vector<SimulcastLayer>& layers,
3007 RtpSenderInterface* sender) {
3008 RTC_DCHECK(sender);
3009 RtpParameters parameters = sender->GetParameters();
3010
3011 // The simulcast envelope cannot be changed, only the status of the streams.
3012 // So we will iterate over the send encodings rather than the layers.
3013 for (RtpEncodingParameters& encoding : parameters.encodings) {
3014 auto iter = std::find_if(layers.begin(), layers.end(),
3015 [&encoding](const SimulcastLayer& layer) {
3016 return layer.rid == encoding.rid;
3017 });
3018 // A layer that cannot be found may have been removed by the remote party.
3019 encoding.active = iter != layers.end() && !iter->is_paused;
3020 }
3021
3022 return sender->SetParameters(parameters);
3023}
3024
3025static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
3026 RTC_DCHECK(sender);
3027 RtpParameters parameters = sender->GetParameters();
3028 if (parameters.encodings.empty()) {
3029 return RTCError::OK();
3030 }
3031
3032 bool first_layer_status = parameters.encodings[0].active;
3033 for (RtpEncodingParameters& encoding : parameters.encodings) {
3034 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
3035 // The user might enable it at a later point in time even though it was
3036 // rejected.
3037 encoding.active = false;
3038 }
3039 parameters.encodings[0].active = first_layer_status;
3040
3041 return sender->SetParameters(parameters);
3042}
3043
Steve Antondcc3c022017-12-22 16:02:54 -08003044RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3045PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003046 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003047 size_t mline_index,
3048 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003049 const ContentInfo* old_local_content,
3050 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003051 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003052 // If this is an offer then the m= section might be recycled. If the m=
3053 // section is being recycled (defined as: rejected in the current local or
3054 // remote description and not rejected in new description), dissociate the
3055 // currently associated RtpTransceiver by setting its mid property to null,
3056 // and discard the mapping between the transceiver and its m= section index.
3057 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3058 old_remote_content)) {
3059 // We want to dissociate the transceiver that has the rejected mid.
3060 const std::string& old_mid =
3061 (old_local_content && old_local_content->rejected)
3062 ? old_local_content->name
3063 : old_remote_content->name;
3064 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003065 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003066 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3067 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003068 old_transceiver->internal()->set_mid(absl::nullopt);
3069 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003070 }
3071 }
3072 const MediaContentDescription* media_desc = content.media_description();
3073 auto transceiver = GetAssociatedTransceiver(content.name);
3074 if (source == cricket::CS_LOCAL) {
3075 // Find the RtpTransceiver that corresponds to this m= section, using the
3076 // mapping between transceivers and m= section indices established when
3077 // creating the offer.
3078 if (!transceiver) {
3079 transceiver = GetTransceiverByMLineIndex(mline_index);
3080 }
3081 if (!transceiver) {
3082 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3083 "Unknown transceiver");
3084 }
3085 } else {
3086 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3087 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3088 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003089 // When simulcast is requested, a transceiver cannot be associated because
3090 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003091 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003092 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3093 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003094 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3095 }
3096 // If no RtpTransceiver was found in the previous step, create one with a
3097 // recvonly direction.
3098 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003099 RTC_LOG(LS_INFO) << "Adding "
3100 << cricket::MediaTypeToString(media_desc->type())
3101 << " transceiver for MID=" << content.name
3102 << " at i=" << mline_index
3103 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003104 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003105 std::vector<RtpEncodingParameters> send_encodings =
3106 GetSendEncodingsFromRemoteDescription(*media_desc);
3107 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3108 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003109 std::string receiver_id;
3110 if (!media_desc->streams().empty()) {
3111 receiver_id = media_desc->streams()[0].id;
3112 } else {
3113 receiver_id = rtc::CreateRandomUuid();
3114 }
3115 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003116 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003117 transceiver->internal()->set_direction(
3118 RtpTransceiverDirection::kRecvOnly);
3119 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003120
3121 // Check if the offer indicated simulcast but the answer rejected it.
3122 // This can happen when simulcast is not supported on the remote party.
3123 // This check can be simplified to comparing the number of send encodings,
3124 // but that might break legacy implementation in which simulcast is not
3125 // signaled in the remote description.
3126 if (old_local_content && old_local_content->media_description() &&
3127 old_local_content->media_description()->HasSimulcast() &&
3128 !media_desc->HasSimulcast()) {
3129 RTCError error =
3130 DisableSimulcastInSender(transceiver->internal()->sender());
3131 if (!error.ok()) {
3132 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3133 return std::move(error);
3134 }
3135 }
Steve Antondcc3c022017-12-22 16:02:54 -08003136 }
3137 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003138 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003139 LOG_AND_RETURN_ERROR(
3140 RTCErrorType::INVALID_PARAMETER,
3141 "Transceiver type does not match media description type.");
3142 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003143 if (media_desc->HasSimulcast()) {
3144 std::vector<SimulcastLayer> layers =
3145 source == cricket::CS_LOCAL
3146 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3147 : media_desc->simulcast_description()
3148 .receive_layers()
3149 .GetAllLayers();
3150 RTCError error = UpdateSimulcastLayerStatusInSender(
3151 layers, transceiver->internal()->sender());
3152 if (!error.ok()) {
3153 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3154 return std::move(error);
3155 }
3156 }
Steve Antondcc3c022017-12-22 16:02:54 -08003157 // Associate the found or created RtpTransceiver with the m= section by
3158 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3159 // section, and establish a mapping between the transceiver and the index of
3160 // the m= section.
3161 transceiver->internal()->set_mid(content.name);
3162 transceiver->internal()->set_mline_index(mline_index);
3163 return std::move(transceiver);
3164}
3165
3166rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3167PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3168 RTC_DCHECK(IsUnifiedPlan());
3169 for (auto transceiver : transceivers_) {
3170 if (transceiver->mid() == mid) {
3171 return transceiver;
3172 }
3173 }
3174 return nullptr;
3175}
3176
3177rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3178PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3179 RTC_DCHECK(IsUnifiedPlan());
3180 for (auto transceiver : transceivers_) {
3181 if (transceiver->internal()->mline_index() == mline_index) {
3182 return transceiver;
3183 }
3184 }
3185 return nullptr;
3186}
3187
3188rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3189PeerConnection::FindAvailableTransceiverToReceive(
3190 cricket::MediaType media_type) const {
3191 RTC_DCHECK(IsUnifiedPlan());
3192 // From JSEP section 5.10 (Applying a Remote Description):
3193 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3194 // the same type that were added to the PeerConnection by addTrack and are not
3195 // associated with any m= section and are not stopped, find the first such
3196 // RtpTransceiver.
3197 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003198 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003199 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3200 !transceiver->stopped()) {
3201 return transceiver;
3202 }
3203 }
3204 return nullptr;
3205}
3206
Steve Antoned10bd92017-12-05 10:52:59 -08003207const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3208 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3209 transceiver,
3210 const SessionDescriptionInterface* sdesc) const {
3211 RTC_DCHECK(transceiver);
3212 RTC_DCHECK(sdesc);
3213 if (IsUnifiedPlan()) {
3214 if (!transceiver->internal()->mid()) {
3215 // This transceiver is not associated with a media section yet.
3216 return nullptr;
3217 }
3218 return sdesc->description()->GetContentByName(
3219 *transceiver->internal()->mid());
3220 } else {
3221 // Plan B only allows at most one audio and one video section, so use the
3222 // first media section of that type.
3223 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003224 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003225 }
3226}
3227
deadbeef46c73892016-11-16 19:42:04 -08003228PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3229 return configuration_;
3230}
3231
deadbeef293e9262017-01-11 12:28:30 -08003232bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3233 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003234 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003235 if (IsClosed()) {
3236 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3237 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3238 }
3239
Qingsi Wanga2d60672018-04-11 16:57:45 -07003240 // According to JSEP, after setLocalDescription, changing the candidate pool
3241 // size is not allowed, and changing the set of ICE servers will not result
3242 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003243 if (local_description() && configuration.ice_candidate_pool_size !=
3244 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003245 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3246 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003247 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003248 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003249
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003250 if (local_description() &&
3251 configuration.use_media_transport != configuration_.use_media_transport) {
3252 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3253 "SetLocalDescription.";
3254 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3255 }
3256
3257 if (remote_description() &&
3258 configuration.use_media_transport != configuration_.use_media_transport) {
3259 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3260 "SetRemoteDescription.";
3261 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3262 }
3263
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003264 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003265 configuration.use_media_transport_for_data_channels !=
3266 configuration_.use_media_transport_for_data_channels) {
3267 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3268 "after calling SetLocalDescription.";
3269 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3270 }
3271
3272 if (remote_description() &&
3273 configuration.use_media_transport_for_data_channels !=
3274 configuration_.use_media_transport_for_data_channels) {
3275 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3276 "after calling SetRemoteDescription.";
3277 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3278 }
3279
3280 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003281 configuration.crypto_options != configuration_.crypto_options) {
3282 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3283 "SetLocalDescription.";
3284 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3285 }
3286
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003287 if (configuration.use_media_transport_for_data_channels ||
3288 configuration.use_media_transport) {
3289 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3290 << "Media transport requires MaxBundle policy.";
3291 }
3292
deadbeef293e9262017-01-11 12:28:30 -08003293 // The simplest (and most future-compatible) way to tell if the config was
3294 // modified in an invalid way is to copy each property we do support
3295 // modifying, then use operator==. There are far more properties we don't
3296 // support modifying than those we do, and more could be added.
3297 RTCConfiguration modified_config = configuration_;
3298 modified_config.servers = configuration.servers;
3299 modified_config.type = configuration.type;
3300 modified_config.ice_candidate_pool_size =
3301 configuration.ice_candidate_pool_size;
3302 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003303 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003304 modified_config.ice_check_interval_strong_connectivity =
3305 configuration.ice_check_interval_strong_connectivity;
3306 modified_config.ice_check_interval_weak_connectivity =
3307 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003308 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3309 modified_config.ice_unwritable_min_checks =
3310 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003311 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003312 modified_config.stun_candidate_keepalive_interval =
3313 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003314 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003315 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003316 modified_config.active_reset_srtp_params =
3317 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003318 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003319 modified_config.use_media_transport_for_data_channels =
3320 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003321 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003322 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003323 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3324 }
3325
Steve Anton038834f2017-07-14 15:59:59 -07003326 // Validate the modified configuration.
3327 RTCError validate_error = ValidateConfiguration(modified_config);
3328 if (!validate_error.ok()) {
3329 return SafeSetError(std::move(validate_error), error);
3330 }
3331
deadbeef293e9262017-01-11 12:28:30 -08003332 // Note that this isn't possible through chromium, since it's an unsigned
3333 // short in WebIDL.
3334 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003335 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003336 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3337 }
3338
3339 // Parse ICE servers before hopping to network thread.
3340 cricket::ServerAddresses stun_servers;
3341 std::vector<cricket::RelayServerConfig> turn_servers;
3342 RTCErrorType parse_error =
3343 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3344 if (parse_error != RTCErrorType::NONE) {
3345 return SafeSetError(parse_error, error);
3346 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003347 // Note if STUN or TURN servers were supplied.
3348 if (!stun_servers.empty()) {
3349 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3350 }
3351 if (!turn_servers.empty()) {
3352 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3353 }
deadbeef293e9262017-01-11 12:28:30 -08003354
3355 // In theory this shouldn't fail.
3356 if (!network_thread()->Invoke<bool>(
3357 RTC_FROM_HERE,
3358 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3359 stun_servers, turn_servers, modified_config.type,
3360 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003361 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003362 modified_config.turn_customizer,
3363 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003364 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003365 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3366 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003367
deadbeefd1a38b52016-12-10 13:15:33 -08003368 // As described in JSEP, calling setConfiguration with new ICE servers or
3369 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3370 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003371 if (modified_config.servers != configuration_.servers ||
3372 modified_config.type != configuration_.type ||
3373 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003374 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003375 }
skvladd1f5fda2017-02-03 16:54:05 -08003376
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003377 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003378 transport_controller_->SetMediaTransportSettings(
3379 modified_config.use_media_transport,
3380 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003381
Zhi Huangb57e1692018-06-12 11:41:11 -07003382 if (configuration_.active_reset_srtp_params !=
3383 modified_config.active_reset_srtp_params) {
3384 transport_controller_->SetActiveResetSrtpParams(
3385 modified_config.active_reset_srtp_params);
3386 }
3387
deadbeef293e9262017-01-11 12:28:30 -08003388 configuration_ = modified_config;
3389 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003390}
3391
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392bool PeerConnection::AddIceCandidate(
3393 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003394 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003395 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003396 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003397 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003398 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003399 return false;
3400 }
Steve Antond25da372017-11-06 14:50:29 -08003401
3402 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003403 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003404 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003405 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003406 return false;
3407 }
3408
3409 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003410 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003411 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003412 return false;
3413 }
3414
3415 bool valid = false;
3416 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3417 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003418 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003419 return false;
3420 }
3421
3422 // Add this candidate to the remote session description.
3423 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003424 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003425 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003426 return false;
3427 }
3428
3429 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003430 bool result = UseCandidate(ice_candidate);
3431 if (result) {
3432 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3433 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3434 } else {
3435 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3436 }
3437 return result;
Steve Antond25da372017-11-06 14:50:29 -08003438 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003439 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003440 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003441 return true;
3442 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443}
3444
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003445bool PeerConnection::RemoveIceCandidates(
3446 const std::vector<cricket::Candidate>& candidates) {
3447 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003448 if (IsClosed()) {
3449 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3450 return false;
3451 }
3452
Steve Antond25da372017-11-06 14:50:29 -08003453 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003454 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3455 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003456 return false;
3457 }
3458
3459 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003460 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003461 return false;
3462 }
3463
3464 size_t number_removed =
3465 mutable_remote_description()->RemoveCandidates(candidates);
3466 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003467 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003468 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003469 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003470 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003471 }
3472
3473 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003474 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3475 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003476 RTC_LOG(LS_ERROR)
3477 << "RemoveIceCandidates: Error when removing remote candidates: "
3478 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003479 }
3480 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003481}
3482
Niels Möller0c4f7be2018-05-07 14:01:37 +02003483RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003484 if (!worker_thread()->IsCurrent()) {
3485 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003486 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003487 }
3488
Niels Möller0c4f7be2018-05-07 14:01:37 +02003489 const bool has_min = bitrate.min_bitrate_bps.has_value();
3490 const bool has_start = bitrate.start_bitrate_bps.has_value();
3491 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003492 if (has_min && *bitrate.min_bitrate_bps < 0) {
3493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3494 "min_bitrate_bps <= 0");
3495 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003496 if (has_start) {
3497 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003499 "start_bitrate_bps < min_bitrate_bps");
3500 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3502 "curent_bitrate_bps < 0");
3503 }
3504 }
3505 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003506 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003508 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003509 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3511 "max_bitrate_bps < min_bitrate_bps");
3512 } else if (*bitrate.max_bitrate_bps < 0) {
3513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3514 "max_bitrate_bps < 0");
3515 }
3516 }
3517
zstein4b979802017-06-02 14:37:37 -07003518 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003519 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003520
3521 return RTCError::OK();
3522}
3523
Alex Narest78609d52017-10-20 10:37:47 +02003524void PeerConnection::SetBitrateAllocationStrategy(
3525 std::unique_ptr<rtc::BitrateAllocationStrategy>
3526 bitrate_allocation_strategy) {
3527 rtc::Thread* worker_thread = factory_->worker_thread();
3528 if (!worker_thread->IsCurrent()) {
3529 rtc::BitrateAllocationStrategy* strategy_raw =
3530 bitrate_allocation_strategy.release();
3531 auto functor = [this, strategy_raw]() {
3532 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003533 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003534 };
3535 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3536 return;
3537 }
3538 RTC_DCHECK(call_.get());
3539 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3540}
3541
henrika5f6bf242017-11-01 11:06:56 +01003542void PeerConnection::SetAudioPlayout(bool playout) {
3543 if (!worker_thread()->IsCurrent()) {
3544 worker_thread()->Invoke<void>(
3545 RTC_FROM_HERE,
3546 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3547 return;
3548 }
3549 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003550 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003551 audio_state->SetPlayout(playout);
3552}
3553
3554void PeerConnection::SetAudioRecording(bool recording) {
3555 if (!worker_thread()->IsCurrent()) {
3556 worker_thread()->Invoke<void>(
3557 RTC_FROM_HERE,
3558 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3559 return;
3560 }
3561 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003562 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003563 audio_state->SetRecording(recording);
3564}
3565
Steve Anton8c0f7a72017-10-03 10:03:10 -07003566std::unique_ptr<rtc::SSLCertificate>
3567PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003568 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3569 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003570 return nullptr;
3571 }
Steve Antonf25303e2018-10-16 15:23:31 -07003572 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003573}
3574
Zhi Huang70b820f2018-01-27 14:16:15 -08003575std::unique_ptr<rtc::SSLCertChain>
3576PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003577 auto audio_transceiver = GetFirstAudioTransceiver();
3578 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003579 return nullptr;
3580 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003581 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003582 audio_transceiver->internal()->channel()->transport_name());
3583}
3584
3585rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3586PeerConnection::GetFirstAudioTransceiver() const {
3587 for (auto transceiver : transceivers_) {
3588 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3589 return transceiver;
3590 }
3591 }
3592 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003593}
3594
ivoc14d5dbe2016-07-04 07:06:55 -07003595bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3596 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003597 // TODO(eladalon): It would be better to not allow negative values into PC.
3598 const size_t max_size = (max_size_bytes < 0)
3599 ? RtcEventLog::kUnlimitedOutput
3600 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003601 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3602 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3603 output_period_ms = 5000;
3604 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003605 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003606 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003607 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003608}
3609
Bjorn Tereliusde939432017-11-20 17:38:14 +01003610bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3611 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003612 // TODO(eladalon): In C++14, this can be done with a lambda.
3613 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003614 bool operator()() {
3615 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3616 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003617 PeerConnection* const pc;
3618 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003619 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003620 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003621 return worker_thread()->Invoke<bool>(
3622 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003623}
3624
3625void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003626 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003627 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3628}
3629
Harald Alvestrandad88c882018-11-28 16:47:46 +01003630rtc::scoped_refptr<DtlsTransportInterface>
3631PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3632 return transport_controller_->LookupDtlsTransportByMid(mid);
3633}
3634
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003635rtc::scoped_refptr<DtlsTransport>
3636PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3637 return transport_controller_->LookupDtlsTransportByMid(mid);
3638}
3639
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003640const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003641 return pending_local_description_ ? pending_local_description_.get()
3642 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003643}
3644
3645const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003646 return pending_remote_description_ ? pending_remote_description_.get()
3647 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003648}
3649
deadbeeffe4a8a42016-12-20 17:56:17 -08003650const SessionDescriptionInterface* PeerConnection::current_local_description()
3651 const {
Steve Anton75737c02017-11-06 10:37:17 -08003652 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003653}
3654
3655const SessionDescriptionInterface* PeerConnection::current_remote_description()
3656 const {
Steve Anton75737c02017-11-06 10:37:17 -08003657 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003658}
3659
3660const SessionDescriptionInterface* PeerConnection::pending_local_description()
3661 const {
Steve Anton75737c02017-11-06 10:37:17 -08003662 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003663}
3664
3665const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3666 const {
Steve Anton75737c02017-11-06 10:37:17 -08003667 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003668}
3669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003670void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003671 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003672 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003673 // Update stats here so that we have the most recent stats for tracks and
3674 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003675 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003676
Steve Anton75737c02017-11-06 10:37:17 -08003677 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003678 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003679
Mirko Bonadei739baf02019-01-27 17:29:42 +01003680 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003681 transceiver->Stop();
3682 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003683
3684 // Ensure that all asynchronous stats requests are completed before destroying
3685 // the transport controller below.
3686 if (stats_collector_) {
3687 stats_collector_->WaitForPendingRequest();
3688 }
3689
3690 // Don't destroy BaseChannels until after stats has been cleaned up so that
3691 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003692 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003693
Qingsi Wang93a84392018-01-30 17:13:09 -08003694 // The event log is used in the transport controller, which must be outlived
3695 // by the former. CreateOffer by the peer connection is implemented
3696 // asynchronously and if the peer connection is closed without resetting the
3697 // WebRTC session description factory, the session description factory would
3698 // call the transport controller.
3699 webrtc_session_desc_factory_.reset();
3700 transport_controller_.reset();
3701
deadbeef42a42632017-03-10 15:18:00 -08003702 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003703 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3704 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003705
Steve Anton978b8762017-09-29 12:15:02 -07003706 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003707 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003708 call_.reset();
3709 // The event log must outlive call (and any other object that uses it).
3710 event_log_.reset();
3711 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003712 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003713 // The .h file says that observer can be discarded after close() returns.
3714 // Make sure this is true.
3715 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003716}
3717
Steve Antonad182762018-09-05 20:22:40 +00003718void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003719 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003720 switch (msg->message_id) {
3721 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3722 SetSessionDescriptionMsg* param =
3723 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3724 param->observer->OnSuccess();
3725 delete param;
3726 break;
3727 }
3728 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3729 SetSessionDescriptionMsg* param =
3730 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3731 param->observer->OnFailure(std::move(param->error));
3732 delete param;
3733 break;
3734 }
3735 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3736 CreateSessionDescriptionMsg* param =
3737 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3738 param->observer->OnFailure(std::move(param->error));
3739 delete param;
3740 break;
3741 }
3742 case MSG_GETSTATS: {
3743 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3744 StatsReports reports;
3745 stats_->GetStats(param->track, &reports);
3746 param->observer->OnComplete(reports);
3747 delete param;
3748 break;
3749 }
3750 case MSG_FREE_DATACHANNELS: {
3751 sctp_data_channels_to_free_.clear();
3752 break;
3753 }
3754 case MSG_REPORT_USAGE_PATTERN: {
3755 ReportUsagePattern();
3756 break;
3757 }
3758 default:
3759 RTC_NOTREACHED() << "Not implemented";
3760 break;
3761 }
3762}
3763
Steve Antonafb0bb72018-02-20 11:35:37 -08003764cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3765 RTC_DCHECK(!IsUnifiedPlan());
3766 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3767 GetAudioTransceiver()->internal()->channel());
3768 if (voice_channel) {
3769 return voice_channel->media_channel();
3770 } else {
3771 return nullptr;
3772 }
3773}
3774
3775cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3776 RTC_DCHECK(!IsUnifiedPlan());
3777 auto* video_channel = static_cast<cricket::VideoChannel*>(
3778 GetVideoTransceiver()->internal()->channel());
3779 if (video_channel) {
3780 return video_channel->media_channel();
3781 } else {
3782 return nullptr;
3783 }
3784}
3785
Steve Anton4171afb2017-11-20 10:20:22 -08003786void PeerConnection::CreateAudioReceiver(
3787 MediaStreamInterface* stream,
3788 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003789 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3790 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003791 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3792 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003793 auto* audio_receiver = new AudioRtpReceiver(
3794 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003795 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003796 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3797 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3798 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003799 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003800 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003801 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003802}
3803
Steve Anton4171afb2017-11-20 10:20:22 -08003804void PeerConnection::CreateVideoReceiver(
3805 MediaStreamInterface* stream,
3806 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003807 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3808 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003809 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3810 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003811 auto* video_receiver = new VideoRtpReceiver(
3812 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003813 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003814 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3815 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3816 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003817 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003818 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003819 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003820}
3821
deadbeef70ab1a12015-09-28 16:53:55 -07003822// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3823// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003824rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003825 const RtpSenderInfo& remote_sender_info) {
3826 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3827 if (!receiver) {
3828 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3829 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003830 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003831 }
Steve Anton4171afb2017-11-20 10:20:22 -08003832 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3833 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3834 } else {
3835 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3836 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003837 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003838}
3839
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003840void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3841 MediaStreamInterface* stream) {
3842 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003843 RTC_DCHECK(track);
3844 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003845 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003846 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003847 // We already have a sender for this track, so just change the stream_id
3848 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003849 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003850 return;
3851 }
3852
3853 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003854 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003855 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003856 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003857 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003858 // If the sender has already been configured in SDP, we call SetSsrc,
3859 // which will connect the sender to the underlying transport. This can
3860 // occur if a local session description that contains the ID of the sender
3861 // is set before AddStream is called. It can also occur if the local
3862 // session description is not changed and RemoveStream is called, and
3863 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003864 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003865 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003866 if (sender_info) {
3867 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003868 }
3869}
3870
3871// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3872// indefinitely, when we have unified plan SDP.
3873void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3874 MediaStreamInterface* stream) {
3875 RTC_DCHECK(!IsClosed());
3876 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003877 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003878 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3879 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003880 return;
3881 }
Steve Anton4171afb2017-11-20 10:20:22 -08003882 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003883}
3884
3885void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3886 MediaStreamInterface* stream) {
3887 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003888 RTC_DCHECK(track);
3889 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003890 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003891 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003892 // We already have a sender for this track, so just change the stream_id
3893 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003894 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003895 return;
3896 }
3897
3898 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003899 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003900 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003901 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003902 GetVideoTransceiver()->internal()->AddSender(new_sender);
3903 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003904 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003905 if (sender_info) {
3906 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003907 }
3908}
3909
3910void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3911 MediaStreamInterface* stream) {
3912 RTC_DCHECK(!IsClosed());
3913 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003914 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003915 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3916 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003917 return;
3918 }
Steve Anton4171afb2017-11-20 10:20:22 -08003919 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003920}
3921
Steve Antonba818672017-11-06 10:21:57 -08003922void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08003923 if (ice_connection_state_ == new_state) {
3924 return;
3925 }
3926
deadbeefcbecd352015-09-23 11:50:27 -07003927 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003928 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003929 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003930 return;
3931 }
Steve Antonba818672017-11-06 10:21:57 -08003932
Mirko Bonadei675513b2017-11-09 11:09:25 +01003933 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3934 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003935 RTC_DCHECK(ice_connection_state_ !=
3936 PeerConnectionInterface::kIceConnectionClosed);
3937
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003938 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003939 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003940}
3941
Alex Loiko9289eda2018-11-23 16:18:59 +00003942void PeerConnection::SetStandardizedIceConnectionState(
3943 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00003944 if (standardized_ice_connection_state_ == new_state)
3945 return;
3946 if (IsClosed())
3947 return;
3948 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003949 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003950}
3951
Jonas Olsson635474e2018-10-18 15:58:17 +02003952void PeerConnection::SetConnectionState(
3953 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02003954 if (connection_state_ == new_state)
3955 return;
3956 if (IsClosed())
3957 return;
3958 connection_state_ = new_state;
3959 Observer()->OnConnectionChange(new_state);
3960}
3961
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003962void PeerConnection::OnIceGatheringChange(
3963 PeerConnectionInterface::IceGatheringState new_state) {
3964 if (IsClosed()) {
3965 return;
3966 }
3967 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003968 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003969}
3970
jbauch81bf7b02017-03-25 08:31:12 -07003971void PeerConnection::OnIceCandidate(
3972 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07003973 if (IsClosed()) {
3974 return;
3975 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003976 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003977 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3978 candidate->candidate().address().IsPrivateIP()) {
3979 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3980 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003981 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003982}
3983
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003984void PeerConnection::OnIceCandidatesRemoved(
3985 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07003986 if (IsClosed()) {
3987 return;
3988 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003989 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003990}
3991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003992void PeerConnection::ChangeSignalingState(
3993 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003994 if (signaling_state_ == signaling_state) {
3995 return;
3996 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003997 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3998 << GetSignalingStateString(signaling_state_)
3999 << " New state: "
4000 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004001 signaling_state_ = signaling_state;
4002 if (signaling_state == kClosed) {
4003 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004004 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004005 standardized_ice_connection_state_ =
4006 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004007 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4008 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004009 if (ice_gathering_state_ != kIceGatheringComplete) {
4010 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004011 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004012 }
4013 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004014 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004015}
4016
deadbeefeb459812015-12-15 19:24:43 -08004017void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4018 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004019 if (IsClosed()) {
4020 return;
4021 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004022 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004023 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004024}
4025
deadbeefeb459812015-12-15 19:24:43 -08004026void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4027 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004028 if (IsClosed()) {
4029 return;
4030 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004031 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004032 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004033}
4034
4035void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4036 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004037 if (IsClosed()) {
4038 return;
4039 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004040 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004041 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004042}
4043
4044void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4045 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004046 if (IsClosed()) {
4047 return;
4048 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004049 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004050 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004051}
4052
Henrik Boström31638672017-11-23 17:48:32 +01004053void PeerConnection::PostSetSessionDescriptionSuccess(
4054 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004055 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4056 signaling_thread()->Post(RTC_FROM_HERE, this,
4057 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004058}
4059
deadbeefab9b2d12015-10-14 11:33:11 -07004060void PeerConnection::PostSetSessionDescriptionFailure(
4061 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004062 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004063 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004064 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4065 msg->error = std::move(error);
4066 signaling_thread()->Post(RTC_FROM_HERE, this,
4067 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004068}
4069
4070void PeerConnection::PostCreateSessionDescriptionFailure(
4071 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004072 RTCError error) {
4073 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004074 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4075 msg->error = std::move(error);
4076 signaling_thread()->Post(RTC_FROM_HERE, this,
4077 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004078}
4079
zhihuang1c378ed2017-08-17 14:10:50 -07004080void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004081 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004082 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004083 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004084
Steve Antondcc3c022017-12-22 16:02:54 -08004085 if (IsUnifiedPlan()) {
4086 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4087 } else {
4088 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4089 }
4090
Steve Antonfa2260d2017-12-28 16:38:23 -08004091 // Intentionally unset the data channel type for RTP data channel with the
4092 // second condition. Otherwise the RTP data channels would be successfully
4093 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4094 // when building with chromium. We want to leave RTP data channels broken, so
4095 // people won't try to use them.
4096 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4097 session_options->data_channel_type = data_channel_type();
4098 }
4099
Steve Antondcc3c022017-12-22 16:02:54 -08004100 // Apply ICE restart flag and renomination flag.
4101 for (auto& options : session_options->media_description_options) {
4102 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4103 options.transport_options.enable_ice_renomination =
4104 configuration_.enable_ice_renomination;
4105 }
4106
4107 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004108 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004109 session_options->pooled_ice_credentials =
4110 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4111 RTC_FROM_HERE,
4112 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4113 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004114 session_options->offer_extmap_allow_mixed =
4115 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004116}
4117
4118void PeerConnection::GetOptionsForPlanBOffer(
4119 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4120 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004121 // Figure out transceiver directional preferences.
4122 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4123 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4124
4125 // By default, generate sendrecv/recvonly m= sections.
4126 bool recv_audio = true;
4127 bool recv_video = true;
4128
4129 // By default, only offer a new m= section if we have media to send with it.
4130 bool offer_new_audio_description = send_audio;
4131 bool offer_new_video_description = send_video;
4132 bool offer_new_data_description = HasDataChannels();
4133
4134 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004135 if (offer_answer_options.offer_to_receive_audio !=
4136 RTCOfferAnswerOptions::kUndefined) {
4137 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004138 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004139 offer_new_audio_description ||
4140 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004141 }
Steve Antondcc3c022017-12-22 16:02:54 -08004142 if (offer_answer_options.offer_to_receive_video !=
4143 RTCOfferAnswerOptions::kUndefined) {
4144 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004145 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004146 offer_new_video_description ||
4147 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004148 }
4149
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004150 absl::optional<size_t> audio_index;
4151 absl::optional<size_t> video_index;
4152 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004153 // If a current description exists, generate m= sections in the same order,
4154 // using the first audio/video/data section that appears and rejecting
4155 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004156 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004157 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004158 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004159 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4160 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4161 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004162 }
4163
zhihuang1c378ed2017-08-17 14:10:50 -07004164 // Add audio/video/data m= sections to the end if needed.
4165 if (!audio_index && offer_new_audio_description) {
4166 session_options->media_description_options.push_back(
4167 cricket::MediaDescriptionOptions(
4168 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004169 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4170 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004171 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004172 }
zhihuang1c378ed2017-08-17 14:10:50 -07004173 if (!video_index && offer_new_video_description) {
4174 session_options->media_description_options.push_back(
4175 cricket::MediaDescriptionOptions(
4176 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004177 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4178 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004179 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004180 }
zhihuang1c378ed2017-08-17 14:10:50 -07004181 if (!data_index && offer_new_data_description) {
4182 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004183 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004184 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004185 }
4186
4187 cricket::MediaDescriptionOptions* audio_media_description_options =
4188 !audio_index ? nullptr
4189 : &session_options->media_description_options[*audio_index];
4190 cricket::MediaDescriptionOptions* video_media_description_options =
4191 !video_index ? nullptr
4192 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004193
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004194 AddPlanBRtpSenderOptions(GetSendersInternal(),
4195 audio_media_description_options,
4196 video_media_description_options,
4197 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004198}
4199
Steve Antondcc3c022017-12-22 16:02:54 -08004200static cricket::MediaDescriptionOptions
4201GetMediaDescriptionOptionsForTransceiver(
4202 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4203 transceiver,
4204 const std::string& mid) {
4205 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004206 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004207 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004208 // This behavior is specified in JSEP. The gist is that:
4209 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4210 // sendrecv.
4211 // 2. If the MSID is included, then it must be included in any subsequent
4212 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004213 if (transceiver->stopped() ||
4214 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4215 !transceiver->internal()->has_ever_been_used_to_send())) {
4216 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004217 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004218
4219 cricket::SenderOptions sender_options;
4220 sender_options.track_id = transceiver->sender()->id();
4221 sender_options.stream_ids = transceiver->sender()->stream_ids();
4222
4223 // The following sets up RIDs and Simulcast.
4224 // RIDs are included if Simulcast is requested or if any RID was specified.
4225 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004226 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4227 send_parameters.encodings.end(),
4228 [](const RtpEncodingParameters& encoding) {
4229 return !encoding.rid.empty();
4230 });
4231
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004232 std::vector<RidDescription> send_rids;
4233 SimulcastLayerList send_layers;
4234 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4235 if (encoding.rid.empty()) {
4236 continue;
4237 }
4238 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4239 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4240 }
4241
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004242 if (has_rids) {
4243 sender_options.rids = send_rids;
4244 }
4245
4246 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004247 // When RIDs are configured, we must set num_sim_layers to 0 to.
4248 // Otherwise, num_sim_layers must be 1 because either there is no
4249 // simulcast, or simulcast is acheived by munging the SDP.
4250 sender_options.num_sim_layers = has_rids ? 0 : 1;
4251 media_description_options.sender_options.push_back(sender_options);
4252
Steve Antondcc3c022017-12-22 16:02:54 -08004253 return media_description_options;
4254}
4255
Steve Anton5c72e712018-12-10 14:25:30 -08004256// Returns the ContentInfo at mline index |i|, or null if none exists.
4257static const ContentInfo* GetContentByIndex(
4258 const SessionDescriptionInterface* sdesc,
4259 size_t i) {
4260 if (!sdesc) {
4261 return nullptr;
4262 }
4263 const ContentInfos& contents = sdesc->description()->contents();
4264 return (i < contents.size() ? &contents[i] : nullptr);
4265}
4266
Steve Antondcc3c022017-12-22 16:02:54 -08004267void PeerConnection::GetOptionsForUnifiedPlanOffer(
4268 const RTCOfferAnswerOptions& offer_answer_options,
4269 cricket::MediaSessionOptions* session_options) {
4270 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4271 // Offers) and 5.2.2 (Subsequent Offers).
4272 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4273 const ContentInfos& local_contents =
4274 (local_description() ? local_description()->description()->contents()
4275 : ContentInfos());
4276 const ContentInfos& remote_contents =
4277 (remote_description() ? remote_description()->description()->contents()
4278 : ContentInfos());
4279 // The mline indices that can be recycled. New transceivers should reuse these
4280 // slots first.
4281 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004282 // First, go through each media section that exists in either the local or
4283 // remote description and generate a media section in this offer for the
4284 // associated transceiver. If a media section can be recycled, generate a
4285 // default, rejected media section here that can be later overwritten.
4286 for (size_t i = 0;
4287 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4288 // Either |local_content| or |remote_content| is non-null.
4289 const ContentInfo* local_content =
4290 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004291 const ContentInfo* current_local_content =
4292 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004293 const ContentInfo* remote_content =
4294 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004295 const ContentInfo* current_remote_content =
4296 GetContentByIndex(current_remote_description(), i);
4297 bool had_been_rejected =
4298 (current_local_content && current_local_content->rejected) ||
4299 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004300 const std::string& mid =
4301 (local_content ? local_content->name : remote_content->name);
4302 cricket::MediaType media_type =
4303 (local_content ? local_content->media_description()->type()
4304 : remote_content->media_description()->type());
4305 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4306 media_type == cricket::MEDIA_TYPE_VIDEO) {
4307 auto transceiver = GetAssociatedTransceiver(mid);
4308 RTC_CHECK(transceiver);
4309 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004310 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004311 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004312 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004313 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4314 RtpTransceiverDirection::kInactive,
4315 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004316 recycleable_mline_indices.push(i);
4317 } else {
4318 session_options->media_description_options.push_back(
4319 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4320 // CreateOffer shouldn't really cause any state changes in
4321 // PeerConnection, but we need a way to match new transceivers to new
4322 // media sections in SetLocalDescription and JSEP specifies this is done
4323 // by recording the index of the media section generated for the
4324 // transceiver in the offer.
4325 transceiver->internal()->set_mline_index(i);
4326 }
4327 } else {
4328 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004329 RTC_CHECK(GetDataMid());
4330 if (had_been_rejected || mid != *GetDataMid()) {
4331 session_options->media_description_options.push_back(
4332 GetMediaDescriptionOptionsForRejectedData(mid));
4333 } else {
4334 session_options->media_description_options.push_back(
4335 GetMediaDescriptionOptionsForActiveData(mid));
4336 }
Steve Antondcc3c022017-12-22 16:02:54 -08004337 }
4338 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004339
Steve Antondcc3c022017-12-22 16:02:54 -08004340 // Next, look for transceivers that are newly added (that is, are not stopped
4341 // and not associated). Reuse media sections marked as recyclable first,
4342 // otherwise append to the end of the offer. New media sections should be
4343 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004344 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004345 if (transceiver->mid() || transceiver->stopped()) {
4346 continue;
4347 }
4348 size_t mline_index;
4349 if (!recycleable_mline_indices.empty()) {
4350 mline_index = recycleable_mline_indices.front();
4351 recycleable_mline_indices.pop();
4352 session_options->media_description_options[mline_index] =
4353 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004354 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004355 } else {
4356 mline_index = session_options->media_description_options.size();
4357 session_options->media_description_options.push_back(
4358 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004359 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004360 }
4361 // See comment above for why CreateOffer changes the transceiver's state.
4362 transceiver->internal()->set_mline_index(mline_index);
4363 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004364 // Lastly, add a m-section if we have local data channels and an m section
4365 // does not already exist.
4366 if (!GetDataMid() && HasDataChannels()) {
4367 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004368 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004369 }
Steve Antondcc3c022017-12-22 16:02:54 -08004370}
4371
4372void PeerConnection::GetOptionsForAnswer(
4373 const RTCOfferAnswerOptions& offer_answer_options,
4374 cricket::MediaSessionOptions* session_options) {
4375 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4376
4377 if (IsUnifiedPlan()) {
4378 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4379 } else {
4380 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4381 }
4382
Steve Antonfa2260d2017-12-28 16:38:23 -08004383 // Intentionally unset the data channel type for RTP data channel. Otherwise
4384 // the RTP data channels would be successfully negotiated by default and the
4385 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4386 // We want to leave RTP data channels broken, so people won't try to use them.
4387 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4388 session_options->data_channel_type = data_channel_type();
4389 }
4390
Steve Antondcc3c022017-12-22 16:02:54 -08004391 // Apply ICE renomination flag.
4392 for (auto& options : session_options->media_description_options) {
4393 options.transport_options.enable_ice_renomination =
4394 configuration_.enable_ice_renomination;
4395 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004396
4397 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004398 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004399 session_options->pooled_ice_credentials =
4400 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4401 RTC_FROM_HERE,
4402 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4403 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004404}
4405
Steve Antondcc3c022017-12-22 16:02:54 -08004406void PeerConnection::GetOptionsForPlanBAnswer(
4407 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004408 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004409 // Figure out transceiver directional preferences.
4410 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4411 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4412
4413 // By default, generate sendrecv/recvonly m= sections. The direction is also
4414 // restricted by the direction in the offer.
4415 bool recv_audio = true;
4416 bool recv_video = true;
4417
4418 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004419 if (offer_answer_options.offer_to_receive_audio !=
4420 RTCOfferAnswerOptions::kUndefined) {
4421 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004422 }
Steve Antondcc3c022017-12-22 16:02:54 -08004423 if (offer_answer_options.offer_to_receive_video !=
4424 RTCOfferAnswerOptions::kUndefined) {
4425 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004426 }
4427
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004428 absl::optional<size_t> audio_index;
4429 absl::optional<size_t> video_index;
4430 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004431
4432 // Generate m= sections that match those in the offer.
4433 // Note that mediasession.cc will handle intersection our preferred
4434 // direction with the offered direction.
4435 GenerateMediaDescriptionOptions(
4436 remote_description(),
4437 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4438 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4439 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004440
4441 cricket::MediaDescriptionOptions* audio_media_description_options =
4442 !audio_index ? nullptr
4443 : &session_options->media_description_options[*audio_index];
4444 cricket::MediaDescriptionOptions* video_media_description_options =
4445 !video_index ? nullptr
4446 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004447
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004448 AddPlanBRtpSenderOptions(GetSendersInternal(),
4449 audio_media_description_options,
4450 video_media_description_options,
4451 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004452}
zhihuangaf388472016-11-02 16:49:48 -07004453
Steve Antondcc3c022017-12-22 16:02:54 -08004454void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4455 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4456 cricket::MediaSessionOptions* session_options) {
4457 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4458 // Answers) and 5.3.2 (Subsequent Answers).
4459 RTC_DCHECK(remote_description());
4460 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4461 for (const ContentInfo& content :
4462 remote_description()->description()->contents()) {
4463 cricket::MediaType media_type = content.media_description()->type();
4464 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4465 media_type == cricket::MEDIA_TYPE_VIDEO) {
4466 auto transceiver = GetAssociatedTransceiver(content.name);
4467 RTC_CHECK(transceiver);
4468 session_options->media_description_options.push_back(
4469 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4470 } else {
4471 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004472 // Reject all data sections if data channels are disabled.
4473 // Reject a data section if it has already been rejected.
4474 // Reject all data sections except for the first one.
4475 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4476 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004477 session_options->media_description_options.push_back(
4478 GetMediaDescriptionOptionsForRejectedData(content.name));
4479 } else {
4480 session_options->media_description_options.push_back(
4481 GetMediaDescriptionOptionsForActiveData(content.name));
4482 }
Steve Antondcc3c022017-12-22 16:02:54 -08004483 }
4484 }
htaa2a49d92016-03-04 02:51:39 -08004485}
4486
zhihuang1c378ed2017-08-17 14:10:50 -07004487void PeerConnection::GenerateMediaDescriptionOptions(
4488 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004489 RtpTransceiverDirection audio_direction,
4490 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004491 absl::optional<size_t>* audio_index,
4492 absl::optional<size_t>* video_index,
4493 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004494 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004495 for (const cricket::ContentInfo& content :
4496 session_desc->description()->contents()) {
4497 if (IsAudioContent(&content)) {
4498 // If we already have an audio m= section, reject this extra one.
4499 if (*audio_index) {
4500 session_options->media_description_options.push_back(
4501 cricket::MediaDescriptionOptions(
4502 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004503 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004504 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004505 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004506 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004507 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4508 content.name, audio_direction,
4509 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004510 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004511 }
4512 } else if (IsVideoContent(&content)) {
4513 // If we already have an video m= section, reject this extra one.
4514 if (*video_index) {
4515 session_options->media_description_options.push_back(
4516 cricket::MediaDescriptionOptions(
4517 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004518 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004519 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004520 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004521 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004522 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4523 content.name, video_direction,
4524 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004525 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004526 }
4527 } else {
4528 RTC_DCHECK(IsDataContent(&content));
4529 // If we already have an data m= section, reject this extra one.
4530 if (*data_index) {
4531 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004532 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004533 } else {
4534 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004535 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004536 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004537 }
4538 }
htaa2a49d92016-03-04 02:51:39 -08004539 }
deadbeefab9b2d12015-10-14 11:33:11 -07004540}
4541
Steve Antonfa2260d2017-12-28 16:38:23 -08004542cricket::MediaDescriptionOptions
4543PeerConnection::GetMediaDescriptionOptionsForActiveData(
4544 const std::string& mid) const {
4545 // Direction for data sections is meaningless, but legacy endpoints might
4546 // expect sendrecv.
4547 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4548 RtpTransceiverDirection::kSendRecv,
4549 /*stopped=*/false);
4550 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4551 return options;
4552}
4553
4554cricket::MediaDescriptionOptions
4555PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4556 const std::string& mid) const {
4557 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4558 RtpTransceiverDirection::kInactive,
4559 /*stopped=*/true);
4560 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4561 return options;
4562}
4563
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004564absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004565 switch (data_channel_type_) {
4566 case cricket::DCT_RTP:
4567 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004568 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004569 }
4570 return rtp_data_channel_->content_name();
4571 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004572 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004573 case cricket::DCT_MEDIA_TRANSPORT:
4574 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004575 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004576 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004577 }
4578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4581 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4582 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004583 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004584}
4585
Steve Anton4171afb2017-11-20 10:20:22 -08004586void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004587 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004588 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004589 cricket::MediaType media_type,
4590 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004591 RTC_DCHECK(!IsUnifiedPlan());
4592
Steve Anton4171afb2017-11-20 10:20:22 -08004593 std::vector<RtpSenderInfo>* current_senders =
4594 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004595
Steve Anton4171afb2017-11-20 10:20:22 -08004596 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004597 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004598 for (auto sender_it = current_senders->begin();
4599 sender_it != current_senders->end();
4600 /* incremented manually */) {
4601 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004602 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004603 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004604 std::string params_stream_id;
4605 if (params) {
4606 params_stream_id =
4607 (!params->first_stream_id().empty() ? params->first_stream_id()
4608 : kDefaultStreamId);
4609 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004610 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004611 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004612 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004613 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004614 sender_exists) {
4615 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004616 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004617 OnRemoteSenderRemoved(info, media_type);
4618 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004619 }
4620 }
4621
Steve Anton4171afb2017-11-20 10:20:22 -08004622 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004623 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004624 if (!params.has_ssrcs()) {
4625 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4626 // sender, this means it is coming from a Unified Plan endpoint,so we just
4627 // create a default.
4628 default_sender_needed = true;
4629 break;
4630 }
4631
Seth Hampson845e8782018-03-02 11:34:10 -08004632 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004633 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004634 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4635 // not supported in Plan B, we just take the first here and create the
4636 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004637 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004638 (!params.first_stream_id().empty() ? params.first_stream_id()
4639 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004640 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004641 uint32_t ssrc = params.first_ssrc();
4642
4643 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004644 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004645 if (!stream) {
4646 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004647 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004648 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004649 remote_streams_->AddStream(stream);
4650 new_streams->AddStream(stream);
4651 }
4652
Steve Anton4171afb2017-11-20 10:20:22 -08004653 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004654 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004655 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004656 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004657 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004658 }
4659 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004660
Steve Anton4171afb2017-11-20 10:20:22 -08004661 // Add default sender if necessary.
4662 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004663 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004664 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004665 if (!default_stream) {
4666 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004667 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004668 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004669 remote_streams_->AddStream(default_stream);
4670 new_streams->AddStream(default_stream);
4671 }
Steve Anton4171afb2017-11-20 10:20:22 -08004672 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4673 ? kDefaultAudioSenderId
4674 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004675 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004676 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004677 if (!default_sender_info) {
4678 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004679 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004680 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004681 }
4682 }
deadbeefab9b2d12015-10-14 11:33:11 -07004683}
4684
Steve Anton4171afb2017-11-20 10:20:22 -08004685void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4686 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004687 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4688 << " receiver for track_id=" << sender_info.sender_id
4689 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004690
Steve Anton3d954a62018-04-02 11:27:23 -07004691 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004692 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004693 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004694 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004695 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004696 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004697 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004698 }
4699}
4700
Steve Anton4171afb2017-11-20 10:20:22 -08004701void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4702 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004703 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4704 << " receiver for track_id=" << sender_info.sender_id
4705 << " and stream_id=" << sender_info.stream_id;
4706
Seth Hampson845e8782018-03-02 11:34:10 -08004707 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004708
Henrik Boström933d8b02017-10-10 10:05:16 -07004709 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004710 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004711 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4712 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004713 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004714 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004715 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004716 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004717 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004718 }
4719 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004720 // Stopping or destroying a VideoRtpReceiver will end the
4721 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004722 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004723 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004724 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004725 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004726 // There's no guarantee the track is still available, e.g. the track may
4727 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004728 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004729 }
4730 } else {
nisseede5da42017-01-12 05:15:36 -08004731 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004732 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004733 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004734 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004735 }
deadbeefab9b2d12015-10-14 11:33:11 -07004736}
4737
4738void PeerConnection::UpdateEndedRemoteMediaStreams() {
4739 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4740 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4741 MediaStreamInterface* stream = remote_streams_->at(i);
4742 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4743 streams_to_remove.push_back(stream);
4744 }
4745 }
4746
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004747 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004748 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004749 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004750 }
4751}
4752
Steve Anton4171afb2017-11-20 10:20:22 -08004753void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004754 const std::vector<cricket::StreamParams>& streams,
4755 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004756 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004757
Seth Hampson845e8782018-03-02 11:34:10 -08004758 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004759 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004760 for (auto sender_it = current_senders->begin();
4761 sender_it != current_senders->end();
4762 /* incremented manually */) {
4763 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004764 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004765 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4766 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004767 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004768 OnLocalSenderRemoved(info, media_type);
4769 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004770 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004771 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004772 }
4773 }
4774
Steve Anton4171afb2017-11-20 10:20:22 -08004775 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004776 for (const cricket::StreamParams& params : streams) {
4777 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004778 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004779 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004780 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004781 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004782 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004783 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004784 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004785 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004786 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004787 }
4788 }
4789}
4790
Steve Anton4171afb2017-11-20 10:20:22 -08004791void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4792 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004793 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004794 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004795 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004796 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4797 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004798 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004799 return;
4800 }
4801
deadbeeffac06552015-11-25 11:26:01 -08004802 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004803 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004804 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004805 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004806 }
deadbeeffac06552015-11-25 11:26:01 -08004807
Seth Hampson5b4f0752018-04-02 16:31:36 -07004808 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004809 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004810}
4811
Steve Anton4171afb2017-11-20 10:20:22 -08004812void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4813 cricket::MediaType media_type) {
4814 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004815 if (!sender) {
4816 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004817 // SessionDescriptions has been renegotiated.
4818 return;
4819 }
deadbeeffac06552015-11-25 11:26:01 -08004820
4821 // A sender has been removed from the SessionDescription but it's still
4822 // associated with the PeerConnection. This only occurs if the SDP doesn't
4823 // match with the calls to CreateSender, AddStream and RemoveStream.
4824 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
Steve Anton4171afb2017-11-20 10:20:22 -08004830 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004831}
4832
4833void PeerConnection::UpdateLocalRtpDataChannels(
4834 const cricket::StreamParamsVec& streams) {
4835 std::vector<std::string> existing_channels;
4836
4837 // Find new and active data channels.
4838 for (const cricket::StreamParams& params : streams) {
4839 // |it->sync_label| is actually the data channel label. The reason is that
4840 // we use the same naming of data channels as we do for
4841 // MediaStreams and Tracks.
4842 // For MediaStreams, the sync_label is the MediaStream label and the
4843 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004844 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004845 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004846 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004847 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004848 continue;
4849 }
4850 // Set the SSRC the data channel should use for sending.
4851 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4852 existing_channels.push_back(data_channel_it->first);
4853 }
4854
4855 UpdateClosingRtpDataChannels(existing_channels, true);
4856}
4857
4858void PeerConnection::UpdateRemoteRtpDataChannels(
4859 const cricket::StreamParamsVec& streams) {
4860 std::vector<std::string> existing_channels;
4861
4862 // Find new and active data channels.
4863 for (const cricket::StreamParams& params : streams) {
4864 // The data channel label is either the mslabel or the SSRC if the mslabel
4865 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004866 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004867 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004868 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004869 auto data_channel_it = rtp_data_channels_.find(label);
4870 if (data_channel_it == rtp_data_channels_.end()) {
4871 // This is a new data channel.
4872 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4873 } else {
4874 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4875 }
4876 existing_channels.push_back(label);
4877 }
4878
4879 UpdateClosingRtpDataChannels(existing_channels, false);
4880}
4881
4882void PeerConnection::UpdateClosingRtpDataChannels(
4883 const std::vector<std::string>& active_channels,
4884 bool is_local_update) {
4885 auto it = rtp_data_channels_.begin();
4886 while (it != rtp_data_channels_.end()) {
4887 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004888 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004889 ++it;
4890 continue;
4891 }
4892
4893 if (is_local_update) {
4894 data_channel->SetSendSsrc(0);
4895 } else {
4896 data_channel->RemotePeerRequestClose();
4897 }
4898
4899 if (data_channel->state() == DataChannel::kClosed) {
4900 rtp_data_channels_.erase(it);
4901 it = rtp_data_channels_.begin();
4902 } else {
4903 ++it;
4904 }
4905 }
4906}
4907
4908void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4909 uint32_t remote_ssrc) {
4910 rtc::scoped_refptr<DataChannel> channel(
4911 InternalCreateDataChannel(label, nullptr));
4912 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004913 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004914 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004915 return;
4916 }
4917 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004918 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4919 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004920 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004921}
4922
4923rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4924 const std::string& label,
4925 const InternalDataChannelInit* config) {
4926 if (IsClosed()) {
4927 return nullptr;
4928 }
Steve Anton75737c02017-11-06 10:37:17 -08004929 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004930 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004931 << "InternalCreateDataChannel: Data is not supported in this call.";
4932 return nullptr;
4933 }
4934 InternalDataChannelInit new_config =
4935 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004936 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004937 if (new_config.id < 0) {
4938 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004939 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004940 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004941 RTC_LOG(LS_ERROR)
4942 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004943 return nullptr;
4944 }
4945 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004946 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004947 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004948 return nullptr;
4949 }
4950 }
4951
Steve Anton75737c02017-11-06 10:37:17 -08004952 rtc::scoped_refptr<DataChannel> channel(
4953 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004954 if (!channel) {
4955 sid_allocator_.ReleaseSid(new_config.id);
4956 return nullptr;
4957 }
4958
4959 if (channel->data_channel_type() == cricket::DCT_RTP) {
4960 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004961 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4962 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004963 return nullptr;
4964 }
4965 rtp_data_channels_[channel->label()] = channel;
4966 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004967 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004968 sctp_data_channels_.push_back(channel);
4969 channel->SignalClosed.connect(this,
4970 &PeerConnection::OnSctpDataChannelClosed);
4971 }
4972
Steve Anton2d8609c2018-01-23 16:38:46 -08004973 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004974 return channel;
4975}
4976
4977bool PeerConnection::HasDataChannels() const {
4978 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4979}
4980
4981void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4982 for (const auto& channel : sctp_data_channels_) {
4983 if (channel->id() < 0) {
4984 int sid;
4985 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004987 continue;
4988 }
4989 channel->SetSctpSid(sid);
4990 }
4991 }
4992}
4993
4994void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004995 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004996 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4997 ++it) {
4998 if (it->get() == channel) {
4999 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005000 // After the closing procedure is done, it's safe to use this ID for
5001 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005002 sid_allocator_.ReleaseSid(channel->id());
5003 }
deadbeefbd292462015-12-14 18:15:29 -08005004 // Since this method is triggered by a signal from the DataChannel,
5005 // we can't free it directly here; we need to free it asynchronously.
5006 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005007 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005008 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5009 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005010 return;
5011 }
5012 }
5013}
5014
deadbeefab9b2d12015-10-14 11:33:11 -07005015void PeerConnection::OnDataChannelDestroyed() {
5016 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5017 // DataChannel may callback to us and try to modify the list.
5018 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5019 temp_rtp_dcs.swap(rtp_data_channels_);
5020 for (const auto& kv : temp_rtp_dcs) {
5021 kv.second->OnTransportChannelDestroyed();
5022 }
5023
5024 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5025 temp_sctp_dcs.swap(sctp_data_channels_);
5026 for (const auto& channel : temp_sctp_dcs) {
5027 channel->OnTransportChannelDestroyed();
5028 }
5029}
5030
5031void PeerConnection::OnDataChannelOpenMessage(
5032 const std::string& label,
5033 const InternalDataChannelInit& config) {
5034 rtc::scoped_refptr<DataChannel> channel(
5035 InternalCreateDataChannel(label, &config));
5036 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005037 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005038 return;
5039 }
5040
deadbeefa601f5c2016-06-06 14:27:39 -07005041 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5042 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005043 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005044 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005045}
5046
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005047bool PeerConnection::HandleOpenMessage_s(
5048 const cricket::ReceiveDataParams& params,
5049 const rtc::CopyOnWriteBuffer& buffer) {
5050 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5051 // Received OPEN message; parse and signal that a new data channel should
5052 // be created.
5053 std::string label;
5054 InternalDataChannelInit config;
5055 config.id = params.ssrc;
5056 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5057 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5058 << params.ssrc;
5059 return true;
5060 }
5061 config.open_handshake_role = InternalDataChannelInit::kAcker;
5062 OnDataChannelOpenMessage(label, config);
5063 return true;
5064 }
5065 return false;
5066}
5067
Steve Anton4171afb2017-11-20 10:20:22 -08005068rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5069PeerConnection::GetAudioTransceiver() const {
5070 // This method only works with Plan B SDP, where there is a single
5071 // audio/video transceiver.
5072 RTC_DCHECK(!IsUnifiedPlan());
5073 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005074 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005075 return transceiver;
5076 }
5077 }
5078 RTC_NOTREACHED();
5079 return nullptr;
5080}
5081
5082rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5083PeerConnection::GetVideoTransceiver() const {
5084 // This method only works with Plan B SDP, where there is a single
5085 // audio/video transceiver.
5086 RTC_DCHECK(!IsUnifiedPlan());
5087 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005088 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005089 return transceiver;
5090 }
5091 }
5092 RTC_NOTREACHED();
5093 return nullptr;
5094}
5095
5096// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5097// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005098bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005099 switch (type) {
5100 case cricket::MEDIA_TYPE_AUDIO:
5101 return !GetAudioTransceiver()->internal()->senders().empty();
5102 case cricket::MEDIA_TYPE_VIDEO:
5103 return !GetVideoTransceiver()->internal()->senders().empty();
5104 case cricket::MEDIA_TYPE_DATA:
5105 return false;
5106 }
5107 RTC_NOTREACHED();
5108 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005109}
5110
Steve Anton4171afb2017-11-20 10:20:22 -08005111rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5112PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005113 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005114 for (auto sender : transceiver->internal()->senders()) {
5115 if (sender->track() == track) {
5116 return sender;
5117 }
5118 }
5119 }
5120 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005121}
5122
Steve Anton4171afb2017-11-20 10:20:22 -08005123rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5124PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005125 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005126 for (auto sender : transceiver->internal()->senders()) {
5127 if (sender->id() == sender_id) {
5128 return sender;
5129 }
5130 }
5131 }
5132 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005133}
5134
Steve Anton4171afb2017-11-20 10:20:22 -08005135rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5136PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005137 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005138 for (auto receiver : transceiver->internal()->receivers()) {
5139 if (receiver->id() == receiver_id) {
5140 return receiver;
5141 }
5142 }
5143 }
5144 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005145}
5146
Steve Anton4171afb2017-11-20 10:20:22 -08005147std::vector<PeerConnection::RtpSenderInfo>*
5148PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5149 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5150 media_type == cricket::MEDIA_TYPE_VIDEO);
5151 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5152 ? &remote_audio_sender_infos_
5153 : &remote_video_sender_infos_;
5154}
5155
5156std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005157 cricket::MediaType media_type) {
5158 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5159 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005160 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5161 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005162}
5163
Steve Anton4171afb2017-11-20 10:20:22 -08005164const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5165 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005166 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005167 const std::string sender_id) const {
5168 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005169 if (sender_info.stream_id == stream_id &&
5170 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005171 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005172 }
5173 }
5174 return nullptr;
5175}
5176
5177DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5178 for (const auto& channel : sctp_data_channels_) {
5179 if (channel->id() == sid) {
5180 return channel;
5181 }
5182 }
5183 return nullptr;
5184}
5185
deadbeef91dd5672016-05-18 16:55:30 -07005186bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005187 const cricket::ServerAddresses& stun_servers,
5188 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005189 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005190 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005191 // To handle both internal and externally created port allocator, we will
5192 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005193 port_allocator_flags_ = port_allocator_->flags();
5194 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5195 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5196 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005197 // If the disable-IPv6 flag was specified, we'll not override it
5198 // by experiment.
5199 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005200 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005201 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5202 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005203 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005204 }
5205
zhihuangb09b3f92017-03-07 14:40:51 -08005206 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005207 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005208 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005209 }
5210
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005211 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005212 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005213 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005214 }
5215
honghaiz60347052016-05-31 18:29:12 -07005216 if (configuration.candidate_network_policy ==
5217 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005218 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005219 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005220 }
5221
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005222 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005223 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005224 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5225 }
5226
Qingsi Wanga2d60672018-04-11 16:57:45 -07005227 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005228 // No step delay is used while allocating ports.
5229 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5230 port_allocator_->set_candidate_filter(
5231 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005232 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005233
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005234 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005235 for (auto& turn_server : turn_servers_copy) {
5236 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005237 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005238 // Call this last since it may create pooled allocator sessions using the
5239 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005240 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005241 stun_servers, std::move(turn_servers_copy),
5242 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5243 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005244 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005245 return true;
5246}
5247
deadbeef91dd5672016-05-18 16:55:30 -07005248bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005249 const cricket::ServerAddresses& stun_servers,
5250 const std::vector<cricket::RelayServerConfig>& turn_servers,
5251 IceTransportsType type,
5252 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005253 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005254 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005255 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005256 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005257 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005258 // According to JSEP, after setLocalDescription, changing the candidate pool
5259 // size is not allowed, and changing the set of ICE servers will not result
5260 // in new candidates being gathered.
5261 if (local_description()) {
5262 port_allocator_->FreezeCandidatePool();
5263 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005264 // Add the custom tls turn servers if they exist.
5265 auto turn_servers_copy = turn_servers;
5266 for (auto& turn_server : turn_servers_copy) {
5267 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5268 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005269 // Call this last since it may create pooled allocator sessions using the
5270 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005271 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005272 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5273 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005274}
5275
Steve Antonba818672017-11-06 10:21:57 -08005276cricket::ChannelManager* PeerConnection::channel_manager() const {
5277 return factory_->channel_manager();
5278}
5279
Elad Alon99c3fe52017-10-13 16:29:40 +02005280bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005281 std::unique_ptr<RtcEventLogOutput> output,
5282 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005283 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005284 if (!event_log_) {
5285 return false;
5286 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005287 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005288}
5289
5290void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005291 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005292 if (event_log_) {
5293 event_log_->StopLogging();
5294 }
ivoc14d5dbe2016-07-04 07:06:55 -07005295}
nisseeaabdf62017-05-05 02:23:02 -07005296
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005297cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005298 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005299 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005300 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005301 if (channel && channel->content_name() == content_name) {
5302 return channel;
5303 }
Steve Anton75737c02017-11-06 10:37:17 -08005304 }
5305 if (rtp_data_channel() &&
5306 rtp_data_channel()->content_name() == content_name) {
5307 return rtp_data_channel();
5308 }
5309 return nullptr;
5310}
5311
5312bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005313 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005314 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005315 RTC_LOG(LS_INFO)
5316 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005317 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005318 return false;
5319 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005320 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005321 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005322 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005323 return false;
5324 }
5325
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005326 absl::optional<rtc::SSLRole> dtls_role;
5327 if (sctp_mid_) {
5328 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5329 } else if (is_caller_) {
5330 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5331 }
Zhi Huange830e682018-03-30 10:48:35 -07005332 if (dtls_role) {
5333 *role = *dtls_role;
5334 return true;
5335 }
5336 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005337}
5338
5339bool PeerConnection::GetSslRole(const std::string& content_name,
5340 rtc::SSLRole* role) {
5341 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005342 RTC_LOG(LS_INFO)
5343 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005344 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005345 return false;
5346 }
5347
Zhi Huange830e682018-03-30 10:48:35 -07005348 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5349 if (dtls_role) {
5350 *role = *dtls_role;
5351 return true;
5352 }
5353 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005354}
5355
Steve Antonf8470812017-12-04 10:46:21 -08005356void PeerConnection::SetSessionError(SessionError error,
5357 const std::string& error_desc) {
5358 RTC_DCHECK_RUN_ON(signaling_thread());
5359 if (error != session_error_) {
5360 session_error_ = error;
5361 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005362 }
5363}
5364
Zhi Huange830e682018-03-30 10:48:35 -07005365RTCError PeerConnection::UpdateSessionState(
5366 SdpType type,
5367 cricket::ContentSource source,
5368 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005369 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005370
5371 // If there's already a pending error then no state transition should happen.
5372 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005373 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005374
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005375 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005376 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005377 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005378 }
5379
5380 // Update the signaling state according to the specified state machine (see
5381 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005382 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005383 ChangeSignalingState(source == cricket::CS_LOCAL
5384 ? PeerConnectionInterface::kHaveLocalOffer
5385 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005386 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005387 ChangeSignalingState(source == cricket::CS_LOCAL
5388 ? PeerConnectionInterface::kHaveLocalPrAnswer
5389 : PeerConnectionInterface::kHaveRemotePrAnswer);
5390 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005391 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005392 ChangeSignalingState(PeerConnectionInterface::kStable);
5393 }
5394
5395 // Update internal objects according to the session description's media
5396 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005397 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005398 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005399 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005400 }
5401
Steve Anton8a006912017-12-04 15:25:56 -08005402 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005403}
5404
Steve Anton8a006912017-12-04 15:25:56 -08005405RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005406 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005407 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005408 const SessionDescriptionInterface* sdesc =
5409 (source == cricket::CS_LOCAL ? local_description()
5410 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005411 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005412
5413 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005414 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005415 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005416 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005417 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005418 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005419 continue;
5420 }
5421 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005422 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005423 if (!content_desc) {
5424 continue;
5425 }
5426 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005427 bool success = (source == cricket::CS_LOCAL)
5428 ? channel->SetLocalContent(content_desc, type, &error)
5429 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005430 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005432 }
5433 }
5434
5435 // If using the RtpDataChannel, push down the new SDP section for it too.
5436 if (rtp_data_channel_) {
5437 const ContentInfo* data_content =
5438 cricket::GetFirstDataContent(sdesc->description());
5439 if (data_content && !data_content->rejected) {
5440 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005441 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005442 if (data_desc) {
5443 std::string error;
5444 bool success =
5445 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005446 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005447 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005448 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005449 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005450 }
Steve Anton75737c02017-11-06 10:37:17 -08005451 }
5452 }
5453 }
Steve Antoned10bd92017-12-05 10:52:59 -08005454
Steve Anton75737c02017-11-06 10:37:17 -08005455 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5456 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5457 if (sctp_transport_ && local_description() && remote_description() &&
5458 cricket::GetFirstDataContent(local_description()->description()) &&
5459 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005460 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005461 RTC_FROM_HERE,
5462 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005463 if (!success) {
5464 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5465 "Failed to push down SCTP parameters.");
5466 }
Steve Anton75737c02017-11-06 10:37:17 -08005467 }
Steve Antoned10bd92017-12-05 10:52:59 -08005468
Steve Anton8a006912017-12-04 15:25:56 -08005469 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005470}
5471
5472bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5473 RTC_DCHECK(network_thread()->IsCurrent());
5474 RTC_DCHECK(local_description());
5475 RTC_DCHECK(remote_description());
5476 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5477 // When we support "max-message-size", that would also be pushed down here.
5478 return sctp_transport_->Start(
5479 GetSctpPort(local_description()->description()),
5480 GetSctpPort(remote_description()->description()));
5481}
5482
Steve Anton8a006912017-12-04 15:25:56 -08005483RTCError PeerConnection::PushdownTransportDescription(
5484 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005485 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005486 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005487
Zhi Huange830e682018-03-30 10:48:35 -07005488 if (source == cricket::CS_LOCAL) {
5489 const SessionDescriptionInterface* sdesc = local_description();
5490 RTC_DCHECK(sdesc);
5491 return transport_controller_->SetLocalDescription(type,
5492 sdesc->description());
5493 } else {
5494 const SessionDescriptionInterface* sdesc = remote_description();
5495 RTC_DCHECK(sdesc);
5496 return transport_controller_->SetRemoteDescription(type,
5497 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005498 }
Steve Anton75737c02017-11-06 10:37:17 -08005499}
5500
5501bool PeerConnection::GetTransportDescription(
5502 const SessionDescription* description,
5503 const std::string& content_name,
5504 cricket::TransportDescription* tdesc) {
5505 if (!description || !tdesc) {
5506 return false;
5507 }
5508 const TransportInfo* transport_info =
5509 description->GetTransportInfoByName(content_name);
5510 if (!transport_info) {
5511 return false;
5512 }
5513 *tdesc = transport_info->description;
5514 return true;
5515}
5516
Steve Anton75737c02017-11-06 10:37:17 -08005517cricket::IceConfig PeerConnection::ParseIceConfig(
5518 const PeerConnectionInterface::RTCConfiguration& config) const {
5519 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005520 switch (config.continual_gathering_policy) {
5521 case PeerConnectionInterface::GATHER_ONCE:
5522 gathering_policy = cricket::GATHER_ONCE;
5523 break;
5524 case PeerConnectionInterface::GATHER_CONTINUALLY:
5525 gathering_policy = cricket::GATHER_CONTINUALLY;
5526 break;
5527 default:
5528 RTC_NOTREACHED();
5529 gathering_policy = cricket::GATHER_ONCE;
5530 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005531
Steve Anton75737c02017-11-06 10:37:17 -08005532 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005533 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5534 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005535 ice_config.prioritize_most_likely_candidate_pairs =
5536 config.prioritize_most_likely_ice_candidate_pairs;
5537 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005538 RTCConfigurationToIceConfigOptionalInt(
5539 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005540 ice_config.continual_gathering_policy = gathering_policy;
5541 ice_config.presume_writable_when_fully_relayed =
5542 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005543 ice_config.ice_check_interval_strong_connectivity =
5544 config.ice_check_interval_strong_connectivity;
5545 ice_config.ice_check_interval_weak_connectivity =
5546 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005547 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005548 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5549 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005550 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005551 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005552 ice_config.regather_all_networks_interval_range =
5553 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005554 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005555 return ice_config;
5556}
5557
Steve Antona41959e2018-11-28 11:15:33 -08005558static absl::string_view GetTrackIdBySsrc(
5559 const SessionDescriptionInterface* session_description,
5560 uint32_t ssrc) {
5561 if (!session_description) {
5562 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005563 }
Steve Antona41959e2018-11-28 11:15:33 -08005564 for (const cricket::ContentInfo& content :
5565 session_description->description()->contents()) {
5566 const cricket::MediaContentDescription& media =
5567 *content.media_description();
5568 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5569 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5570 const cricket::StreamParams* stream_params =
5571 cricket::GetStreamBySsrc(media.streams(), ssrc);
5572 if (stream_params) {
5573 return stream_params->id;
5574 }
5575 }
5576 }
5577 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005578}
5579
Steve Antona41959e2018-11-28 11:15:33 -08005580absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5581 return GetTrackIdBySsrc(local_description(), ssrc);
5582}
5583
5584absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5585 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005586}
5587
5588bool PeerConnection::SendData(const cricket::SendDataParams& params,
5589 const rtc::CopyOnWriteBuffer& payload,
5590 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005591 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5592 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5593 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005594 return false;
5595 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005596 if (media_transport_) {
5597 SendDataParams send_params;
5598 send_params.type = ToWebrtcDataMessageType(params.type);
5599 send_params.ordered = params.ordered;
5600 if (params.max_rtx_count >= 0) {
5601 send_params.max_rtx_count = params.max_rtx_count;
5602 } else if (params.max_rtx_ms >= 0) {
5603 send_params.max_rtx_ms = params.max_rtx_ms;
5604 }
5605 return media_transport_->SendData(params.sid, send_params, payload).ok();
5606 }
Steve Anton75737c02017-11-06 10:37:17 -08005607 return rtp_data_channel_
5608 ? rtp_data_channel_->SendData(params, payload, result)
5609 : network_thread()->Invoke<bool>(
5610 RTC_FROM_HERE,
5611 Bind(&cricket::SctpTransportInternal::SendData,
5612 sctp_transport_.get(), params, payload, result));
5613}
5614
5615bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005616 RTC_DCHECK_RUN_ON(signaling_thread());
5617 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005618 // Don't log an error here, because DataChannels are expected to call
5619 // ConnectDataChannel in this state. It's the only way to initially tell
5620 // whether or not the underlying transport is ready.
5621 return false;
5622 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005623 if (media_transport_) {
5624 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5625 &DataChannel::OnChannelReady);
5626 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5627 &DataChannel::OnDataReceived);
5628 SignalMediaTransportChannelClosing_s.connect(
5629 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5630 SignalMediaTransportChannelClosed_s.connect(
5631 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5632 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005633 rtp_data_channel_->SignalReadyToSendData.connect(
5634 webrtc_data_channel, &DataChannel::OnChannelReady);
5635 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5636 &DataChannel::OnDataReceived);
5637 } else {
5638 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5639 &DataChannel::OnChannelReady);
5640 SignalSctpDataReceived.connect(webrtc_data_channel,
5641 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005642 SignalSctpClosingProcedureStartedRemotely.connect(
5643 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5644 SignalSctpClosingProcedureComplete.connect(
5645 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005646 }
5647 return true;
5648}
5649
5650void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005651 RTC_DCHECK_RUN_ON(signaling_thread());
5652 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005653 RTC_LOG(LS_ERROR)
5654 << "DisconnectDataChannel called when rtp_data_channel_ and "
5655 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005656 return;
5657 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005658 if (media_transport_) {
5659 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5660 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5661 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5662 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5663 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005664 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5665 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5666 } else {
5667 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5668 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005669 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5670 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005671 }
5672}
5673
5674void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005675 if (media_transport_) {
5676 // No-op. Media transport does not need to add streams.
5677 return;
5678 }
Steve Anton75737c02017-11-06 10:37:17 -08005679 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005680 RTC_LOG(LS_ERROR)
5681 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005682 return;
5683 }
5684 network_thread()->Invoke<void>(
5685 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5686 sctp_transport_.get(), sid));
5687}
5688
5689void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005690 if (media_transport_) {
5691 media_transport_->CloseChannel(sid);
5692 return;
5693 }
Steve Anton75737c02017-11-06 10:37:17 -08005694 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005695 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005696 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005697 return;
5698 }
5699 network_thread()->Invoke<void>(
5700 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5701 sctp_transport_.get(), sid));
5702}
5703
5704bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005705 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005706 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005707 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005708 sctp_ready_to_send_data_;
5709}
5710
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005711void PeerConnection::OnDataReceived(int channel_id,
5712 DataMessageType type,
5713 const rtc::CopyOnWriteBuffer& buffer) {
5714 cricket::ReceiveDataParams params;
5715 params.sid = channel_id;
5716 params.type = ToCricketDataMessageType(type);
5717 media_transport_invoker_->AsyncInvoke<void>(
5718 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5719 RTC_DCHECK_RUN_ON(signaling_thread());
5720 if (!HandleOpenMessage_s(params, buffer)) {
5721 SignalMediaTransportReceivedData_s(params, buffer);
5722 }
5723 });
5724}
5725
5726void PeerConnection::OnChannelClosing(int channel_id) {
5727 media_transport_invoker_->AsyncInvoke<void>(
5728 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5729 RTC_DCHECK_RUN_ON(signaling_thread());
5730 SignalMediaTransportChannelClosing_s(channel_id);
5731 });
5732}
5733
5734void PeerConnection::OnChannelClosed(int channel_id) {
5735 media_transport_invoker_->AsyncInvoke<void>(
5736 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5737 RTC_DCHECK_RUN_ON(signaling_thread());
5738 SignalMediaTransportChannelClosed_s(channel_id);
5739 });
5740}
5741
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005742absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005743 if (sctp_mid_ && transport_controller_) {
5744 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5745 if (dtls_transport) {
5746 return dtls_transport->transport_name();
5747 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005748 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005749 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005750 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005751}
5752
Qingsi Wang72a43a12018-02-20 16:03:18 -08005753cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5754 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005755 network_thread()->Invoke<void>(
5756 RTC_FROM_HERE,
5757 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5758 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005759 return candidate_states_list;
5760}
5761
Steve Anton5dfde182018-02-06 10:34:40 -08005762std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5763 const {
5764 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005765 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005766 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005767 if (channel) {
5768 transport_names_by_mid[channel->content_name()] =
5769 channel->transport_name();
5770 }
Steve Anton75737c02017-11-06 10:37:17 -08005771 }
Steve Anton5dfde182018-02-06 10:34:40 -08005772 if (rtp_data_channel_) {
5773 transport_names_by_mid[rtp_data_channel_->content_name()] =
5774 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005777 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005778 RTC_DCHECK(transport_name);
5779 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005780 }
Steve Anton5dfde182018-02-06 10:34:40 -08005781 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005782}
5783
Steve Anton5dfde182018-02-06 10:34:40 -08005784std::map<std::string, cricket::TransportStats>
5785PeerConnection::GetTransportStatsByNames(
5786 const std::set<std::string>& transport_names) {
5787 if (!network_thread()->IsCurrent()) {
5788 return network_thread()
5789 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5790 RTC_FROM_HERE,
5791 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005792 }
Steve Anton5dfde182018-02-06 10:34:40 -08005793 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5794 for (const std::string& transport_name : transport_names) {
5795 cricket::TransportStats transport_stats;
5796 bool success =
5797 transport_controller_->GetStats(transport_name, &transport_stats);
5798 if (success) {
5799 transport_stats_by_name[transport_name] = std::move(transport_stats);
5800 } else {
5801 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5802 << transport_name;
5803 }
5804 }
5805 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005806}
5807
5808bool PeerConnection::GetLocalCertificate(
5809 const std::string& transport_name,
5810 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005811 if (!certificate) {
5812 return false;
5813 }
5814 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5815 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005816}
5817
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005818std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005819 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005820 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005821}
5822
5823cricket::DataChannelType PeerConnection::data_channel_type() const {
5824 return data_channel_type_;
5825}
5826
5827bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5828 return pending_ice_restarts_.find(content_name) !=
5829 pending_ice_restarts_.end();
5830}
5831
Steve Anton75737c02017-11-06 10:37:17 -08005832bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5833 return transport_controller_->NeedsIceRestart(content_name);
5834}
5835
5836void PeerConnection::OnCertificateReady(
5837 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5838 transport_controller_->SetLocalCertificate(certificate);
5839}
5840
5841void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005842 SetSessionError(SessionError::kTransport,
5843 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005844}
5845
Alex Loiko9289eda2018-11-23 16:18:59 +00005846void PeerConnection::OnTransportControllerConnectionState(
5847 cricket::IceConnectionState state) {
5848 switch (state) {
5849 case cricket::kIceConnectionConnecting:
5850 // If the current state is Connected or Completed, then there were
5851 // writable channels but now there are not, so the next state must
5852 // be Disconnected.
5853 // kIceConnectionConnecting is currently used as the default,
5854 // un-connected state by the TransportController, so its only use is
5855 // detecting disconnections.
5856 if (ice_connection_state_ ==
5857 PeerConnectionInterface::kIceConnectionConnected ||
5858 ice_connection_state_ ==
5859 PeerConnectionInterface::kIceConnectionCompleted) {
5860 SetIceConnectionState(
5861 PeerConnectionInterface::kIceConnectionDisconnected);
5862 }
5863 break;
5864 case cricket::kIceConnectionFailed:
5865 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5866 break;
5867 case cricket::kIceConnectionConnected:
5868 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5869 "all transports are writable.";
5870 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5871 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5872 break;
5873 case cricket::kIceConnectionCompleted:
5874 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5875 "all transports are complete.";
5876 if (ice_connection_state_ !=
5877 PeerConnectionInterface::kIceConnectionConnected) {
5878 // If jumping directly from "checking" to "connected",
5879 // signal "connected" first.
5880 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5881 }
5882 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5883 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5884 ReportTransportStats();
5885 break;
5886 default:
5887 RTC_NOTREACHED();
5888 }
5889}
5890
Steve Anton75737c02017-11-06 10:37:17 -08005891void PeerConnection::OnTransportControllerCandidatesGathered(
5892 const std::string& transport_name,
5893 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005894 int sdp_mline_index;
5895 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005896 RTC_LOG(LS_ERROR)
5897 << "OnTransportControllerCandidatesGathered: content name "
5898 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005899 return;
5900 }
5901
5902 for (cricket::Candidates::const_iterator citer = candidates.begin();
5903 citer != candidates.end(); ++citer) {
5904 // Use transport_name as the candidate media id.
5905 std::unique_ptr<JsepIceCandidate> candidate(
5906 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5907 if (local_description()) {
5908 mutable_local_description()->AddCandidate(candidate.get());
5909 }
5910 OnIceCandidate(std::move(candidate));
5911 }
5912}
5913
5914void PeerConnection::OnTransportControllerCandidatesRemoved(
5915 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08005916 // Sanity check.
5917 for (const cricket::Candidate& candidate : candidates) {
5918 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005919 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005920 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005921 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005922 return;
5923 }
5924 }
5925
5926 if (local_description()) {
5927 mutable_local_description()->RemoveCandidates(candidates);
5928 }
5929 OnIceCandidatesRemoved(candidates);
5930}
5931
5932void PeerConnection::OnTransportControllerDtlsHandshakeError(
5933 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005934 RTC_HISTOGRAM_ENUMERATION(
5935 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5936 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005937}
5938
Steve Antoned10bd92017-12-05 10:52:59 -08005939void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005940 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005941 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005942 if (channel && !channel->enabled()) {
5943 channel->Enable(true);
5944 }
Steve Anton75737c02017-11-06 10:37:17 -08005945 }
5946
Steve Anton4171afb2017-11-20 10:20:22 -08005947 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005948 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005949 }
Steve Anton75737c02017-11-06 10:37:17 -08005950}
5951
5952// Returns the media index for a local ice candidate given the content name.
5953bool PeerConnection::GetLocalCandidateMediaIndex(
5954 const std::string& content_name,
5955 int* sdp_mline_index) {
5956 if (!local_description() || !sdp_mline_index) {
5957 return false;
5958 }
5959
5960 bool content_found = false;
5961 const ContentInfos& contents = local_description()->description()->contents();
5962 for (size_t index = 0; index < contents.size(); ++index) {
5963 if (contents[index].name == content_name) {
5964 *sdp_mline_index = static_cast<int>(index);
5965 content_found = true;
5966 break;
5967 }
5968 }
5969 return content_found;
5970}
5971
5972bool PeerConnection::UseCandidatesInSessionDescription(
5973 const SessionDescriptionInterface* remote_desc) {
5974 if (!remote_desc) {
5975 return true;
5976 }
5977 bool ret = true;
5978
5979 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5980 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5981 for (size_t n = 0; n < candidates->count(); ++n) {
5982 const IceCandidateInterface* candidate = candidates->at(n);
5983 bool valid = false;
5984 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5985 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005986 RTC_LOG(LS_INFO)
5987 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005988 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005989 }
5990 continue;
5991 }
5992 ret = UseCandidate(candidate);
5993 if (!ret) {
5994 break;
5995 }
5996 }
5997 }
5998 return ret;
5999}
6000
6001bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6002 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6003 size_t remote_content_size =
6004 remote_description()->description()->contents().size();
6005 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006006 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006007 return false;
6008 }
6009
6010 cricket::ContentInfo content =
6011 remote_description()->description()->contents()[mediacontent_index];
6012 std::vector<cricket::Candidate> candidates;
6013 candidates.push_back(candidate->candidate());
6014 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006015 RTCError error =
6016 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006017 if (error.ok()) {
6018 // Candidates successfully submitted for checking.
6019 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6020 ice_connection_state_ ==
6021 PeerConnectionInterface::kIceConnectionDisconnected) {
6022 // If state is New, then the session has just gotten its first remote ICE
6023 // candidates, so go to Checking.
6024 // If state is Disconnected, the session is re-using old candidates or
6025 // receiving additional ones, so go to Checking.
6026 // If state is Connected, stay Connected.
6027 // TODO(bemasc): If state is Connected, and the new candidates are for a
6028 // newly added transport, then the state actually _should_ move to
6029 // checking. Add a way to distinguish that case.
6030 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6031 }
6032 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006033 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006034 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006035 }
6036 return true;
6037}
6038
6039void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006040 // Destroy video channel first since it may have a pointer to the
6041 // voice channel.
6042 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006043 if (!video_info || video_info->rejected) {
6044 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006045 }
6046
Steve Anton6fec8802017-12-04 10:37:29 -08006047 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6048 if (!audio_info || audio_info->rejected) {
6049 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006050 }
6051
6052 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6053 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006054 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006055 }
6056}
6057
Steve Antondcc3c022017-12-22 16:02:54 -08006058RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6059 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006060 const cricket::ContentGroup* bundle_group = nullptr;
6061 if (configuration_.bundle_policy ==
6062 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006063 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006064 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006065 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6066 "max-bundle configured but session description "
6067 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006068 }
6069 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006070 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006071}
6072
6073RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006074 // Creating the media channels. Transports should already have been created
6075 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006076 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006077 if (voice && !voice->rejected &&
6078 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006079 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006080 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006081 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6082 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006083 }
6084 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6085 }
6086
Steve Antondcc3c022017-12-22 16:02:54 -08006087 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006088 if (video && !video->rejected &&
6089 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006090 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006091 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006092 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6093 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006094 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006095 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006096 }
6097
Steve Antondcc3c022017-12-22 16:02:54 -08006098 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006099 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006100 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006101 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006102 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6103 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006104 }
6105 }
6106
Steve Anton8a006912017-12-04 15:25:56 -08006107 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006108}
6109
Steve Anton4171afb2017-11-20 10:20:22 -08006110// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006111cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006112 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006113 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006114 MediaTransportInterface* media_transport = nullptr;
6115 if (configuration_.use_media_transport) {
6116 media_transport = GetMediaTransport(mid);
6117 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006118
Steve Anton75737c02017-11-06 10:37:17 -08006119 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006120 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006121 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006122 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006123 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006124 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006125 }
Steve Anton75737c02017-11-06 10:37:17 -08006126 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6127 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006128 voice_channel->SignalSentPacket.connect(this,
6129 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006130 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006131
Steve Antoneda6ccd2017-12-04 10:21:55 -08006132 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006133}
6134
Steve Anton4171afb2017-11-20 10:20:22 -08006135// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006136cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006137 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006138 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006139 MediaTransportInterface* media_transport = nullptr;
6140 if (configuration_.use_media_transport) {
6141 media_transport = GetMediaTransport(mid);
6142 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006143
Steve Anton75737c02017-11-06 10:37:17 -08006144 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006145 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006146 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006147 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006148 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006149 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006150 }
Steve Anton75737c02017-11-06 10:37:17 -08006151 video_channel->SignalDtlsSrtpSetupFailure.connect(
6152 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006153 video_channel->SignalSentPacket.connect(this,
6154 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006155 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006156
Steve Antoneda6ccd2017-12-04 10:21:55 -08006157 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006158}
6159
Zhi Huange830e682018-03-30 10:48:35 -07006160bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006161 switch (data_channel_type_) {
6162 case cricket::DCT_MEDIA_TRANSPORT:
6163 if (network_thread()->Invoke<bool>(
6164 RTC_FROM_HERE,
6165 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6166 this, mid))) {
6167 for (const auto& channel : sctp_data_channels_) {
6168 channel->OnTransportChannelCreated();
6169 }
6170 return true;
6171 }
Steve Anton75737c02017-11-06 10:37:17 -08006172 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006173 case cricket::DCT_SCTP:
6174 if (!sctp_factory_) {
6175 RTC_LOG(LS_ERROR)
6176 << "Trying to create SCTP transport, but didn't compile with "
6177 "SCTP support (HAVE_SCTP)";
6178 return false;
6179 }
6180 if (!network_thread()->Invoke<bool>(
6181 RTC_FROM_HERE,
6182 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6183 return false;
6184 }
6185 for (const auto& channel : sctp_data_channels_) {
6186 channel->OnTransportChannelCreated();
6187 }
6188 return true;
6189 case cricket::DCT_RTP:
6190 default:
6191 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6192 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6193 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006194 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006195 if (!rtp_data_channel_) {
6196 return false;
6197 }
6198 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6199 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6200 rtp_data_channel_->SignalSentPacket.connect(
6201 this, &PeerConnection::OnSentPacket_w);
6202 rtp_data_channel_->SetRtpTransport(rtp_transport);
6203 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006204 }
6205
Steve Anton75737c02017-11-06 10:37:17 -08006206 return true;
6207}
6208
6209Call::Stats PeerConnection::GetCallStats() {
6210 if (!worker_thread()->IsCurrent()) {
6211 return worker_thread()->Invoke<Call::Stats>(
6212 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6213 }
6214 if (call_) {
6215 return call_->GetStats();
6216 } else {
6217 return Call::Stats();
6218 }
6219}
6220
Zhi Huange830e682018-03-30 10:48:35 -07006221bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006222 RTC_DCHECK(network_thread()->IsCurrent());
6223 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006224 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006225 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006226 RTC_DCHECK(dtls_transport);
6227 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006228 RTC_DCHECK(sctp_transport_);
6229 sctp_invoker_.reset(new rtc::AsyncInvoker());
6230 sctp_transport_->SignalReadyToSendData.connect(
6231 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6232 sctp_transport_->SignalDataReceived.connect(
6233 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006234 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6235 // another thread. Would be nice if there was a helper class similar to
6236 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6237 // code.
6238 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6239 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6240 sctp_transport_->SignalClosingProcedureComplete.connect(
6241 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006242 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006243 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006244 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006245}
6246
6247void PeerConnection::DestroySctpTransport_n() {
6248 RTC_DCHECK(network_thread()->IsCurrent());
6249 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006250 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006251 sctp_invoker_.reset(nullptr);
6252 sctp_ready_to_send_data_ = false;
6253}
6254
6255void PeerConnection::OnSctpTransportReadyToSendData_n() {
6256 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6257 RTC_DCHECK(network_thread()->IsCurrent());
6258 // Note: Cannot use rtc::Bind here because it will grab a reference to
6259 // PeerConnection and potentially cause PeerConnection to live longer than
6260 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6261 // be destroyed before PeerConnection is destroyed, and at that point all
6262 // pending tasks will be cleared.
6263 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6264 OnSctpTransportReadyToSendData_s(true);
6265 });
6266}
6267
6268void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6269 RTC_DCHECK(signaling_thread()->IsCurrent());
6270 sctp_ready_to_send_data_ = ready;
6271 SignalSctpReadyToSendData(ready);
6272}
6273
6274void PeerConnection::OnSctpTransportDataReceived_n(
6275 const cricket::ReceiveDataParams& params,
6276 const rtc::CopyOnWriteBuffer& payload) {
6277 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6278 RTC_DCHECK(network_thread()->IsCurrent());
6279 // Note: Cannot use rtc::Bind here because it will grab a reference to
6280 // PeerConnection and potentially cause PeerConnection to live longer than
6281 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6282 // be destroyed before PeerConnection is destroyed, and at that point all
6283 // pending tasks will be cleared.
6284 sctp_invoker_->AsyncInvoke<void>(
6285 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6286 OnSctpTransportDataReceived_s(params, payload);
6287 });
6288}
6289
6290void PeerConnection::OnSctpTransportDataReceived_s(
6291 const cricket::ReceiveDataParams& params,
6292 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006293 RTC_DCHECK_RUN_ON(signaling_thread());
6294 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006295 SignalSctpDataReceived(params, payload);
6296 }
6297}
6298
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006299void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006300 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6301 RTC_DCHECK(network_thread()->IsCurrent());
6302 sctp_invoker_->AsyncInvoke<void>(
6303 RTC_FROM_HERE, signaling_thread(),
6304 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006305 &SignalSctpClosingProcedureStartedRemotely, sid));
6306}
6307
6308void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6309 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6310 RTC_DCHECK(network_thread()->IsCurrent());
6311 sctp_invoker_->AsyncInvoke<void>(
6312 RTC_FROM_HERE, signaling_thread(),
6313 rtc::Bind(&sigslot::signal1<int>::operator(),
6314 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006315}
6316
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006317bool PeerConnection::SetupMediaTransportForDataChannels_n(
6318 const std::string& mid) {
6319 media_transport_ = transport_controller_->GetMediaTransport(mid);
6320 if (!media_transport_) {
6321 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6322 return false;
6323 }
6324
6325 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6326 media_transport_->SetDataSink(this);
6327 media_transport_data_mid_ = mid;
6328 transport_controller_->SignalMediaTransportStateChanged.connect(
6329 this, &PeerConnection::OnMediaTransportStateChanged_n);
6330 // Check the initial state right away, in case transport is already writable.
6331 OnMediaTransportStateChanged_n();
6332 return true;
6333}
6334
6335void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6336 if (!media_transport_) {
6337 return;
6338 }
6339 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6340 media_transport_data_mid_.reset();
6341 media_transport_->SetDataSink(nullptr);
6342 media_transport_invoker_ = nullptr;
6343 media_transport_ = nullptr;
6344}
6345
6346void PeerConnection::OnMediaTransportStateChanged_n() {
6347 if (!media_transport_data_mid_ ||
6348 transport_controller_->GetMediaTransportState(
6349 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6350 return;
6351 }
6352 media_transport_invoker_->AsyncInvoke<void>(
6353 RTC_FROM_HERE, signaling_thread(), [this] {
6354 RTC_DCHECK_RUN_ON(signaling_thread());
6355 media_transport_ready_to_send_data_ = true;
6356 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6357 });
6358}
6359
Steve Anton75737c02017-11-06 10:37:17 -08006360// Returns false if bundle is enabled and rtcp_mux is disabled.
6361bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6362 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6363 if (!bundle_enabled)
6364 return true;
6365
6366 const cricket::ContentGroup* bundle_group =
6367 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6368 RTC_DCHECK(bundle_group != NULL);
6369
6370 const cricket::ContentInfos& contents = desc->contents();
6371 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6372 citer != contents.end(); ++citer) {
6373 const cricket::ContentInfo* content = (&*citer);
6374 RTC_DCHECK(content != NULL);
6375 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006376 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006377 if (!HasRtcpMuxEnabled(content))
6378 return false;
6379 }
6380 }
6381 // RTCP-MUX is enabled in all the contents.
6382 return true;
6383}
6384
6385bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006386 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006387}
6388
Steve Anton06817cd2018-12-18 15:55:30 -08006389static RTCError ValidateMids(const cricket::SessionDescription& description) {
6390 std::set<std::string> mids;
6391 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006392 if (content.name.empty()) {
6393 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6394 "A media section is missing a MID attribute.");
6395 }
Steve Anton06817cd2018-12-18 15:55:30 -08006396 if (!mids.insert(content.name).second) {
6397 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6398 "Duplicate a=mid value '" + content.name + "'.");
6399 }
6400 }
6401 return RTCError::OK();
6402}
6403
Steve Anton8a006912017-12-04 15:25:56 -08006404RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006405 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006406 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006407 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006408 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006409 }
6410
6411 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006413 }
6414
Steve Anton3828c062017-12-06 10:34:51 -08006415 SdpType type = sdesc->GetType();
6416 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6417 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006418 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006419 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006420 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006421 }
6422
Steve Anton06817cd2018-12-18 15:55:30 -08006423 RTCError error = ValidateMids(*sdesc->description());
6424 if (!error.ok()) {
6425 return error;
6426 }
6427
Steve Anton75737c02017-11-06 10:37:17 -08006428 // Verify crypto settings.
6429 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006430 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6431 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006432 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006433 if (!crypto_error.ok()) {
6434 return crypto_error;
6435 }
Steve Anton75737c02017-11-06 10:37:17 -08006436 }
6437
6438 // Verify ice-ufrag and ice-pwd.
6439 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006440 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6441 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006442 }
6443
6444 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006445 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6446 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006447 }
6448
6449 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6450 // m-lines that do not rtcp-mux enabled.
6451
6452 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006453 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006454 // With an answer we want to compare the new answer session description with
6455 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006456 const cricket::SessionDescription* offer_desc =
6457 (source == cricket::CS_LOCAL) ? remote_description()->description()
6458 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006459 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6460 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6461 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006462 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6463 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006464 }
6465 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006466 // The re-offers should respect the order of m= sections in current
6467 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006468 // With a re-offer, either the current local or current remote descriptions
6469 // could be the most up to date, so we would like to check against both of
6470 // them if they exist. It could be the case that one of them has a 0 port
6471 // for a media section, but the other does not. This is important to check
6472 // against in the case that we are recycling an m= section.
6473 const cricket::SessionDescription* current_desc = nullptr;
6474 const cricket::SessionDescription* secondary_current_desc = nullptr;
6475 if (local_description()) {
6476 current_desc = local_description()->description();
6477 if (remote_description()) {
6478 secondary_current_desc = remote_description()->description();
6479 }
6480 } else if (remote_description()) {
6481 current_desc = remote_description()->description();
6482 }
Steve Anton75737c02017-11-06 10:37:17 -08006483 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006484 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6485 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006486 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6487 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
6489 }
6490
Steve Antonba42e992018-04-09 14:10:01 -07006491 if (IsUnifiedPlan()) {
6492 // Ensure that each audio and video media section has at most one
6493 // "StreamParams". This will return an error if receiving a session
6494 // description from a "Plan B" endpoint which adds multiple tracks of the
6495 // same type. With Unified Plan, there can only be at most one track per
6496 // media section.
6497 for (const ContentInfo& content : sdesc->description()->contents()) {
6498 const MediaContentDescription& desc = *content.description;
6499 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6500 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6501 desc.streams().size() > 1u) {
6502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6503 "Media section has more than one track specified "
6504 "with a=ssrc lines which is not supported with "
6505 "Unified Plan.");
6506 }
6507 }
6508 }
6509
Steve Anton8a006912017-12-04 15:25:56 -08006510 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006511}
6512
Steve Anton3828c062017-12-06 10:34:51 -08006513bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006514 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006515 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006516 return (state == PeerConnectionInterface::kStable) ||
6517 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006518 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006519 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006520 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6521 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6522 }
6523}
6524
Steve Anton3828c062017-12-06 10:34:51 -08006525bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006526 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006527 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006528 return (state == PeerConnectionInterface::kStable) ||
6529 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006530 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006531 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006532 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6533 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6534 }
6535}
6536
Steve Antonf8470812017-12-04 10:46:21 -08006537const char* PeerConnection::SessionErrorToString(SessionError error) const {
6538 switch (error) {
6539 case SessionError::kNone:
6540 return "ERROR_NONE";
6541 case SessionError::kContent:
6542 return "ERROR_CONTENT";
6543 case SessionError::kTransport:
6544 return "ERROR_TRANSPORT";
6545 }
6546 RTC_NOTREACHED();
6547 return "";
6548}
6549
Steve Anton75737c02017-11-06 10:37:17 -08006550std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006551 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006552 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6553 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006554 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006555}
6556
Steve Anton8e20f172018-03-06 10:55:04 -08006557void PeerConnection::ReportSdpFormatReceived(
6558 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006559 int num_audio_mlines = 0;
6560 int num_video_mlines = 0;
6561 int num_audio_tracks = 0;
6562 int num_video_tracks = 0;
6563 for (const ContentInfo& content : remote_offer.description()->contents()) {
6564 cricket::MediaType media_type = content.media_description()->type();
6565 int num_tracks = std::max(
6566 1, static_cast<int>(content.media_description()->streams().size()));
6567 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6568 num_audio_mlines += 1;
6569 num_audio_tracks += num_tracks;
6570 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6571 num_video_mlines += 1;
6572 num_video_tracks += num_tracks;
6573 }
6574 }
6575 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6576 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6577 format = kSdpFormatReceivedComplexUnifiedPlan;
6578 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6579 format = kSdpFormatReceivedComplexPlanB;
6580 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6581 format = kSdpFormatReceivedSimple;
6582 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006583 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6584 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006585}
6586
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006587void PeerConnection::NoteUsageEvent(UsageEvent event) {
6588 RTC_DCHECK_RUN_ON(signaling_thread());
6589 usage_event_accumulator_ |= static_cast<int>(event);
6590}
6591
6592void PeerConnection::ReportUsagePattern() const {
6593 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006594 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6595 usage_event_accumulator_,
6596 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006597 const int bad_bits =
6598 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6599 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6600 const int good_bits =
6601 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6602 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6603 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6604 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6605 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006606 // If called after close(), we can't report, because observer may have
6607 // been deallocated, and therefore pointer is null. Write to log instead.
6608 if (observer_) {
6609 Observer()->OnInterestingUsage(usage_event_accumulator_);
6610 } else {
6611 RTC_LOG(LS_INFO) << "Interesting usage signature "
6612 << usage_event_accumulator_
6613 << " observed after observer shutdown";
6614 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006615 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006616}
6617
Steve Anton0ffaaa22018-02-23 10:31:30 -08006618void PeerConnection::ReportNegotiatedSdpSemantics(
6619 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006620 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006621 switch (answer.description()->msid_signaling()) {
6622 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006623 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006624 break;
6625 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006626 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006627 break;
6628 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006629 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006630 break;
6631 case cricket::kMsidSignalingMediaSection |
6632 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006633 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006634 break;
6635 default:
6636 RTC_NOTREACHED();
6637 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006638 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6639 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006640}
6641
Steve Anton75737c02017-11-06 10:37:17 -08006642// We need to check the local/remote description for the Transport instead of
6643// the session, because a new Transport added during renegotiation may have
6644// them unset while the session has them set from the previous negotiation.
6645// Not doing so may trigger the auto generation of transport description and
6646// mess up DTLS identity information, ICE credential, etc.
6647bool PeerConnection::ReadyToUseRemoteCandidate(
6648 const IceCandidateInterface* candidate,
6649 const SessionDescriptionInterface* remote_desc,
6650 bool* valid) {
6651 *valid = true;
6652
6653 const SessionDescriptionInterface* current_remote_desc =
6654 remote_desc ? remote_desc : remote_description();
6655
6656 if (!current_remote_desc) {
6657 return false;
6658 }
6659
6660 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6661 size_t remote_content_size =
6662 current_remote_desc->description()->contents().size();
6663 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006664 RTC_LOG(LS_ERROR)
6665 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6666 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006667
6668 *valid = false;
6669 return false;
6670 }
6671
6672 cricket::ContentInfo content =
6673 current_remote_desc->description()->contents()[mediacontent_index];
6674
6675 const std::string transport_name = GetTransportName(content.name);
6676 if (transport_name.empty()) {
6677 return false;
6678 }
Zhi Huange830e682018-03-30 10:48:35 -07006679 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006680}
6681
6682bool PeerConnection::SrtpRequired() const {
6683 return dtls_enabled_ ||
6684 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6685}
6686
6687void PeerConnection::OnTransportControllerGatheringState(
6688 cricket::IceGatheringState state) {
6689 RTC_DCHECK(signaling_thread()->IsCurrent());
6690 if (state == cricket::kIceGatheringGathering) {
6691 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6692 } else if (state == cricket::kIceGatheringComplete) {
6693 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6694 }
6695}
6696
6697void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006698 std::map<std::string, std::set<cricket::MediaType>>
6699 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006700 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006701 if (transceiver->internal()->channel()) {
6702 const std::string& transport_name =
6703 transceiver->internal()->channel()->transport_name();
6704 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006705 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006706 }
Steve Anton75737c02017-11-06 10:37:17 -08006707 }
6708 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006709 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6710 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006711 }
Zhi Huange830e682018-03-30 10:48:35 -07006712
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006713 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006714 if (transport_name) {
6715 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006716 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006717 }
Zhi Huange830e682018-03-30 10:48:35 -07006718
Steve Antonc7b964c2018-02-01 14:39:45 -08006719 for (const auto& entry : media_types_by_transport_name) {
6720 const std::string& transport_name = entry.first;
6721 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006722 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006723 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006724 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006725 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006726 }
6727 }
6728}
6729// Walk through the ConnectionInfos to gather best connection usage
6730// for IPv4 and IPv6.
6731void PeerConnection::ReportBestConnectionState(
6732 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006733 for (const cricket::TransportChannelStats& channel_stats :
6734 stats.channel_stats) {
6735 for (const cricket::ConnectionInfo& connection_info :
6736 channel_stats.connection_infos) {
6737 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006738 continue;
6739 }
6740
Steve Antonc7b964c2018-02-01 14:39:45 -08006741 const cricket::Candidate& local = connection_info.local_candidate;
6742 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006743
6744 // Increment the counter for IceCandidatePairType.
6745 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6746 (local.type() == RELAY_PORT_TYPE &&
6747 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006748 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6749 GetIceCandidatePairCounter(local, remote),
6750 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006751 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006752 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6753 GetIceCandidatePairCounter(local, remote),
6754 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006755 } else {
6756 RTC_CHECK(0);
6757 }
Steve Anton75737c02017-11-06 10:37:17 -08006758
6759 // Increment the counter for IP type.
6760 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006761 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6762 kBestConnections_IPv4,
6763 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006764 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006765 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6766 kBestConnections_IPv6,
6767 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006768 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006769 RTC_CHECK(!local.address().hostname().empty() &&
6770 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006771 }
6772
6773 return;
6774 }
6775 }
6776}
6777
6778void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006779 const cricket::TransportStats& stats,
6780 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006781 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6782 return;
6783 }
6784
6785 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6786 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6787 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6788 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6789 return;
6790 }
6791
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006792 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6793 for (cricket::MediaType media_type : media_types) {
6794 switch (media_type) {
6795 case cricket::MEDIA_TYPE_AUDIO:
6796 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6797 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6798 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6799 break;
6800 case cricket::MEDIA_TYPE_VIDEO:
6801 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6802 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6803 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6804 break;
6805 case cricket::MEDIA_TYPE_DATA:
6806 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6807 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6808 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6809 break;
6810 default:
6811 RTC_NOTREACHED();
6812 continue;
6813 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006814 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006815 }
6816
6817 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6818 for (cricket::MediaType media_type : media_types) {
6819 switch (media_type) {
6820 case cricket::MEDIA_TYPE_AUDIO:
6821 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6822 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6823 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6824 break;
6825 case cricket::MEDIA_TYPE_VIDEO:
6826 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6827 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6828 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6829 break;
6830 case cricket::MEDIA_TYPE_DATA:
6831 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6832 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6833 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6834 break;
6835 default:
6836 RTC_NOTREACHED();
6837 continue;
6838 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006839 }
Steve Anton75737c02017-11-06 10:37:17 -08006840 }
6841}
6842
6843void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6844 RTC_DCHECK(worker_thread()->IsCurrent());
6845 RTC_DCHECK(call_);
6846 call_->OnSentPacket(sent_packet);
6847}
6848
6849const std::string PeerConnection::GetTransportName(
6850 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006851 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006852 if (channel) {
6853 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006854 }
Steve Anton6fec8802017-12-04 10:37:29 -08006855 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006856 RTC_DCHECK(sctp_mid_);
6857 if (content_name == *sctp_mid_) {
6858 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006859 }
6860 }
6861 // Return an empty string if failed to retrieve the transport name.
6862 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006863}
6864
Steve Anton6fec8802017-12-04 10:37:29 -08006865void PeerConnection::DestroyTransceiverChannel(
6866 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6867 transceiver) {
6868 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006869
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006870 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006871 if (channel) {
6872 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006873 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006874 }
6875}
6876
6877void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006878 if (rtp_data_channel_) {
6879 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006880 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006881 rtp_data_channel_ = nullptr;
6882 }
6883
6884 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6885 // grab a reference to this PeerConnection. If this is called from the
6886 // PeerConnection destructor, the RefCountedObject vtable will have already
6887 // been destroyed (since it is a subclass of PeerConnection) and using
6888 // rtc::Bind will cause "Pure virtual function called" error to appear.
6889
6890 if (sctp_transport_) {
6891 OnDataChannelDestroyed();
6892 network_thread()->Invoke<void>(RTC_FROM_HERE,
6893 [this] { DestroySctpTransport_n(); });
6894 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006895
6896 if (media_transport_) {
6897 OnDataChannelDestroyed();
6898 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6899 RTC_DCHECK_RUN_ON(network_thread());
6900 TeardownMediaTransportForDataChannels_n();
6901 });
6902 }
Steve Anton6fec8802017-12-04 10:37:29 -08006903}
6904
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006905void PeerConnection::DestroyChannelInterface(
6906 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006907 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006908 switch (channel->media_type()) {
6909 case cricket::MEDIA_TYPE_AUDIO:
6910 channel_manager()->DestroyVoiceChannel(
6911 static_cast<cricket::VoiceChannel*>(channel));
6912 break;
6913 case cricket::MEDIA_TYPE_VIDEO:
6914 channel_manager()->DestroyVideoChannel(
6915 static_cast<cricket::VideoChannel*>(channel));
6916 break;
6917 case cricket::MEDIA_TYPE_DATA:
6918 channel_manager()->DestroyRtpDataChannel(
6919 static_cast<cricket::RtpDataChannel*>(channel));
6920 break;
6921 default:
6922 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6923 break;
6924 }
Zhi Huange830e682018-03-30 10:48:35 -07006925}
Steve Anton6fec8802017-12-04 10:37:29 -08006926
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006927bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006928 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006929 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006930 cricket::DtlsTransportInternal* dtls_transport,
6931 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006932 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006933 auto base_channel = GetChannel(mid);
6934 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006935 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006936 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006937 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006938 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006939 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006940
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006941 if (configuration_.use_media_transport) {
6942 // Only pass media transport to call object if media transport is used
6943 // for media (and not data channel).
6944 call_->MediaTransportChange(media_transport);
6945 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006946
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006947 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006948}
6949
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006950PeerConnectionObserver* PeerConnection::Observer() const {
6951 // In earlier production code, the pointer was not cleared on close,
6952 // which might have led to undefined behavior if the observer was not
6953 // deallocated, or strange crashes if it was.
6954 // We use CHECK in order to catch such behavior if it exists.
6955 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6956 RTC_CHECK(observer_);
6957 return observer_;
6958}
6959
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006960CryptoOptions PeerConnection::GetCryptoOptions() {
6961 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6962 // after it has been removed.
6963 return configuration_.crypto_options.has_value()
6964 ? *configuration_.crypto_options
6965 : factory_->options().crypto_options;
6966}
6967
Harald Alvestrand89061872018-01-02 14:08:34 +01006968void PeerConnection::ClearStatsCache() {
6969 if (stats_collector_) {
6970 stats_collector_->ClearCachedStatsReport();
6971 }
6972}
6973
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006974void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006975 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6976 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006977}
6978
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006979} // namespace webrtc