blob: bf3ad56f534dd3c689bf5b3d4ebaa5485bd61347 [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"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
28#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020030#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020033#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010057#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080058#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020059#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
79using cricket::STUN_PORT_TYPE;
80using cricket::RELAY_PORT_TYPE;
81using cricket::PRFLX_PORT_TYPE;
82
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800111// UMA metric names.
112const char kSimulcastVersionApplyLocalDescription[] =
113 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
114const char kSimulcastVersionApplyRemoteDescription[] =
115 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
116const char kSimulcastNumberOfEncodings[] =
117 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
118const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
119
Seth Hampson845e8782018-03-02 11:34:10 -0800120static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800121static const char kDefaultAudioSenderId[] = "defaulta0";
122static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700123
zhihuang8f65cdf2016-05-06 18:40:30 -0700124// The length of RTCP CNAMEs.
125static const int kRtcpCnameLength = 16;
126
Steve Antonad182762018-09-05 20:22:40 +0000127enum {
128 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
129 MSG_SET_SESSIONDESCRIPTION_FAILED,
130 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
131 MSG_GETSTATS,
132 MSG_FREE_DATACHANNELS,
133 MSG_REPORT_USAGE_PATTERN,
134};
135
Harald Alvestrand19793842018-06-25 12:03:50 +0200136static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
137
Steve Antonad182762018-09-05 20:22:40 +0000138struct SetSessionDescriptionMsg : public rtc::MessageData {
139 explicit SetSessionDescriptionMsg(
140 webrtc::SetSessionDescriptionObserver* observer)
141 : observer(observer) {}
142
143 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
144 RTCError error;
145};
146
147struct CreateSessionDescriptionMsg : public rtc::MessageData {
148 explicit CreateSessionDescriptionMsg(
149 webrtc::CreateSessionDescriptionObserver* observer)
150 : observer(observer) {}
151
152 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
153 RTCError error;
154};
155
156struct GetStatsMsg : public rtc::MessageData {
157 GetStatsMsg(webrtc::StatsObserver* observer,
158 webrtc::MediaStreamTrackInterface* track)
159 : observer(observer), track(track) {}
160 rtc::scoped_refptr<webrtc::StatsObserver> observer;
161 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
162};
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164// Check if we can send |new_stream| on a PeerConnection.
165bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
166 webrtc::MediaStreamInterface* new_stream) {
167 if (!new_stream || !current_streams) {
168 return false;
169 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700170 if (current_streams->find(new_stream->id()) != nullptr) {
171 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100172 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700173 return false;
174 }
175 return true;
176}
177
deadbeef5e97fb52015-10-15 12:49:08 -0700178// If the direction is "recvonly" or "inactive", treat the description
179// as containing no streams.
180// See: https://code.google.com/p/webrtc/issues/detail?id=5054
181std::vector<cricket::StreamParams> GetActiveStreams(
182 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800183 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700184 ? desc->streams()
185 : std::vector<cricket::StreamParams>();
186}
187
deadbeefab9b2d12015-10-14 11:33:11 -0700188bool IsValidOfferToReceiveMedia(int value) {
189 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
190 return (value >= Options::kUndefined) &&
191 (value <= Options::kMaxOfferToReceiveMedia);
192}
193
zhihuang1c378ed2017-08-17 14:10:50 -0700194// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800195void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700196 const std::vector<rtc::scoped_refptr<
197 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700198 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200199 cricket::MediaDescriptionOptions* video_media_description_options,
200 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700201 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
203 if (audio_media_description_options) {
204 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700205 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700206 }
207 } else {
208 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
209 if (video_media_description_options) {
210 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800211 sender->id(), sender->internal()->stream_ids(), {},
212 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700215 }
zhihuang1c378ed2017-08-17 14:10:50 -0700216}
olka3c747662017-08-17 06:50:32 -0700217
zhihuang1c378ed2017-08-17 14:10:50 -0700218// Add options to |session_options| from |rtp_data_channels|.
219void AddRtpDataChannelOptions(
220 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
221 rtp_data_channels,
222 cricket::MediaDescriptionOptions* data_media_description_options) {
223 if (!data_media_description_options) {
224 return;
225 }
deadbeefab9b2d12015-10-14 11:33:11 -0700226 // Check for data channels.
227 for (const auto& kv : rtp_data_channels) {
228 const DataChannel* channel = kv.second;
229 if (channel->state() == DataChannel::kConnecting ||
230 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700231 // Legacy RTP data channels are signaled with the track/stream ID set to
232 // the data channel's label.
233 data_media_description_options->AddRtpDataChannel(channel->label(),
234 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700235 }
236 }
237}
238
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700239uint32_t ConvertIceTransportTypeToCandidateFilter(
240 PeerConnectionInterface::IceTransportsType type) {
241 switch (type) {
242 case PeerConnectionInterface::kNone:
243 return cricket::CF_NONE;
244 case PeerConnectionInterface::kRelay:
245 return cricket::CF_RELAY;
246 case PeerConnectionInterface::kNoHost:
247 return (cricket::CF_ALL & ~cricket::CF_HOST);
248 case PeerConnectionInterface::kAll:
249 return cricket::CF_ALL;
250 default:
nissec80e7412017-01-11 05:56:46 -0800251 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700252 }
253 return cricket::CF_NONE;
254}
255
deadbeef293e9262017-01-11 12:28:30 -0800256// Helper to set an error and return from a method.
257bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
258 if (error) {
259 error->set_type(type);
260 }
261 return type == webrtc::RTCErrorType::NONE;
262}
263
Steve Anton038834f2017-07-14 15:59:59 -0700264bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700265 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700266 if (error_out) {
267 *error_out = std::move(error);
268 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700269 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700270}
271
Steve Antonba818672017-11-06 10:21:57 -0800272std::string GetSignalingStateString(
273 PeerConnectionInterface::SignalingState state) {
274 switch (state) {
275 case PeerConnectionInterface::kStable:
276 return "kStable";
277 case PeerConnectionInterface::kHaveLocalOffer:
278 return "kHaveLocalOffer";
279 case PeerConnectionInterface::kHaveLocalPrAnswer:
280 return "kHavePrAnswer";
281 case PeerConnectionInterface::kHaveRemoteOffer:
282 return "kHaveRemoteOffer";
283 case PeerConnectionInterface::kHaveRemotePrAnswer:
284 return "kHaveRemotePrAnswer";
285 case PeerConnectionInterface::kClosed:
286 return "kClosed";
287 }
288 RTC_NOTREACHED();
289 return "";
290}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700291
Steve Anton75737c02017-11-06 10:37:17 -0800292IceCandidatePairType GetIceCandidatePairCounter(
293 const cricket::Candidate& local,
294 const cricket::Candidate& remote) {
295 const auto& l = local.type();
296 const auto& r = remote.type();
297 const auto& host = LOCAL_PORT_TYPE;
298 const auto& srflx = STUN_PORT_TYPE;
299 const auto& relay = RELAY_PORT_TYPE;
300 const auto& prflx = PRFLX_PORT_TYPE;
301 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800302 bool local_hostname =
303 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
304 bool remote_hostname = !remote.address().hostname().empty() &&
305 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800306 bool local_private = IPIsPrivate(local.address().ipaddr());
307 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800308 if (local_hostname) {
309 if (remote_hostname) {
310 return kIceCandidatePairHostNameHostName;
311 } else if (remote_private) {
312 return kIceCandidatePairHostNameHostPrivate;
313 } else {
314 return kIceCandidatePairHostNameHostPublic;
315 }
316 } else if (local_private) {
317 if (remote_hostname) {
318 return kIceCandidatePairHostPrivateHostName;
319 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800320 return kIceCandidatePairHostPrivateHostPrivate;
321 } else {
322 return kIceCandidatePairHostPrivateHostPublic;
323 }
324 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800325 if (remote_hostname) {
326 return kIceCandidatePairHostPublicHostName;
327 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800328 return kIceCandidatePairHostPublicHostPrivate;
329 } else {
330 return kIceCandidatePairHostPublicHostPublic;
331 }
332 }
333 }
334 if (l == host && r == srflx)
335 return kIceCandidatePairHostSrflx;
336 if (l == host && r == relay)
337 return kIceCandidatePairHostRelay;
338 if (l == host && r == prflx)
339 return kIceCandidatePairHostPrflx;
340 if (l == srflx && r == host)
341 return kIceCandidatePairSrflxHost;
342 if (l == srflx && r == srflx)
343 return kIceCandidatePairSrflxSrflx;
344 if (l == srflx && r == relay)
345 return kIceCandidatePairSrflxRelay;
346 if (l == srflx && r == prflx)
347 return kIceCandidatePairSrflxPrflx;
348 if (l == relay && r == host)
349 return kIceCandidatePairRelayHost;
350 if (l == relay && r == srflx)
351 return kIceCandidatePairRelaySrflx;
352 if (l == relay && r == relay)
353 return kIceCandidatePairRelayRelay;
354 if (l == relay && r == prflx)
355 return kIceCandidatePairRelayPrflx;
356 if (l == prflx && r == host)
357 return kIceCandidatePairPrflxHost;
358 if (l == prflx && r == srflx)
359 return kIceCandidatePairPrflxSrflx;
360 if (l == prflx && r == relay)
361 return kIceCandidatePairPrflxRelay;
362 return kIceCandidatePairMax;
363}
364
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800365// Logic to decide if an m= section can be recycled. This means that the new
366// m= section is not rejected, but the old local or remote m= section is
367// rejected. |old_content_one| and |old_content_two| refer to the m= section
368// of the old remote and old local descriptions in no particular order.
369// We need to check both the old local and remote because either
370// could be the most current from the latest negotation.
371bool IsMediaSectionBeingRecycled(SdpType type,
372 const ContentInfo& content,
373 const ContentInfo* old_content_one,
374 const ContentInfo* old_content_two) {
375 return type == SdpType::kOffer && !content.rejected &&
376 ((old_content_one && old_content_one->rejected) ||
377 (old_content_two && old_content_two->rejected));
378}
379
Steve Anton75737c02017-11-06 10:37:17 -0800380// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800381// |current_desc|. The number of m= sections in |new_desc| should be no
382// less than |current_desc|. In the case of checking an answer's
383// |new_desc|, the |current_desc| is the last offer that was set as the
384// local or remote. In the case of checking an offer's |new_desc| we
385// check against the local and remote descriptions stored from the last
386// negotiation, because either of these could be the most up to date for
387// possible rejected m sections. These are the |current_desc| and
388// |secondary_current_desc|.
389bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
390 const SessionDescription* secondary_current_desc,
391 const SessionDescription& new_desc,
392 const SdpType type) {
393 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 return false;
395 }
396
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800397 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
398 const cricket::ContentInfo* secondary_content_info = nullptr;
399 if (secondary_current_desc &&
400 i < secondary_current_desc->contents().size()) {
401 secondary_content_info = &secondary_current_desc->contents()[i];
402 }
403 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
404 &current_desc.contents()[i],
405 secondary_content_info)) {
406 // For new offer descriptions, if the media section can be recycled, it's
407 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800408 continue;
409 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800411 return false;
412 }
413 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800414 new_desc.contents()[i].media_description();
415 const MediaContentDescription* current_desc_mdesc =
416 current_desc.contents()[i].media_description();
417 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 return false;
419 }
420 }
421 return true;
422}
423
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800424bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
425 const SessionDescription& desc2) {
426 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800427}
428
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700429void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
430 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200431 // Array of structs needed to map {KeyExchangeProtocolType,
432 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
433 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
434 static constexpr struct {
435 KeyExchangeProtocolType protocol_type;
436 cricket::MediaType media_type;
437 KeyExchangeProtocolMedia protocol_media;
438 } kEnumCounterKeyProtocolMediaMap[] = {
439 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
440 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
441 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
442 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
443 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
444 kEnumCounterKeyProtocolMediaTypeDtlsData},
445 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
446 kEnumCounterKeyProtocolMediaTypeSdesAudio},
447 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
448 kEnumCounterKeyProtocolMediaTypeSdesVideo},
449 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
450 kEnumCounterKeyProtocolMediaTypeSdesData},
451 };
452
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700453 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
454 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100455
Mirko Bonadeiab499822018-09-11 10:43:20 +0200456 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
457 if (i.protocol_type == protocol_type && i.media_type == media_type) {
458 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
459 i.protocol_media,
460 kEnumCounterKeyProtocolMediaTypeMax);
461 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100462 }
463}
464
Harald Alvestrand76829d72018-07-18 23:24:36 +0200465void NoteAddIceCandidateResult(int result) {
466 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
467 kAddIceCandidateMax);
468}
469
Steve Anton75737c02017-11-06 10:37:17 -0800470// Checks that each non-rejected content has SDES crypto keys or a DTLS
471// fingerprint, unless it's in a BUNDLE group, in which case only the
472// BUNDLE-tag section (first media section/description in the BUNDLE group)
473// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
474// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
475// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700476RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100483 // Note what media is used with each crypto protocol, for all sections.
484 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
485 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700486 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800487 const std::string& mid = content_info.name;
488 if (bundle && bundle->HasContentName(mid) &&
489 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800490 // This isn't the first media section in the BUNDLE group, so it's not
491 // required to have crypto attributes, since only the crypto attributes
492 // from the first section actually get used.
493 continue;
494 }
495
496 // If the content isn't rejected or bundled into another m= section, crypto
497 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800498 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800499 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800500 if (!media || !tinfo) {
501 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800503 }
504 if (dtls_enabled) {
505 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100506 RTC_LOG(LS_WARNING)
507 << "Session description must have DTLS fingerprint if "
508 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800509 return RTCError(RTCErrorType::INVALID_PARAMETER,
510 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800511 }
512 } else {
513 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800515 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800516 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800517 }
518 }
519 }
Steve Anton8a006912017-12-04 15:25:56 -0800520 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800521}
522
523// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
524// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
525// media section/description in the BUNDLE group) needs a ufrag and pwd.
526bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
527 const cricket::ContentGroup* bundle =
528 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800529 for (const cricket::ContentInfo& content_info : desc->contents()) {
530 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800531 continue;
532 }
Steve Anton8a006912017-12-04 15:25:56 -0800533 const std::string& mid = content_info.name;
534 if (bundle && bundle->HasContentName(mid) &&
535 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800536 // This isn't the first media section in the BUNDLE group, so it's not
537 // required to have ufrag/password, since only the ufrag/password from
538 // the first section actually get used.
539 continue;
540 }
541
542 // If the content isn't rejected or bundled into another m= section,
543 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800544 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800545 if (!tinfo) {
546 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100547 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800548 return false;
549 }
550 if (tinfo->description.ice_ufrag.empty() ||
551 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100552 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800553 return false;
554 }
555 }
556 return true;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Get the SCTP port out of a SessionDescription.
560// Return -1 if not found.
561int GetSctpPort(const SessionDescription* session_description) {
Harald Alvestrand26bf7c42019-04-23 05:20:17 +0000562 const cricket::SctpDataContentDescription* data_desc =
563 GetFirstSctpDataContentDescription(session_description);
Steve Antonb1c1de12017-12-21 15:14:30 -0800564 RTC_DCHECK(data_desc);
565 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800566 return -1;
567 }
Harald Alvestrand26bf7c42019-04-23 05:20:17 +0000568 return data_desc->port();
Steve Anton75737c02017-11-06 10:37:17 -0800569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800663void ReportSimulcastApiVersion(const char* name,
664 const SessionDescription& session) {
665 bool has_legacy = false;
666 bool has_spec_compliant = false;
667 for (const ContentInfo& content : session.contents()) {
668 if (!content.description) {
669 continue;
670 }
671 has_spec_compliant |= content.description->HasSimulcast();
672 for (const StreamParams& sp : content.description->streams()) {
673 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
674 }
675 }
676
677 if (has_legacy) {
678 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
679 kSimulcastApiVersionMax);
680 }
681 if (has_spec_compliant) {
682 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
683 kSimulcastApiVersionMax);
684 }
685 if (!has_legacy && !has_spec_compliant) {
686 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
687 kSimulcastApiVersionMax);
688 }
689}
690
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200691const ContentInfo* FindTransceiverMSection(
692 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
693 const SessionDescriptionInterface* session_description) {
694 return transceiver->mid()
695 ? session_description->description()->GetContentByName(
696 *transceiver->mid())
697 : nullptr;
698}
699
Steve Anton75737c02017-11-06 10:37:17 -0800700} // namespace
701
Henrik Boström31638672017-11-23 17:48:32 +0100702// Upon completion, posts a task to execute the callback of the
703// SetSessionDescriptionObserver asynchronously on the same thread. At this
704// point, the state of the peer connection might no longer reflect the effects
705// of the SetRemoteDescription operation, as the peer connection could have been
706// modified during the post.
707// TODO(hbos): Remove this class once we remove the version of
708// PeerConnectionInterface::SetRemoteDescription() that takes a
709// SetSessionDescriptionObserver as an argument.
710class PeerConnection::SetRemoteDescriptionObserverAdapter
711 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
712 public:
713 SetRemoteDescriptionObserverAdapter(
714 rtc::scoped_refptr<PeerConnection> pc,
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
716 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
717
718 // SetRemoteDescriptionObserverInterface implementation.
719 void OnSetRemoteDescriptionComplete(RTCError error) override {
720 if (error.ok())
721 pc_->PostSetSessionDescriptionSuccess(wrapper_);
722 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100723 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100724 }
725
726 private:
727 rtc::scoped_refptr<PeerConnection> pc_;
728 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
729};
730
deadbeef293e9262017-01-11 12:28:30 -0800731bool PeerConnectionInterface::RTCConfiguration::operator==(
732 const PeerConnectionInterface::RTCConfiguration& o) const {
733 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800735 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000736 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700737 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800738 BundlePolicy bundle_policy;
739 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700740 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
741 int ice_candidate_pool_size;
742 bool disable_ipv6;
743 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700744 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100745 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700746 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200747 absl::optional<int> screencast_min_bitrate;
748 absl::optional<bool> combined_audio_video_bwe;
749 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800750 TcpCandidatePolicy tcp_candidate_policy;
751 CandidateNetworkPolicy candidate_network_policy;
752 int audio_jitter_buffer_max_packets;
753 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100754 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100755 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800756 int ice_connection_receiving_timeout;
757 int ice_backup_candidate_pair_ping_interval;
758 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800759 bool prioritize_most_likely_ice_candidate_pairs;
760 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800761 bool prune_turn_ports;
762 bool presume_writable_when_fully_relayed;
763 bool enable_ice_renomination;
764 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200765 absl::optional<int> ice_check_interval_strong_connectivity;
766 absl::optional<int> ice_check_interval_weak_connectivity;
767 absl::optional<int> ice_check_min_interval;
768 absl::optional<int> ice_unwritable_timeout;
769 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800770 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200771 absl::optional<int> stun_candidate_keepalive_interval;
772 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200773 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800774 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700776 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700777 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700778 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700779 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100780 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800781 };
782 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
783 "Did you add something to RTCConfiguration and forget to "
784 "update operator==?");
785 return type == o.type && servers == o.servers &&
786 bundle_policy == o.bundle_policy &&
787 rtcp_mux_policy == o.rtcp_mux_policy &&
788 tcp_candidate_policy == o.tcp_candidate_policy &&
789 candidate_network_policy == o.candidate_network_policy &&
790 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
791 audio_jitter_buffer_fast_accelerate ==
792 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100793 audio_jitter_buffer_min_delay_ms ==
794 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100795 audio_jitter_buffer_enable_rtx_handling ==
796 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800797 ice_connection_receiving_timeout ==
798 o.ice_connection_receiving_timeout &&
799 ice_backup_candidate_pair_ping_interval ==
800 o.ice_backup_candidate_pair_ping_interval &&
801 continual_gathering_policy == o.continual_gathering_policy &&
802 certificates == o.certificates &&
803 prioritize_most_likely_ice_candidate_pairs ==
804 o.prioritize_most_likely_ice_candidate_pairs &&
805 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800806 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700807 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100808 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800809 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800810 screencast_min_bitrate == o.screencast_min_bitrate &&
811 combined_audio_video_bwe == o.combined_audio_video_bwe &&
812 enable_dtls_srtp == o.enable_dtls_srtp &&
813 ice_candidate_pool_size == o.ice_candidate_pool_size &&
814 prune_turn_ports == o.prune_turn_ports &&
815 presume_writable_when_fully_relayed ==
816 o.presume_writable_when_fully_relayed &&
817 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800818 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800819 ice_check_interval_strong_connectivity ==
820 o.ice_check_interval_strong_connectivity &&
821 ice_check_interval_weak_connectivity ==
822 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700823 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700824 ice_unwritable_timeout == o.ice_unwritable_timeout &&
825 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800826 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800827 stun_candidate_keepalive_interval ==
828 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200829 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800830 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800831 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700832 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700833 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700834 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700835 use_media_transport_for_data_channels ==
836 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100837 crypto_options == o.crypto_options &&
838 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800839}
840
841bool PeerConnectionInterface::RTCConfiguration::operator!=(
842 const PeerConnectionInterface::RTCConfiguration& o) const {
843 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800844}
845
zhihuang8f65cdf2016-05-06 18:40:30 -0700846// Generate a RTCP CNAME when a PeerConnection is created.
847std::string GenerateRtcpCname() {
848 std::string cname;
849 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800851 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700852 }
853 return cname;
854}
855
zhihuang1c378ed2017-08-17 14:10:50 -0700856bool ValidateOfferAnswerOptions(
857 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
858 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
859 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700860}
861
zhihuang1c378ed2017-08-17 14:10:50 -0700862// From |rtc_options|, fill parts of |session_options| shared by all generated
863// m= sections (in other words, nothing that involves a map/array).
864void ExtractSharedMediaSessionOptions(
865 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
866 cricket::MediaSessionOptions* session_options) {
867 session_options->vad_enabled = rtc_options.voice_activity_detection;
868 session_options->bundle_enabled = rtc_options.use_rtp_mux;
869}
zhihuanga77e6bb2017-08-14 18:17:48 -0700870
zhihuang38ede132017-06-15 12:52:32 -0700871PeerConnection::PeerConnection(PeerConnectionFactory* factory,
872 std::unique_ptr<RtcEventLog> event_log,
873 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700875 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100876 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700877 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700878 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700879 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100880 call_(std::move(call)),
881 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882
883PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800885 RTC_DCHECK_RUN_ON(signaling_thread());
886
Steve Anton8af21862017-12-15 11:20:13 -0800887 // Need to stop transceivers before destroying the stats collector because
888 // AudioRtpSender has a reference to the StatsCollector it will update when
889 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100890 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800891 transceiver->Stop();
892 }
Steve Anton4171afb2017-11-20 10:20:22 -0800893
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800895 if (stats_collector_) {
896 stats_collector_->WaitForPendingRequest();
897 stats_collector_ = nullptr;
898 }
Steve Anton75737c02017-11-06 10:37:17 -0800899
Steve Anton8af21862017-12-15 11:20:13 -0800900 // Don't destroy BaseChannels until after stats has been cleaned up so that
901 // the last stats request can still read from the channels.
902 DestroyAllChannels();
903
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800905
906 webrtc_session_desc_factory_.reset();
907 sctp_invoker_.reset();
908 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800909 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800910 transport_controller_.reset();
911
deadbeef91dd5672016-05-18 16:55:30 -0700912 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100913 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
914 RTC_DCHECK_RUN_ON(network_thread());
915 port_allocator_.reset();
916 });
eladalon248fd4f2017-09-06 05:18:15 -0700917 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700918 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100919 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700920 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800921 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700922 event_log_.reset();
923 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924}
925
Steve Anton8af21862017-12-15 11:20:13 -0800926void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800927 // Destroy video channels first since they may have a pointer to a voice
928 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100929 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800930 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800931 DestroyTransceiverChannel(transceiver);
932 }
933 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100934 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800935 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800936 DestroyTransceiverChannel(transceiver);
937 }
938 }
939 DestroyDataChannel();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000943 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700944 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100945 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100946 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100947 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700948
949 RTCError config_error = ValidateConfiguration(configuration);
950 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700952 return false;
953 }
954
Benjamin Wrightcab58882018-05-02 15:12:47 -0700955 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_ERROR)
957 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100958 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800959 return false;
960 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200961
Benjamin Wrightcab58882018-05-02 15:12:47 -0700962 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800963 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100964 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100965 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800966 return false;
967 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700968
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700970 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700971 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700972 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800973
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200974 cricket::ServerAddresses stun_servers;
975 std::vector<cricket::RelayServerConfig> turn_servers;
976
977 RTCErrorType parse_error =
978 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
979 if (parse_error != RTCErrorType::NONE) {
980 return false;
981 }
982
deadbeef91dd5672016-05-18 16:55:30 -0700983 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700984 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100985 const auto pa_result =
986 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200987 RTC_FROM_HERE,
988 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100989 stun_servers, turn_servers, configuration));
990
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200991 // If initialization was successful, note if STUN or TURN servers
992 // were supplied.
993 if (!stun_servers.empty()) {
994 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
995 }
996 if (!turn_servers.empty()) {
997 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001000 // Send information about IPv4/IPv6 status.
1001 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001002 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001003 address_family = kPeerConnection_IPv6;
1004 } else {
1005 address_family = kPeerConnection_IPv4;
1006 }
1007 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1008 kPeerConnectionAddressFamilyCounter_Max);
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1011
Steve Anton75737c02017-11-06 10:37:17 -08001012 // RFC 3264: The numeric value of the session id and version in the
1013 // o line MUST be representable with a "64 bit signed integer".
1014 // Due to this constraint session id |session_id_| is max limited to
1015 // LLONG_MAX.
1016 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001017 JsepTransportController::Config config;
1018 config.redetermine_role_on_ice_restart =
1019 configuration.redetermine_role_on_ice_restart;
1020 config.ssl_max_version = factory_->options().ssl_max_version;
1021 config.disable_encryption = options.disable_encryption;
1022 config.bundle_policy = configuration.bundle_policy;
1023 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001024 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1025 // stub.
1026 config.crypto_options = configuration.crypto_options.has_value()
1027 ? *configuration.crypto_options
1028 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001029 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001030 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001031#if defined(ENABLE_EXTERNAL_AUTH)
1032 config.enable_external_auth = true;
1033#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001034 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001035
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001036 if (configuration.use_media_transport ||
1037 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001038 if (!factory_->media_transport_factory()) {
1039 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001040 << "PeerConnecton is initialized with use_media_transport = true or "
1041 << "use_media_transport_for_data_channels = true "
1042 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001043 return false;
1044 }
1045
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001046 if (configuration.use_media_transport ||
1047 configuration.use_media_transport_for_data_channels) {
1048 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1049 // RTP media transport is introduced. But until then, we require SDES to
1050 // be enabled.
1051 if (configuration.enable_dtls_srtp.has_value() &&
1052 configuration.enable_dtls_srtp.value()) {
1053 RTC_LOG(LS_WARNING)
1054 << "When media transport is used, SDES must be enabled. Set "
1055 "configuration.enable_dtls_srtp to false. use_media_transport="
1056 << configuration.use_media_transport
1057 << ", use_media_transport_for_data_channels="
1058 << configuration.use_media_transport_for_data_channels;
1059 return false;
1060 }
1061 }
1062
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001063 config.use_media_transport_for_media = configuration.use_media_transport;
1064 config.use_media_transport_for_data_channels =
1065 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001066 config.media_transport_factory = factory_->media_transport_factory();
1067 }
1068
Zhi Huange830e682018-03-30 10:48:35 -07001069 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001070 signaling_thread(), network_thread(), port_allocator_.get(),
1071 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001072 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001073 this, &PeerConnection::OnTransportControllerConnectionState);
1074 transport_controller_->SignalStandardizedIceConnectionState.connect(
1075 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001076 transport_controller_->SignalConnectionState.connect(
1077 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001078 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001079 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001081 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001082 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001083 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1084 transport_controller_->SignalDtlsHandshakeError.connect(
1085 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1086
1087 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001088
deadbeefab9b2d12015-10-14 11:33:11 -07001089 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001090 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091
Steve Antonba818672017-11-06 10:21:57 -08001092 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001093 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001094
Steve Anton75737c02017-11-06 10:37:17 -08001095 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1096 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1097 if (!configuration.certificates.empty()) {
1098 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1099 // just picking the first one. The decision should be made based on the DTLS
1100 // handshake. The DTLS negotiations need to know about all certificates.
1101 certificate = configuration.certificates[0];
1102 }
1103
Steve Antond25da372017-11-06 14:50:29 -08001104 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001105
1106 if (options.disable_encryption) {
1107 dtls_enabled_ = false;
1108 } else {
1109 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001110 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001111 // |configuration| can override the default |dtls_enabled_| value.
1112 if (configuration.enable_dtls_srtp) {
1113 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1114 }
1115 }
1116
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001117 if (configuration.use_media_transport_for_data_channels) {
1118 if (configuration.enable_rtp_data_channel) {
1119 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1120 "use_media_transport_for_data_channels are "
1121 "incompatible and cannot both be set to true";
1122 return false;
1123 }
1124 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1125 } else if (configuration.enable_rtp_data_channel) {
1126 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1127 // set. It takes precendence over the disable_sctp_data_channels
1128 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001129 data_channel_type_ = cricket::DCT_RTP;
1130 } else {
1131 // DTLS has to be enabled to use SCTP.
1132 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1133 data_channel_type_ = cricket::DCT_SCTP;
1134 }
1135 }
1136
1137 video_options_.screencast_min_bitrate_kbps =
1138 configuration.screencast_min_bitrate;
1139 audio_options_.combined_audio_video_bwe =
1140 configuration.combined_audio_video_bwe;
1141
1142 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001143 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001144
1145 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001146 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001147
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001148 audio_options_.audio_jitter_buffer_min_delay_ms =
1149 configuration.audio_jitter_buffer_min_delay_ms;
1150
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001151 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1152 configuration.audio_jitter_buffer_enable_rtx_handling;
1153
Steve Anton75737c02017-11-06 10:37:17 -08001154 // Whether the certificate generator/certificate is null or not determines
1155 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1156 // the right instructions by clearing the variables if needed.
1157 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001158 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001159 certificate = nullptr;
1160 } else if (certificate) {
1161 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001162 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001163 }
1164
1165 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1166 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001167 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001168 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1169 this, &PeerConnection::OnCertificateReady);
1170
1171 if (options.disable_encryption) {
1172 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1173 }
1174
1175 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001176 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001177 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178
Steve Anton4171afb2017-11-20 10:20:22 -08001179 // Add default audio/video transceivers for Plan B SDP.
1180 if (!IsUnifiedPlan()) {
1181 transceivers_.push_back(
1182 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1183 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1184 transceivers_.push_back(
1185 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1186 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1187 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001188 int delay_ms =
1189 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001190 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1191 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001192
1193 if (dependencies.video_bitrate_allocator_factory) {
1194 video_bitrate_allocator_factory_ =
1195 std::move(dependencies.video_bitrate_allocator_factory);
1196 } else {
1197 video_bitrate_allocator_factory_ =
1198 CreateBuiltinVideoBitrateAllocatorFactory();
1199 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 return true;
1201}
1202
Steve Anton038834f2017-07-14 15:59:59 -07001203RTCError PeerConnection::ValidateConfiguration(
1204 const RTCConfiguration& config) const {
1205 if (config.ice_regather_interval_range &&
1206 config.continual_gathering_policy == GATHER_ONCE) {
1207 return RTCError(RTCErrorType::INVALID_PARAMETER,
1208 "ice_regather_interval_range specified but continual "
1209 "gathering policy is GATHER_ONCE");
1210 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001211 auto result =
1212 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1213 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001214}
1215
Yves Gerey665174f2018-06-19 15:03:05 +02001216rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001217 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001218 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1219 "Plan SdpSemantics. Please use GetSenders "
1220 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001221 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222}
1223
Yves Gerey665174f2018-06-19 15:03:05 +02001224rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001225 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001226 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1227 "Plan SdpSemantics. Please use GetReceivers "
1228 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001229 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230}
1231
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001232bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001233 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001234 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1235 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001236 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001237 if (IsClosed()) {
1238 return false;
1239 }
deadbeefab9b2d12015-10-14 11:33:11 -07001240 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 return false;
1242 }
deadbeefab9b2d12015-10-14 11:33:11 -07001243
1244 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001245 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1246 observer->SignalAudioTrackAdded.connect(this,
1247 &PeerConnection::OnAudioTrackAdded);
1248 observer->SignalAudioTrackRemoved.connect(
1249 this, &PeerConnection::OnAudioTrackRemoved);
1250 observer->SignalVideoTrackAdded.connect(this,
1251 &PeerConnection::OnVideoTrackAdded);
1252 observer->SignalVideoTrackRemoved.connect(
1253 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001254 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001255
deadbeefab9b2d12015-10-14 11:33:11 -07001256 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001257 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001258 }
1259 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001260 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001261 }
1262
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001263 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001264 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 return true;
1266}
1267
1268void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001269 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001270 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1271 "Plan SdpSemantics. Please use RemoveTrack "
1272 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001273 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001274 if (!IsClosed()) {
1275 for (const auto& track : local_stream->GetAudioTracks()) {
1276 RemoveAudioTrack(track.get(), local_stream);
1277 }
1278 for (const auto& track : local_stream->GetVideoTracks()) {
1279 RemoveVideoTrack(track.get(), local_stream);
1280 }
deadbeefab9b2d12015-10-14 11:33:11 -07001281 }
deadbeefab9b2d12015-10-14 11:33:11 -07001282 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001283 stream_observers_.erase(
1284 std::remove_if(
1285 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001286 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001287 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001288 }),
1289 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001290
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 if (IsClosed()) {
1292 return;
1293 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001294 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295}
1296
Steve Anton2d6c76a2018-01-05 17:10:52 -08001297RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001298 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001299 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001300 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001301 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (!track) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1304 }
1305 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1306 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1308 "Track has invalid kind: " + track->kind());
1309 }
Steve Antonf9381f02017-12-14 10:23:57 -08001310 if (IsClosed()) {
1311 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1312 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001315 LOG_AND_RETURN_ERROR(
1316 RTCErrorType::INVALID_PARAMETER,
1317 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001318 }
Steve Antonf9381f02017-12-14 10:23:57 -08001319 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001320 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1321 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001322 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001323 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001324 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001325 }
1326 return sender_or_error;
1327}
deadbeefe1f9d832016-01-14 15:35:42 -08001328
Steve Antonf9381f02017-12-14 10:23:57 -08001329RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1330PeerConnection::AddTrackPlanB(
1331 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001332 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001333 if (stream_ids.size() > 1u) {
1334 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1335 "AddTrack with more than one stream is not "
1336 "supported with Plan B semantics.");
1337 }
1338 std::vector<std::string> adjusted_stream_ids = stream_ids;
1339 if (adjusted_stream_ids.empty()) {
1340 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1341 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001342 cricket::MediaType media_type =
1343 (track->kind() == MediaStreamTrackInterface::kAudioKind
1344 ? cricket::MEDIA_TYPE_AUDIO
1345 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001346 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001347 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001348 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001349 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001350 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001351 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001352 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001353 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001354 if (sender_info) {
1355 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001356 }
Steve Antonf9381f02017-12-14 10:23:57 -08001357 } else {
1358 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001359 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001360 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001361 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001362 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001363 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001364 if (sender_info) {
1365 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001366 }
deadbeefe1f9d832016-01-14 15:35:42 -08001367 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001368 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001369}
deadbeefe1f9d832016-01-14 15:35:42 -08001370
Steve Antonf9381f02017-12-14 10:23:57 -08001371RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1372PeerConnection::AddTrackUnifiedPlan(
1373 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001374 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001375 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1376 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001377 RTC_LOG(LS_INFO) << "Reusing an existing "
1378 << cricket::MediaTypeToString(transceiver->media_type())
1379 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001380 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001381 transceiver->internal()->set_direction(
1382 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001384 transceiver->internal()->set_direction(
1385 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001386 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001387 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001388 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001389 } else {
1390 cricket::MediaType media_type =
1391 (track->kind() == MediaStreamTrackInterface::kAudioKind
1392 ? cricket::MEDIA_TYPE_AUDIO
1393 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001394 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1395 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001396 std::string sender_id = track->id();
1397 // Avoid creating a sender with an existing ID by generating a random ID.
1398 // This can happen if this is the second time AddTrack has created a sender
1399 // for this track.
1400 if (FindSenderById(sender_id)) {
1401 sender_id = rtc::CreateRandomUuid();
1402 }
Florent Castelli892acf02018-10-01 22:47:20 +02001403 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1405 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001406 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001407 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001408 }
Steve Antonf9381f02017-12-14 10:23:57 -08001409 return transceiver->sender();
1410}
1411
1412rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1413PeerConnection::FindFirstTransceiverForAddedTrack(
1414 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1415 RTC_DCHECK(track);
1416 for (auto transceiver : transceivers_) {
1417 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001418 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001419 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001420 !transceiver->internal()->has_ever_been_used_to_send() &&
1421 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001422 return transceiver;
1423 }
1424 }
1425 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001426}
1427
1428bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1429 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001430 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001431}
1432
Steve Anton24db5732018-07-23 10:27:33 -07001433RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001434 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001435 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001436 if (!sender) {
1437 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1438 }
deadbeefe1f9d832016-01-14 15:35:42 -08001439 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001440 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1441 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001442 }
Steve Antonf9381f02017-12-14 10:23:57 -08001443 if (IsUnifiedPlan()) {
1444 auto transceiver = FindTransceiverBySender(sender);
1445 if (!transceiver || !sender->track()) {
1446 return RTCError::OK();
1447 }
1448 sender->SetTrack(nullptr);
1449 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001450 transceiver->internal()->set_direction(
1451 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001452 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001453 transceiver->internal()->set_direction(
1454 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001455 }
Steve Anton4171afb2017-11-20 10:20:22 -08001456 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001457 bool removed;
1458 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1459 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1460 } else {
1461 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1462 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1463 }
1464 if (!removed) {
1465 LOG_AND_RETURN_ERROR(
1466 RTCErrorType::INVALID_PARAMETER,
1467 "Couldn't find sender " + sender->id() + " to remove.");
1468 }
Steve Anton4171afb2017-11-20 10:20:22 -08001469 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001470 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001471 return RTCError::OK();
1472}
1473
1474rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1475PeerConnection::FindTransceiverBySender(
1476 rtc::scoped_refptr<RtpSenderInterface> sender) {
1477 for (auto transceiver : transceivers_) {
1478 if (transceiver->sender() == sender) {
1479 return transceiver;
1480 }
1481 }
1482 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001483}
1484
Steve Anton9158ef62017-11-27 13:01:52 -08001485RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1486PeerConnection::AddTransceiver(
1487 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1488 return AddTransceiver(track, RtpTransceiverInit());
1489}
1490
1491RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1492PeerConnection::AddTransceiver(
1493 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1494 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001495 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001496 RTC_CHECK(IsUnifiedPlan())
1497 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001498 if (!track) {
1499 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1500 }
1501 cricket::MediaType media_type;
1502 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1503 media_type = cricket::MEDIA_TYPE_AUDIO;
1504 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1505 media_type = cricket::MEDIA_TYPE_VIDEO;
1506 } else {
1507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1508 "Track kind is not audio or video");
1509 }
1510 return AddTransceiver(media_type, track, init);
1511}
1512
1513RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1514PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1515 return AddTransceiver(media_type, RtpTransceiverInit());
1516}
1517
1518RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1519PeerConnection::AddTransceiver(cricket::MediaType media_type,
1520 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001521 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001522 RTC_CHECK(IsUnifiedPlan())
1523 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001524 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1525 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1527 "media type is not audio or video");
1528 }
1529 return AddTransceiver(media_type, nullptr, init);
1530}
1531
1532RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1533PeerConnection::AddTransceiver(
1534 cricket::MediaType media_type,
1535 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001536 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001537 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001538 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1539 media_type == cricket::MEDIA_TYPE_VIDEO));
1540 if (track) {
1541 RTC_DCHECK_EQ(media_type,
1542 (track->kind() == MediaStreamTrackInterface::kAudioKind
1543 ? cricket::MEDIA_TYPE_AUDIO
1544 : cricket::MEDIA_TYPE_VIDEO));
1545 }
1546
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001547 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1548 init.send_encodings.size(), 0, 7, 8);
1549
Amit Hilbuchaa584152019-02-06 17:09:52 -08001550 size_t num_rids = absl::c_count_if(init.send_encodings,
1551 [](const RtpEncodingParameters& encoding) {
1552 return !encoding.rid.empty();
1553 });
1554 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001555 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001556 RTCErrorType::INVALID_PARAMETER,
1557 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001558 }
1559
Amit Hilbuchf4770402019-04-08 14:11:57 -07001560 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1561 [](const RtpEncodingParameters& encoding) {
1562 return !IsLegalRsidName(encoding.rid);
1563 })) {
1564 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1565 "Invalid RID value provided.");
1566 }
1567
Amit Hilbuchaa584152019-02-06 17:09:52 -08001568 if (absl::c_any_of(init.send_encodings,
1569 [](const RtpEncodingParameters& encoding) {
1570 return encoding.ssrc.has_value();
1571 })) {
1572 LOG_AND_RETURN_ERROR(
1573 RTCErrorType::UNSUPPORTED_PARAMETER,
1574 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001575 }
1576
1577 RtpParameters parameters;
1578 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001579
1580 // Encodings are dropped from the tail if too many are provided.
1581 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1582 parameters.encodings.erase(
1583 parameters.encodings.begin() + kMaxSimulcastStreams,
1584 parameters.encodings.end());
1585 }
1586
1587 // Single RID should be removed.
1588 if (parameters.encodings.size() == 1 &&
1589 !parameters.encodings[0].rid.empty()) {
1590 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1591 parameters.encodings[0].rid.clear();
1592 }
1593
1594 // If RIDs were not provided, they are generated for simulcast scenario.
1595 if (parameters.encodings.size() > 1 && num_rids == 0) {
1596 rtc::UniqueStringGenerator rid_generator;
1597 for (RtpEncodingParameters& encoding : parameters.encodings) {
1598 encoding.rid = rid_generator();
1599 }
1600 }
1601
Florent Castelli892acf02018-10-01 22:47:20 +02001602 if (UnimplementedRtpParameterHasValue(parameters)) {
1603 LOG_AND_RETURN_ERROR(
1604 RTCErrorType::UNSUPPORTED_PARAMETER,
1605 "Attempted to set an unimplemented parameter of RtpParameters.");
1606 }
Steve Anton9158ef62017-11-27 13:01:52 -08001607
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001608 auto result = cricket::CheckRtpParametersValues(parameters);
1609 if (!result.ok()) {
1610 LOG_AND_RETURN_ERROR(result.type(), result.message());
1611 }
1612
Steve Anton3d954a62018-04-02 11:27:23 -07001613 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1614 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001615 // Set the sender ID equal to the track ID if the track is specified unless
1616 // that sender ID is already in use.
1617 std::string sender_id =
1618 (track && !FindSenderById(track->id()) ? track->id()
1619 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001620 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001621 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001622 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1623 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1624 transceiver->internal()->set_direction(init.direction);
1625
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001626 if (update_negotiation_needed) {
1627 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001628 }
Steve Antonf9381f02017-12-14 10:23:57 -08001629
1630 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1631}
1632
Steve Anton02ee47c2018-01-10 16:26:06 -08001633rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1634PeerConnection::CreateSender(
1635 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001636 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001637 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001638 const std::vector<std::string>& stream_ids,
1639 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001640 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001641 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001642 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1643 RTC_DCHECK(!track ||
1644 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1645 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1646 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001647 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001648 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001649 } else {
1650 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1651 RTC_DCHECK(!track ||
1652 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1653 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001654 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001655 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001656 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001657 bool set_track_succeeded = sender->SetTrack(track);
1658 RTC_DCHECK(set_track_succeeded);
1659 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001660 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001661 return sender;
1662}
1663
1664rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1665PeerConnection::CreateReceiver(cricket::MediaType media_type,
1666 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001667 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1668 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001669 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001670 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001671 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1672 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001673 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001674 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001675 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001676 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001677 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1678 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001679 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001680 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001681 return receiver;
1682}
1683
1684rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1685PeerConnection::CreateAndAddTransceiver(
1686 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1687 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1688 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001689 // Ensure that the new sender does not have an ID that is already in use by
1690 // another sender.
1691 // Allow receiver IDs to conflict since those come from remote SDP (which
1692 // could be invalid, but should not cause a crash).
1693 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001694 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1695 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001696 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001697 transceiver->internal()->SignalNegotiationNeeded.connect(
1698 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001699 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001700}
1701
Steve Anton52d86772018-02-20 15:48:12 -08001702void PeerConnection::OnNegotiationNeeded() {
1703 RTC_DCHECK_RUN_ON(signaling_thread());
1704 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001705 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001706}
1707
deadbeeffac06552015-11-25 11:26:01 -08001708rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001709 const std::string& kind,
1710 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001711 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001712 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1713 "Plan SdpSemantics. Please use AddTransceiver "
1714 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001715 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001716 if (IsClosed()) {
1717 return nullptr;
1718 }
Steve Anton4171afb2017-11-20 10:20:22 -08001719
Seth Hampson5b4f0752018-04-02 16:31:36 -07001720 // Internally we need to have one stream with Plan B semantics, so we
1721 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001722 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001723 if (stream_id.empty()) {
1724 stream_ids.push_back(rtc::CreateRandomUuid());
1725 RTC_LOG(LS_INFO)
1726 << "No stream_id specified for sender. Generated stream ID: "
1727 << stream_ids[0];
1728 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001729 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001730 }
1731
Steve Anton4171afb2017-11-20 10:20:22 -08001732 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001733 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001734 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001735 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001736 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001737 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001738 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001740 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001741 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001742 auto video_sender =
1743 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001744 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001745 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001746 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001747 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001748 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001750 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001751 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001752 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001753
deadbeefe1f9d832016-01-14 15:35:42 -08001754 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001755}
1756
deadbeef70ab1a12015-09-28 16:53:55 -07001757std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1758 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001759 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001760 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001761 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001762 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001763 }
1764 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001765}
1766
Steve Anton4171afb2017-11-20 10:20:22 -08001767std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1768PeerConnection::GetSendersInternal() const {
1769 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1770 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001771 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001772 auto senders = transceiver->internal()->senders();
1773 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1774 }
1775 return all_senders;
1776}
1777
deadbeef70ab1a12015-09-28 16:53:55 -07001778std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1779PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001780 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001781 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001782 for (const auto& receiver : GetReceiversInternal()) {
1783 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001784 }
1785 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001786}
1787
Steve Anton4171afb2017-11-20 10:20:22 -08001788std::vector<
1789 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1790PeerConnection::GetReceiversInternal() const {
1791 std::vector<
1792 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1793 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001794 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001795 auto receivers = transceiver->internal()->receivers();
1796 all_receivers.insert(all_receivers.end(), receivers.begin(),
1797 receivers.end());
1798 }
1799 return all_receivers;
1800}
1801
Steve Anton9158ef62017-11-27 13:01:52 -08001802std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1803PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001804 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001805 RTC_CHECK(IsUnifiedPlan())
1806 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001807 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001808 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001809 all_transceivers.push_back(transceiver);
1810 }
1811 return all_transceivers;
1812}
1813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001815 MediaStreamTrackInterface* track,
1816 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001817 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001818 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001819 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001820 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821 return false;
1822 }
1823
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001824 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001825 // The StatsCollector is used to tell if a track is valid because it may
1826 // remember tracks that the PeerConnection previously removed.
1827 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001828 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1829 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001830 return false;
1831 }
Steve Antonad182762018-09-05 20:22:40 +00001832 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1833 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834 return true;
1835}
1836
hbos74e1a4f2016-09-15 23:33:01 -07001837void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001838 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001839 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001840 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001841 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001842 stats_collector_->GetStatsReport(callback);
1843}
1844
Henrik Boström1df1bf82018-03-20 13:24:20 +01001845void PeerConnection::GetStats(
1846 rtc::scoped_refptr<RtpSenderInterface> selector,
1847 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1848 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001849 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001850 RTC_DCHECK(callback);
1851 RTC_DCHECK(stats_collector_);
1852 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1853 if (selector) {
1854 for (const auto& proxy_transceiver : transceivers_) {
1855 for (const auto& proxy_sender :
1856 proxy_transceiver->internal()->senders()) {
1857 if (proxy_sender == selector) {
1858 internal_sender = proxy_sender->internal();
1859 break;
1860 }
1861 }
1862 if (internal_sender)
1863 break;
1864 }
1865 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001866 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001867 // belong to the PeerConnection (in Plan B, senders can be removed from the
1868 // PeerConnection). This means that "all the stats objects representing the
1869 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1870 // produces an empty stats report.
1871 stats_collector_->GetStatsReport(internal_sender, callback);
1872}
1873
1874void PeerConnection::GetStats(
1875 rtc::scoped_refptr<RtpReceiverInterface> selector,
1876 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1877 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001878 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001879 RTC_DCHECK(callback);
1880 RTC_DCHECK(stats_collector_);
1881 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1882 if (selector) {
1883 for (const auto& proxy_transceiver : transceivers_) {
1884 for (const auto& proxy_receiver :
1885 proxy_transceiver->internal()->receivers()) {
1886 if (proxy_receiver == selector) {
1887 internal_receiver = proxy_receiver->internal();
1888 break;
1889 }
1890 }
1891 if (internal_receiver)
1892 break;
1893 }
1894 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001895 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001896 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1897 // the PeerConnection). This means that "all the stats objects representing
1898 // the selector" is an empty set. Invoking GetStatsReport() with a null
1899 // selector produces an empty stats report.
1900 stats_collector_->GetStatsReport(internal_receiver, callback);
1901}
1902
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001904 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 return signaling_state_;
1906}
1907
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908PeerConnectionInterface::IceConnectionState
1909PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001910 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 return ice_connection_state_;
1912}
1913
Alex Loiko9289eda2018-11-23 16:18:59 +00001914PeerConnectionInterface::IceConnectionState
1915PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001916 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001917 return standardized_ice_connection_state_;
1918}
1919
Jonas Olsson635474e2018-10-18 15:58:17 +02001920PeerConnectionInterface::PeerConnectionState
1921PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001922 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001923 return connection_state_;
1924}
1925
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926PeerConnectionInterface::IceGatheringState
1927PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001928 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 return ice_gathering_state_;
1930}
1931
Yves Gerey665174f2018-06-19 15:03:05 +02001932rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 const std::string& label,
1934 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001935 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001936 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001937
deadbeefab9b2d12015-10-14 11:33:11 -07001938 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001939
kwibergd1fe2812016-04-27 06:47:29 -07001940 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001941 if (config) {
1942 internal_config.reset(new InternalDataChannelInit(*config));
1943 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001944 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001945 InternalCreateDataChannel(label, internal_config.get()));
1946 if (!channel.get()) {
1947 return nullptr;
1948 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001950 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1951 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001952 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001953 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001954 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001955 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956 return DataChannelProxy::Create(signaling_thread(), channel.get());
1957}
1958
1959void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001960 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001961 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001962 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001963
nisse7ce109a2017-01-31 00:57:56 -08001964 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001965 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001966 return;
1967 }
deadbeefab9b2d12015-10-14 11:33:11 -07001968
Steve Anton8d3444d2017-10-20 15:30:51 -07001969 if (IsClosed()) {
1970 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001971 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001972 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001973 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001974 return;
1975 }
1976
zhihuang1c378ed2017-08-17 14:10:50 -07001977 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001978 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001979 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001980 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001981 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001982 return;
1983 }
1984
Steve Anton22da89f2018-01-25 13:58:07 -08001985 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1986 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1987 if (IsUnifiedPlan()) {
1988 RTCError error = HandleLegacyOfferOptions(options);
1989 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001990 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001991 return;
1992 }
1993 }
1994
zhihuang1c378ed2017-08-17 14:10:50 -07001995 cricket::MediaSessionOptions session_options;
1996 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001997 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998}
1999
Steve Anton22da89f2018-01-25 13:58:07 -08002000RTCError PeerConnection::HandleLegacyOfferOptions(
2001 const RTCOfferAnswerOptions& options) {
2002 RTC_DCHECK(IsUnifiedPlan());
2003
2004 if (options.offer_to_receive_audio == 0) {
2005 RemoveRecvDirectionFromReceivingTransceiversOfType(
2006 cricket::MEDIA_TYPE_AUDIO);
2007 } else if (options.offer_to_receive_audio == 1) {
2008 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2009 } else if (options.offer_to_receive_audio > 1) {
2010 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2011 "offer_to_receive_audio > 1 is not supported.");
2012 }
2013
2014 if (options.offer_to_receive_video == 0) {
2015 RemoveRecvDirectionFromReceivingTransceiversOfType(
2016 cricket::MEDIA_TYPE_VIDEO);
2017 } else if (options.offer_to_receive_video == 1) {
2018 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2019 } else if (options.offer_to_receive_video > 1) {
2020 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2021 "offer_to_receive_video > 1 is not supported.");
2022 }
2023
2024 return RTCError::OK();
2025}
2026
2027void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2028 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002029 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002030 RtpTransceiverDirection new_direction =
2031 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2032 if (new_direction != transceiver->direction()) {
2033 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2034 << " transceiver (MID="
2035 << transceiver->mid().value_or("<not set>") << ") from "
2036 << RtpTransceiverDirectionToString(
2037 transceiver->direction())
2038 << " to "
2039 << RtpTransceiverDirectionToString(new_direction)
2040 << " since CreateOffer specified offer_to_receive=0";
2041 transceiver->internal()->set_direction(new_direction);
2042 }
Steve Anton22da89f2018-01-25 13:58:07 -08002043 }
2044}
2045
2046void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2047 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002048 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002049 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002050 RTC_LOG(LS_INFO)
2051 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2052 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002053 RtpTransceiverInit init;
2054 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002055 AddTransceiver(media_type, nullptr, init,
2056 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002057 }
2058}
2059
2060std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2061PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2062 std::vector<
2063 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2064 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002065 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002066 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002067 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2068 receiving_transceivers.push_back(transceiver);
2069 }
2070 }
2071 return receiving_transceivers;
2072}
2073
htaa2a49d92016-03-04 02:51:39 -08002074void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2075 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002076 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002077 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002078 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002079 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002080 return;
2081 }
2082
Steve Antondffead82018-02-06 10:31:29 -08002083 if (!(signaling_state_ == kHaveRemoteOffer ||
2084 signaling_state_ == kHaveLocalPrAnswer)) {
2085 std::string error =
2086 "PeerConnection cannot create an answer in a state other than "
2087 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002088 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002089 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002090 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002091 return;
2092 }
2093
Steve Antondffead82018-02-06 10:31:29 -08002094 // The remote description should be set if we're in the right state.
2095 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002096
Steve Anton22da89f2018-01-25 13:58:07 -08002097 if (IsUnifiedPlan()) {
2098 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2099 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2100 "supported with Unified Plan semantics. Use the "
2101 "RtpTransceiver API instead.";
2102 }
2103 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2104 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2105 "supported with Unified Plan semantics. Use the "
2106 "RtpTransceiver API instead.";
2107 }
2108 }
2109
htaa2a49d92016-03-04 02:51:39 -08002110 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002111 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002112
Steve Antond25da372017-11-06 14:50:29 -08002113 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114}
2115
2116void PeerConnection::SetLocalDescription(
2117 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002118 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002119 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002120 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002121
Steve Anton80dd7b52018-02-16 17:08:42 -08002122 // The SetLocalDescription contract is that we take ownership of the session
2123 // description regardless of the outcome, so wrap it in a unique_ptr right
2124 // away. Ideally, SetLocalDescription's signature will be changed to take the
2125 // description as a unique_ptr argument to formalize this agreement.
2126 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2127
nisse7ce109a2017-01-31 00:57:56 -08002128 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002129 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 return;
2131 }
Steve Anton8a006912017-12-04 15:25:56 -08002132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002134 PostSetSessionDescriptionFailure(
2135 observer,
2136 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 return;
2138 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002139
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 // If a session error has occurred the PeerConnection is in a possibly
2141 // inconsistent state so fail right away.
2142 if (session_error() != SessionError::kNone) {
2143 std::string error_message = GetSessionErrorMsg();
2144 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002145 PostSetSessionDescriptionFailure(
2146 observer,
2147 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002148 return;
2149 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002150
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2152 if (!error.ok()) {
2153 std::string error_message = GetSetDescriptionErrorMessage(
2154 cricket::CS_LOCAL, desc->GetType(), error);
2155 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002156 PostSetSessionDescriptionFailure(
2157 observer,
2158 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002159 return;
2160 }
2161
2162 // Grab the description type before moving ownership to ApplyLocalDescription,
2163 // which may destroy it before returning.
2164 const SdpType type = desc->GetType();
2165
2166 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002167 // |desc| may be destroyed at this point.
2168
2169 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002170 // If ApplyLocalDescription fails, the PeerConnection could be in an
2171 // inconsistent state, so act conservatively here and set the session error
2172 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2173 SetSessionError(SessionError::kContent, error.message());
2174 std::string error_message =
2175 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2176 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002177 PostSetSessionDescriptionFailure(
2178 observer,
2179 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002180 return;
2181 }
Steve Anton8a006912017-12-04 15:25:56 -08002182 RTC_DCHECK(local_description());
2183
2184 PostSetSessionDescriptionSuccess(observer);
2185
Steve Antonad182762018-09-05 20:22:40 +00002186 // MaybeStartGathering needs to be called after posting
2187 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2188 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002189 transport_controller_->MaybeStartGathering();
2190
Steve Antona3a92c22017-12-07 10:27:41 -08002191 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002192 // TODO(deadbeef): We already had to hop to the network thread for
2193 // MaybeStartGathering...
2194 network_thread()->Invoke<void>(
2195 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2196 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002197 // Make UMA notes about what was agreed to.
2198 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002199 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002200
2201 if (IsUnifiedPlan()) {
2202 bool was_negotiation_needed = is_negotiation_needed_;
2203 UpdateNegotiationNeeded();
2204 if (signaling_state() == kStable && was_negotiation_needed &&
2205 is_negotiation_needed_) {
2206 Observer()->OnRenegotiationNeeded();
2207 }
2208 }
2209
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002210 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002211}
2212
2213RTCError PeerConnection::ApplyLocalDescription(
2214 std::unique_ptr<SessionDescriptionInterface> desc) {
2215 RTC_DCHECK_RUN_ON(signaling_thread());
2216 RTC_DCHECK(desc);
2217
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 // Update stats here so that we have the most recent stats for tracks and
2219 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002220 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002221
Steve Antondcc3c022017-12-22 16:02:54 -08002222 // Take a reference to the old local description since it's used below to
2223 // compare against the new local description. When setting the new local
2224 // description, grab ownership of the replaced session description in case it
2225 // is the same as |old_local_description|, to keep it alive for the duration
2226 // of the method.
2227 const SessionDescriptionInterface* old_local_description =
2228 local_description();
2229 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002230 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002231 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002232 replaced_local_description = pending_local_description_
2233 ? std::move(pending_local_description_)
2234 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002235 current_local_description_ = std::move(desc);
2236 pending_local_description_ = nullptr;
2237 current_remote_description_ = std::move(pending_remote_description_);
2238 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002239 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002240 pending_local_description_ = std::move(desc);
2241 }
2242 // The session description to apply now must be accessed by
2243 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002244 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002245
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002246 // Report statistics about any use of simulcast.
2247 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2248 *local_description()->description());
2249
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002250 if (!is_caller_) {
2251 if (remote_description()) {
2252 // Remote description was applied first, so this PC is the callee.
2253 is_caller_ = false;
2254 } else {
2255 // Local description is applied first, so this PC is the caller.
2256 is_caller_ = true;
2257 }
2258 }
2259
Zhi Huange830e682018-03-30 10:48:35 -07002260 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2261 if (!error.ok()) {
2262 return error;
2263 }
2264
Steve Antondcc3c022017-12-22 16:02:54 -08002265 if (IsUnifiedPlan()) {
2266 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002267 cricket::CS_LOCAL, *local_description(), old_local_description,
2268 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002269 if (!error.ok()) {
2270 return error;
2271 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002272 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2273 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002274 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002275 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2276 // Note that code paths that don't set MID won't be able to use
2277 // information about DTLS transports.
2278 if (transceiver->mid()) {
2279 auto dtls_transport =
2280 LookupDtlsTransportByMidInternal(*transceiver->mid());
2281 transceiver->internal()->sender_internal()->set_transport(
2282 dtls_transport);
2283 transceiver->internal()->receiver_internal()->set_transport(
2284 dtls_transport);
2285 }
2286
Steve Antondcc3c022017-12-22 16:02:54 -08002287 const ContentInfo* content =
2288 FindMediaSectionForTransceiver(transceiver, local_description());
2289 if (!content) {
2290 continue;
2291 }
2292 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002293 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2294 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002295 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002296 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2297 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2298 // "recvonly", process the removal of a remote track for the media
2299 // description, given transceiver, removeList, and muteTracks.
2300 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2301 (transceiver->internal()->fired_direction() &&
2302 RtpTransceiverDirectionHasRecv(
2303 *transceiver->internal()->fired_direction()))) {
2304 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2305 &removed_streams);
2306 }
2307 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2308 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002309 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002310 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002311 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002312 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002313 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002314 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002315 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002316 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002317 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002318 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002319 }
2320 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002321 // Media channels will be created only when offer is set. These may use new
2322 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002323 if (type == SdpType::kOffer) {
2324 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2325 // description is applied. Restore back to old description.
2326 RTCError error = CreateChannels(*local_description()->description());
2327 if (!error.ok()) {
2328 return error;
2329 }
2330 }
Steve Antondcc3c022017-12-22 16:02:54 -08002331 // Remove unused channels if MediaContentDescription is rejected.
2332 RemoveUnusedChannels(local_description()->description());
2333 }
Steve Anton8a006912017-12-04 15:25:56 -08002334
Zhi Huange830e682018-03-30 10:48:35 -07002335 error = UpdateSessionState(type, cricket::CS_LOCAL,
2336 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002337 if (!error.ok()) {
2338 return error;
2339 }
Steve Antondcc3c022017-12-22 16:02:54 -08002340
Steve Anton8a006912017-12-04 15:25:56 -08002341 if (remote_description()) {
2342 // Now that we have a local description, we can push down remote candidates.
2343 UseCandidatesInSessionDescription(remote_description());
2344 }
2345
2346 pending_ice_restarts_.clear();
2347 if (session_error() != SessionError::kNone) {
2348 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2349 }
2350
deadbeefab9b2d12015-10-14 11:33:11 -07002351 // If setting the description decided our SSL role, allocate any necessary
2352 // SCTP sids.
2353 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002354 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002355 AllocateSctpSids(role);
2356 }
2357
Steve Antond3679212018-01-17 17:41:02 -08002358 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002359 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002360 const ContentInfo* content =
2361 FindMediaSectionForTransceiver(transceiver, local_description());
2362 if (!content) {
2363 continue;
2364 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002365 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2366 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002367 // 0 is a special value meaning "this sender has no associated send
2368 // stream". Need to call this so the sender won't attempt to configure
2369 // a no longer existing stream and run into DCHECKs in the lower
2370 // layers.
2371 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002372 } else {
2373 // Get the StreamParams from the channel which could generate SSRCs.
2374 const std::vector<StreamParams>& streams = channel->local_streams();
2375 transceiver->internal()->sender_internal()->set_stream_ids(
2376 streams[0].stream_ids());
2377 transceiver->internal()->sender_internal()->SetSsrc(
2378 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002379 }
2380 }
2381 } else {
2382 // Plan B semantics.
2383
Steve Antondcc3c022017-12-22 16:02:54 -08002384 // Update state and SSRC of local MediaStreams and DataChannels based on the
2385 // local session description.
2386 const cricket::ContentInfo* audio_content =
2387 GetFirstAudioContent(local_description()->description());
2388 if (audio_content) {
2389 if (audio_content->rejected) {
2390 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2391 } else {
2392 const cricket::AudioContentDescription* audio_desc =
2393 audio_content->media_description()->as_audio();
2394 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2395 }
deadbeeffaac4972015-11-12 15:33:07 -08002396 }
deadbeefab9b2d12015-10-14 11:33:11 -07002397
Steve Antondcc3c022017-12-22 16:02:54 -08002398 const cricket::ContentInfo* video_content =
2399 GetFirstVideoContent(local_description()->description());
2400 if (video_content) {
2401 if (video_content->rejected) {
2402 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2403 } else {
2404 const cricket::VideoContentDescription* video_desc =
2405 video_content->media_description()->as_video();
2406 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2407 }
deadbeeffaac4972015-11-12 15:33:07 -08002408 }
deadbeefab9b2d12015-10-14 11:33:11 -07002409 }
2410
2411 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002412 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002413 if (data_content) {
2414 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002415 data_content->media_description()->as_data();
Harald Alvestrand26bf7c42019-04-23 05:20:17 +00002416 // data_desc will be null if this is an SCTP description.
2417 if (data_desc && absl::StartsWith(data_desc->protocol(),
2418 cricket::kMediaProtocolRtpPrefix)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002419 UpdateLocalRtpDataChannels(data_desc->streams());
2420 }
2421 }
2422
Steve Anton8a006912017-12-04 15:25:56 -08002423 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424}
2425
Steve Anton06817cd2018-12-18 15:55:30 -08002426// The SDP parser used to populate these values by default for the 'content
2427// name' if an a=mid line was absent.
2428static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2429 switch (media_type) {
2430 case cricket::MEDIA_TYPE_AUDIO:
2431 return cricket::CN_AUDIO;
2432 case cricket::MEDIA_TYPE_VIDEO:
2433 return cricket::CN_VIDEO;
2434 case cricket::MEDIA_TYPE_DATA:
2435 return cricket::CN_DATA;
2436 }
2437 RTC_NOTREACHED();
2438 return "";
2439}
2440
2441void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002442 cricket::SessionDescription* new_remote_description) {
2443 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002444 const cricket::ContentInfos& local_contents =
2445 (local_description() ? local_description()->description()->contents()
2446 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002447 const cricket::ContentInfos& remote_contents =
2448 (remote_description() ? remote_description()->description()->contents()
2449 : cricket::ContentInfos());
2450 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2451 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002452 if (!content.name.empty()) {
2453 continue;
2454 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002455 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002456 absl::string_view source_explanation;
2457 if (IsUnifiedPlan()) {
2458 if (i < local_contents.size()) {
2459 new_mid = local_contents[i].name;
2460 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002461 } else if (i < remote_contents.size()) {
2462 new_mid = remote_contents[i].name;
2463 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002464 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002465 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002466 source_explanation = "generated just now";
2467 }
2468 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002469 new_mid = std::string(
2470 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002471 source_explanation = "to match pre-existing behavior";
2472 }
Steve Antond7180cc2019-02-07 10:44:53 -08002473 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002474 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002475 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002476 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2477 << " is missing an a=mid line. Filling in the value '"
2478 << new_mid << "' " << source_explanation << ".";
2479 }
2480}
2481
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002482void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002483 SetSessionDescriptionObserver* observer,
2484 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002485 SetRemoteDescription(
2486 std::unique_ptr<SessionDescriptionInterface>(desc),
2487 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2488 new SetRemoteDescriptionObserverAdapter(this, observer)));
2489}
2490
2491void PeerConnection::SetRemoteDescription(
2492 std::unique_ptr<SessionDescriptionInterface> desc,
2493 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002494 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002495 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002496
nisse7ce109a2017-01-31 00:57:56 -08002497 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002498 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 return;
2500 }
Steve Anton8a006912017-12-04 15:25:56 -08002501
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002503 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002504 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002505 return;
2506 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002507
Steve Anton80dd7b52018-02-16 17:08:42 -08002508 // If a session error has occurred the PeerConnection is in a possibly
2509 // inconsistent state so fail right away.
2510 if (session_error() != SessionError::kNone) {
2511 std::string error_message = GetSessionErrorMsg();
2512 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2513 observer->OnSetRemoteDescriptionComplete(
2514 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2515 return;
2516 }
Steve Anton71439a62018-02-15 11:53:06 -08002517
Steve Antonba42e992018-04-09 14:10:01 -07002518 if (desc->GetType() == SdpType::kOffer) {
2519 // Report to UMA the format of the received offer.
2520 ReportSdpFormatReceived(*desc);
2521 }
2522
Steve Anton06817cd2018-12-18 15:55:30 -08002523 // Handle remote descriptions missing a=mid lines for interop with legacy end
2524 // points.
2525 FillInMissingRemoteMids(desc->description());
2526
Steve Anton80dd7b52018-02-16 17:08:42 -08002527 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002528 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002529 std::string error_message = GetSetDescriptionErrorMessage(
2530 cricket::CS_REMOTE, desc->GetType(), error);
2531 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002532 observer->OnSetRemoteDescriptionComplete(
2533 RTCError(error.type(), std::move(error_message)));
2534 return;
2535 }
Steve Anton71439a62018-02-15 11:53:06 -08002536
Steve Anton80dd7b52018-02-16 17:08:42 -08002537 // Grab the description type before moving ownership to
2538 // ApplyRemoteDescription, which may destroy it before returning.
2539 const SdpType type = desc->GetType();
2540
2541 error = ApplyRemoteDescription(std::move(desc));
2542 // |desc| may be destroyed at this point.
2543
2544 if (!error.ok()) {
2545 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2546 // inconsistent state, so act conservatively here and set the session error
2547 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2548 SetSessionError(SessionError::kContent, error.message());
2549 std::string error_message =
2550 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2551 RTC_LOG(LS_ERROR) << error_message;
2552 observer->OnSetRemoteDescriptionComplete(
2553 RTCError(error.type(), std::move(error_message)));
2554 return;
2555 }
2556 RTC_DCHECK(remote_description());
2557
2558 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002559 // TODO(deadbeef): We already had to hop to the network thread for
2560 // MaybeStartGathering...
2561 network_thread()->Invoke<void>(
2562 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2563 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002564 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002565 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002566 }
2567
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002568 if (IsUnifiedPlan()) {
2569 bool was_negotiation_needed = is_negotiation_needed_;
2570 UpdateNegotiationNeeded();
2571 if (signaling_state() == kStable && was_negotiation_needed &&
2572 is_negotiation_needed_) {
2573 Observer()->OnRenegotiationNeeded();
2574 }
2575 }
2576
Steve Anton8a006912017-12-04 15:25:56 -08002577 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002578 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002579}
2580
2581RTCError PeerConnection::ApplyRemoteDescription(
2582 std::unique_ptr<SessionDescriptionInterface> desc) {
2583 RTC_DCHECK_RUN_ON(signaling_thread());
2584 RTC_DCHECK(desc);
2585
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002586 // Update stats here so that we have the most recent stats for tracks and
2587 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002588 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002589
Steve Antondcc3c022017-12-22 16:02:54 -08002590 // Take a reference to the old remote description since it's used below to
2591 // compare against the new remote description. When setting the new remote
2592 // description, grab ownership of the replaced session description in case it
2593 // is the same as |old_remote_description|, to keep it alive for the duration
2594 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002595 const SessionDescriptionInterface* old_remote_description =
2596 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002597 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002598 SdpType type = desc->GetType();
2599 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002600 replaced_remote_description = pending_remote_description_
2601 ? std::move(pending_remote_description_)
2602 : std::move(current_remote_description_);
2603 current_remote_description_ = std::move(desc);
2604 pending_remote_description_ = nullptr;
2605 current_local_description_ = std::move(pending_local_description_);
2606 } else {
2607 replaced_remote_description = std::move(pending_remote_description_);
2608 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 }
Steve Anton8a006912017-12-04 15:25:56 -08002610 // The session description to apply now must be accessed by
2611 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002612 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002614 // Report statistics about any use of simulcast.
2615 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2616 *remote_description()->description());
2617
Zhi Huange830e682018-03-30 10:48:35 -07002618 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2619 if (!error.ok()) {
2620 return error;
2621 }
Steve Anton8a006912017-12-04 15:25:56 -08002622 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002623 if (IsUnifiedPlan()) {
2624 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002625 cricket::CS_REMOTE, *remote_description(), local_description(),
2626 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002627 if (!error.ok()) {
2628 return error;
2629 }
Steve Antondcc3c022017-12-22 16:02:54 -08002630 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002631 // Media channels will be created only when offer is set. These may use new
2632 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002633 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002634 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002635 // description is applied. Restore back to old description.
2636 RTCError error = CreateChannels(*remote_description()->description());
2637 if (!error.ok()) {
2638 return error;
2639 }
2640 }
Steve Antondcc3c022017-12-22 16:02:54 -08002641 // Remove unused channels if MediaContentDescription is rejected.
2642 RemoveUnusedChannels(remote_description()->description());
2643 }
Steve Anton8a006912017-12-04 15:25:56 -08002644
Zhi Huange830e682018-03-30 10:48:35 -07002645 // NOTE: Candidates allocation will be initiated only when
2646 // SetLocalDescription is called.
2647 error = UpdateSessionState(type, cricket::CS_REMOTE,
2648 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002649 if (!error.ok()) {
2650 return error;
2651 }
2652
2653 if (local_description() &&
2654 !UseCandidatesInSessionDescription(remote_description())) {
2655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2656 }
2657
2658 if (old_remote_description) {
2659 for (const cricket::ContentInfo& content :
2660 old_remote_description->description()->contents()) {
2661 // Check if this new SessionDescription contains new ICE ufrag and
2662 // password that indicates the remote peer requests an ICE restart.
2663 // TODO(deadbeef): When we start storing both the current and pending
2664 // remote description, this should reset pending_ice_restarts and compare
2665 // against the current description.
2666 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2667 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002668 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002669 pending_ice_restarts_.insert(content.name);
2670 }
2671 } else {
2672 // We retain all received candidates only if ICE is not restarted.
2673 // When ICE is restarted, all previous candidates belong to an old
2674 // generation and should not be kept.
2675 // TODO(deadbeef): This goes against the W3C spec which says the remote
2676 // description should only contain candidates from the last set remote
2677 // description plus any candidates added since then. We should remove
2678 // this once we're sure it won't break anything.
2679 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2680 old_remote_description, content.name, mutable_remote_description());
2681 }
2682 }
2683 }
2684
2685 if (session_error() != SessionError::kNone) {
2686 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2687 }
2688
2689 // Set the the ICE connection state to connecting since the connection may
2690 // become writable with peer reflexive candidates before any remote candidate
2691 // is signaled.
2692 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2693 // is to have a new signal the indicates a change in checking state from the
2694 // transport and expose a new checking() member from transport that can be
2695 // read to determine the current checking state. The existing SignalConnecting
2696 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002697 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002698 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002699 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2700 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2701 }
2702
deadbeefab9b2d12015-10-14 11:33:11 -07002703 // If setting the description decided our SSL role, allocate any necessary
2704 // SCTP sids.
2705 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002706 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002707 AllocateSctpSids(role);
2708 }
2709
Steve Antondcc3c022017-12-22 16:02:54 -08002710 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002711 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002712 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002713 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002714 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002715 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002716 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002717 const ContentInfo* content =
2718 FindMediaSectionForTransceiver(transceiver, remote_description());
2719 if (!content) {
2720 continue;
2721 }
2722 const MediaContentDescription* media_desc = content->media_description();
2723 RtpTransceiverDirection local_direction =
2724 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002725 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2726 // RTCSessionDescription: Set the associated remote streams given
2727 // transceiver.[[Receiver]], msids, addList, and removeList".
2728 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2729 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2730 std::vector<std::string> stream_ids;
2731 if (!media_desc->streams().empty()) {
2732 // The remote description has signaled the stream IDs.
2733 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002734 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002735 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2736 << " (" << GetStreamIdsString(stream_ids) << ").";
2737 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2738 stream_ids, &added_streams,
2739 &removed_streams);
2740 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2741 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2742 // and transceiver's current direction is neither sendrecv nor recvonly,
2743 // process the addition of a remote track for the media description.
2744 if (!transceiver->fired_direction() ||
2745 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2746 RTC_LOG(LS_INFO)
2747 << "Processing the addition of a remote track for MID="
2748 << content->name << ".";
2749 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002750 }
Steve Antondcc3c022017-12-22 16:02:54 -08002751 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002752 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2754 // removal of a remote track for the media description, given transceiver,
2755 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002756 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002757 (transceiver->fired_direction() &&
2758 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2759 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2760 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002761 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002763 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002764 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002765 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002766 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002767 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002768 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002769 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002770 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2771 if (transceiver->mid()) {
2772 auto dtls_transport =
2773 LookupDtlsTransportByMidInternal(*transceiver->mid());
2774 transceiver->internal()->sender_internal()->set_transport(
2775 dtls_transport);
2776 transceiver->internal()->receiver_internal()->set_transport(
2777 dtls_transport);
2778 }
Steve Antondcc3c022017-12-22 16:02:54 -08002779 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002780 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002781 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002782 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002783 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2784 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002785 transceiver->Stop();
2786 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002787 if (!content->rejected &&
2788 RtpTransceiverDirectionHasRecv(local_direction)) {
2789 // Set ssrc to 0 in the case of an unsignalled ssrc.
2790 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002791 if (!media_desc->streams().empty() &&
2792 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002793 ssrc = media_desc->streams()[0].first_ssrc();
2794 }
2795 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002796 }
Steve Antondcc3c022017-12-22 16:02:54 -08002797 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002798 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002799 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002801 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002802 observer->OnTrack(transceiver);
2803 observer->OnAddTrack(transceiver->receiver(),
2804 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002805 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002806 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002807 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002808 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002809 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002810 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002811 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002812 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002813 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002814 }
Steve Antondcc3c022017-12-22 16:02:54 -08002815 }
2816
Henrik Boströmfdb92012017-11-09 19:55:44 +01002817 const cricket::ContentInfo* audio_content =
2818 GetFirstAudioContent(remote_description()->description());
2819 const cricket::ContentInfo* video_content =
2820 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002821 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002822 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002823 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002824 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002825 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002826 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002827
2828 // Check if the descriptions include streams, just in case the peer supports
2829 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002830 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002831 (audio_desc && !audio_desc->streams().empty()) ||
2832 (video_desc && !video_desc->streams().empty())) {
2833 remote_peer_supports_msid_ = true;
2834 }
deadbeefab9b2d12015-10-14 11:33:11 -07002835
2836 // We wait to signal new streams until we finish processing the description,
2837 // since only at that point will new streams have all their tracks.
2838 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2839
Steve Antondcc3c022017-12-22 16:02:54 -08002840 if (!IsUnifiedPlan()) {
2841 // TODO(steveanton): When removing RTP senders/receivers in response to a
2842 // rejected media section, there is some cleanup logic that expects the
2843 // voice/ video channel to still be set. But in this method the voice/video
2844 // channel would have been destroyed by the SetRemoteDescription caller
2845 // above so the cleanup that relies on them fails to run. The RemoveSenders
2846 // calls should be moved to right before the DestroyChannel calls to fix
2847 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002848
Steve Antondcc3c022017-12-22 16:02:54 -08002849 // Find all audio rtp streams and create corresponding remote AudioTracks
2850 // and MediaStreams.
2851 if (audio_content) {
2852 if (audio_content->rejected) {
2853 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2854 } else {
2855 bool default_audio_track_needed =
2856 !remote_peer_supports_msid_ &&
2857 RtpTransceiverDirectionHasSend(audio_desc->direction());
2858 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2859 default_audio_track_needed, audio_desc->type(),
2860 new_streams);
2861 }
deadbeeffaac4972015-11-12 15:33:07 -08002862 }
deadbeefab9b2d12015-10-14 11:33:11 -07002863
Steve Antondcc3c022017-12-22 16:02:54 -08002864 // Find all video rtp streams and create corresponding remote VideoTracks
2865 // and MediaStreams.
2866 if (video_content) {
2867 if (video_content->rejected) {
2868 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2869 } else {
2870 bool default_video_track_needed =
2871 !remote_peer_supports_msid_ &&
2872 RtpTransceiverDirectionHasSend(video_desc->direction());
2873 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2874 default_video_track_needed, video_desc->type(),
2875 new_streams);
2876 }
deadbeeffaac4972015-11-12 15:33:07 -08002877 }
deadbeefab9b2d12015-10-14 11:33:11 -07002878
Steve Antondcc3c022017-12-22 16:02:54 -08002879 // Update the DataChannels with the information from the remote peer.
2880 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002881 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002882 cricket::kMediaProtocolRtpPrefix)) {
2883 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2884 }
deadbeefab9b2d12015-10-14 11:33:11 -07002885 }
deadbeefab9b2d12015-10-14 11:33:11 -07002886
Steve Antondcc3c022017-12-22 16:02:54 -08002887 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002888 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002889 for (size_t i = 0; i < new_streams->count(); ++i) {
2890 MediaStreamInterface* new_stream = new_streams->at(i);
2891 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002892 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002893 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2894 }
deadbeefab9b2d12015-10-14 11:33:11 -07002895
Steve Antondcc3c022017-12-22 16:02:54 -08002896 UpdateEndedRemoteMediaStreams();
2897 }
deadbeefab9b2d12015-10-14 11:33:11 -07002898
Steve Anton8a006912017-12-04 15:25:56 -08002899 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002900}
2901
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002902void PeerConnection::SetAssociatedRemoteStreams(
2903 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2904 const std::vector<std::string>& stream_ids,
2905 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2906 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2907 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2908 for (const std::string& stream_id : stream_ids) {
2909 rtc::scoped_refptr<MediaStreamInterface> stream =
2910 remote_streams_->find(stream_id);
2911 if (!stream) {
2912 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2913 MediaStream::Create(stream_id));
2914 remote_streams_->AddStream(stream);
2915 added_streams->push_back(stream);
2916 }
2917 media_streams.push_back(stream);
2918 }
2919 // Special case: "a=msid" missing, use random stream ID.
2920 if (media_streams.empty() &&
2921 !(remote_description()->description()->msid_signaling() &
2922 cricket::kMsidSignalingMediaSection)) {
2923 if (!missing_msid_default_stream_) {
2924 missing_msid_default_stream_ = MediaStreamProxy::Create(
2925 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2926 added_streams->push_back(missing_msid_default_stream_);
2927 }
2928 media_streams.push_back(missing_msid_default_stream_);
2929 }
2930 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2931 receiver->streams();
2932 // SetStreams() will add/remove the receiver's track to/from the streams. This
2933 // differs from the spec - the spec uses an "addList" and "removeList" to
2934 // update the stream-track relationships in a later step. We do this earlier,
2935 // changing the order of things, but the end-result is the same.
2936 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2937 // instead. https://crbug.com/webrtc/9480
2938 receiver->SetStreams(media_streams);
2939 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2940}
2941
Steve Anton0f5400a2018-07-17 14:25:36 -07002942void PeerConnection::ProcessRemovalOfRemoteTrack(
2943 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2944 transceiver,
2945 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2946 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2947 RTC_DCHECK(transceiver->mid());
2948 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2949 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002950 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002951 transceiver->internal()->receiver_internal()->streams();
2952 // This will remove the remote track from the streams.
2953 transceiver->internal()->receiver_internal()->set_stream_ids({});
2954 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002955 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2956}
2957
2958void PeerConnection::RemoveRemoteStreamsIfEmpty(
2959 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2960 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2961 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2962 // streams, see if the stream was removed by checking if this was the last
2963 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002964 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002965 if (remote_stream->GetAudioTracks().empty() &&
2966 remote_stream->GetVideoTracks().empty()) {
2967 remote_streams_->RemoveStream(remote_stream);
2968 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002969 }
2970 }
2971}
2972
Steve Antondcc3c022017-12-22 16:02:54 -08002973RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2974 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002975 const SessionDescriptionInterface& new_session,
2976 const SessionDescriptionInterface* old_local_description,
2977 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002978 RTC_DCHECK(IsUnifiedPlan());
2979
Steve Anton7464fca2018-01-19 11:10:37 -08002980 const cricket::ContentGroup* bundle_group = nullptr;
2981 if (new_session.GetType() == SdpType::kOffer) {
2982 auto bundle_group_or_error =
2983 GetEarlyBundleGroup(*new_session.description());
2984 if (!bundle_group_or_error.ok()) {
2985 return bundle_group_or_error.MoveError();
2986 }
2987 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002988 }
Steve Antondcc3c022017-12-22 16:02:54 -08002989
Steve Antondcc3c022017-12-22 16:02:54 -08002990 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002991 for (size_t i = 0; i < new_contents.size(); ++i) {
2992 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002993 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002994 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002995 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2996 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002997 const cricket::ContentInfo* old_local_content = nullptr;
2998 if (old_local_description &&
2999 i < old_local_description->description()->contents().size()) {
3000 old_local_content =
3001 &old_local_description->description()->contents()[i];
3002 }
3003 const cricket::ContentInfo* old_remote_content = nullptr;
3004 if (old_remote_description &&
3005 i < old_remote_description->description()->contents().size()) {
3006 old_remote_content =
3007 &old_remote_description->description()->contents()[i];
3008 }
Steve Antondcc3c022017-12-22 16:02:54 -08003009 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003010 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3011 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003012 if (!transceiver_or_error.ok()) {
3013 return transceiver_or_error.MoveError();
3014 }
3015 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003016 RTCError error =
3017 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3018 if (!error.ok()) {
3019 return error;
3020 }
3021 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003022 if (GetDataMid() && new_content.name != *GetDataMid()) {
3023 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003024 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3025 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003026 continue;
3027 }
3028 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3029 if (!error.ok()) {
3030 return error;
3031 }
Steve Antondcc3c022017-12-22 16:02:54 -08003032 } else {
3033 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3034 "Unknown section type.");
3035 }
3036 }
3037
3038 return RTCError::OK();
3039}
3040
3041RTCError PeerConnection::UpdateTransceiverChannel(
3042 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3043 transceiver,
3044 const cricket::ContentInfo& content,
3045 const cricket::ContentGroup* bundle_group) {
3046 RTC_DCHECK(IsUnifiedPlan());
3047 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003048 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003049 if (content.rejected) {
3050 if (channel) {
3051 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003052 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003053 }
3054 } else {
3055 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003056 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003057 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003058 } else {
Steve Anton69470252018-02-09 11:43:08 -08003059 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003060 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003061 }
3062 if (!channel) {
3063 LOG_AND_RETURN_ERROR(
3064 RTCErrorType::INTERNAL_ERROR,
3065 "Failed to create channel for mid=" + content.name);
3066 }
3067 transceiver->internal()->SetChannel(channel);
3068 }
3069 }
3070 return RTCError::OK();
3071}
3072
Steve Antonfa2260d2017-12-28 16:38:23 -08003073RTCError PeerConnection::UpdateDataChannel(
3074 cricket::ContentSource source,
3075 const cricket::ContentInfo& content,
3076 const cricket::ContentGroup* bundle_group) {
3077 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003078 // If data channels are disabled, ignore this media section. CreateAnswer
3079 // will take care of rejecting it.
3080 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003081 }
3082 if (content.rejected) {
3083 DestroyDataChannel();
3084 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003085 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003086 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003087 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3088 "Failed to create data channel.");
3089 }
3090 }
3091 if (source == cricket::CS_REMOTE) {
3092 const MediaContentDescription* data_desc = content.media_description();
3093 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3094 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3095 }
3096 }
3097 }
3098 return RTCError::OK();
3099}
3100
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003101// This method will extract any send encodings that were sent by the remote
3102// connection. This is currently only relevant for Simulcast scenario (where
3103// the number of layers may be communicated by the server).
3104static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3105 const MediaContentDescription& desc) {
3106 if (!desc.HasSimulcast()) {
3107 return {};
3108 }
3109 std::vector<RtpEncodingParameters> result;
3110 const SimulcastDescription& simulcast = desc.simulcast_description();
3111
3112 // This is a remote description, the parameters we are after should appear
3113 // as receive streams.
3114 for (const auto& alternatives : simulcast.receive_layers()) {
3115 RTC_DCHECK(!alternatives.empty());
3116 // There is currently no way to specify or choose from alternatives.
3117 // We will always use the first alternative, which is the most preferred.
3118 const SimulcastLayer& layer = alternatives[0];
3119 RtpEncodingParameters parameters;
3120 parameters.rid = layer.rid;
3121 parameters.active = !layer.is_paused;
3122 result.push_back(parameters);
3123 }
3124
3125 return result;
3126}
3127
3128static RTCError UpdateSimulcastLayerStatusInSender(
3129 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003130 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003131 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003132 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003133 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003134
3135 // The simulcast envelope cannot be changed, only the status of the streams.
3136 // So we will iterate over the send encodings rather than the layers.
3137 for (RtpEncodingParameters& encoding : parameters.encodings) {
3138 auto iter = std::find_if(layers.begin(), layers.end(),
3139 [&encoding](const SimulcastLayer& layer) {
3140 return layer.rid == encoding.rid;
3141 });
3142 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003143 if (iter == layers.end()) {
3144 disabled_layers.push_back(encoding.rid);
3145 continue;
3146 }
3147
3148 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003149 }
3150
Amit Hilbuch619b2942019-02-26 15:55:19 -08003151 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003152 if (result.ok()) {
3153 result = sender->DisableEncodingLayers(disabled_layers);
3154 }
3155
3156 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003157}
3158
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003159static bool SimulcastIsRejected(
3160 const ContentInfo* local_content,
3161 const MediaContentDescription& answer_media_desc) {
3162 bool simulcast_offered = local_content &&
3163 local_content->media_description() &&
3164 local_content->media_description()->HasSimulcast();
3165 bool simulcast_answered = answer_media_desc.HasSimulcast();
3166 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3167 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3168 return simulcast_offered && (!simulcast_answered || !rids_supported);
3169}
3170
Amit Hilbuch2297d332019-02-19 12:49:22 -08003171static RTCError DisableSimulcastInSender(
3172 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003173 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003174 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003175 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003176 return RTCError::OK();
3177 }
3178
Amit Hilbuch2297d332019-02-19 12:49:22 -08003179 std::vector<std::string> disabled_layers;
3180 std::transform(
3181 parameters.encodings.begin() + 1, parameters.encodings.end(),
3182 std::back_inserter(disabled_layers),
3183 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3184 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003185}
3186
Steve Antondcc3c022017-12-22 16:02:54 -08003187RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3188PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003189 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003190 size_t mline_index,
3191 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003192 const ContentInfo* old_local_content,
3193 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003194 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003195 // If this is an offer then the m= section might be recycled. If the m=
3196 // section is being recycled (defined as: rejected in the current local or
3197 // remote description and not rejected in new description), dissociate the
3198 // currently associated RtpTransceiver by setting its mid property to null,
3199 // and discard the mapping between the transceiver and its m= section index.
3200 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3201 old_remote_content)) {
3202 // We want to dissociate the transceiver that has the rejected mid.
3203 const std::string& old_mid =
3204 (old_local_content && old_local_content->rejected)
3205 ? old_local_content->name
3206 : old_remote_content->name;
3207 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003208 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003209 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3210 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003211 old_transceiver->internal()->set_mid(absl::nullopt);
3212 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003213 }
3214 }
3215 const MediaContentDescription* media_desc = content.media_description();
3216 auto transceiver = GetAssociatedTransceiver(content.name);
3217 if (source == cricket::CS_LOCAL) {
3218 // Find the RtpTransceiver that corresponds to this m= section, using the
3219 // mapping between transceivers and m= section indices established when
3220 // creating the offer.
3221 if (!transceiver) {
3222 transceiver = GetTransceiverByMLineIndex(mline_index);
3223 }
3224 if (!transceiver) {
3225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3226 "Unknown transceiver");
3227 }
3228 } else {
3229 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3230 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3231 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003232 // When simulcast is requested, a transceiver cannot be associated because
3233 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003234 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003235 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3236 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003237 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3238 }
3239 // If no RtpTransceiver was found in the previous step, create one with a
3240 // recvonly direction.
3241 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003242 RTC_LOG(LS_INFO) << "Adding "
3243 << cricket::MediaTypeToString(media_desc->type())
3244 << " transceiver for MID=" << content.name
3245 << " at i=" << mline_index
3246 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003247 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003248 std::vector<RtpEncodingParameters> send_encodings =
3249 GetSendEncodingsFromRemoteDescription(*media_desc);
3250 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3251 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003252 std::string receiver_id;
3253 if (!media_desc->streams().empty()) {
3254 receiver_id = media_desc->streams()[0].id;
3255 } else {
3256 receiver_id = rtc::CreateRandomUuid();
3257 }
3258 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003259 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003260 transceiver->internal()->set_direction(
3261 RtpTransceiverDirection::kRecvOnly);
3262 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003263
3264 // Check if the offer indicated simulcast but the answer rejected it.
3265 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003266 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003267 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003268 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003269 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003270 if (!error.ok()) {
3271 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3272 return std::move(error);
3273 }
3274 }
Steve Antondcc3c022017-12-22 16:02:54 -08003275 }
3276 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003277 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003278 LOG_AND_RETURN_ERROR(
3279 RTCErrorType::INVALID_PARAMETER,
3280 "Transceiver type does not match media description type.");
3281 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003282 if (media_desc->HasSimulcast()) {
3283 std::vector<SimulcastLayer> layers =
3284 source == cricket::CS_LOCAL
3285 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3286 : media_desc->simulcast_description()
3287 .receive_layers()
3288 .GetAllLayers();
3289 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003290 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003291 if (!error.ok()) {
3292 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3293 return std::move(error);
3294 }
3295 }
Steve Antondcc3c022017-12-22 16:02:54 -08003296 // Associate the found or created RtpTransceiver with the m= section by
3297 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3298 // section, and establish a mapping between the transceiver and the index of
3299 // the m= section.
3300 transceiver->internal()->set_mid(content.name);
3301 transceiver->internal()->set_mline_index(mline_index);
3302 return std::move(transceiver);
3303}
3304
3305rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3306PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3307 RTC_DCHECK(IsUnifiedPlan());
3308 for (auto transceiver : transceivers_) {
3309 if (transceiver->mid() == mid) {
3310 return transceiver;
3311 }
3312 }
3313 return nullptr;
3314}
3315
3316rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3317PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3318 RTC_DCHECK(IsUnifiedPlan());
3319 for (auto transceiver : transceivers_) {
3320 if (transceiver->internal()->mline_index() == mline_index) {
3321 return transceiver;
3322 }
3323 }
3324 return nullptr;
3325}
3326
3327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3328PeerConnection::FindAvailableTransceiverToReceive(
3329 cricket::MediaType media_type) const {
3330 RTC_DCHECK(IsUnifiedPlan());
3331 // From JSEP section 5.10 (Applying a Remote Description):
3332 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3333 // the same type that were added to the PeerConnection by addTrack and are not
3334 // associated with any m= section and are not stopped, find the first such
3335 // RtpTransceiver.
3336 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003337 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003338 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3339 !transceiver->stopped()) {
3340 return transceiver;
3341 }
3342 }
3343 return nullptr;
3344}
3345
Steve Antoned10bd92017-12-05 10:52:59 -08003346const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3347 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3348 transceiver,
3349 const SessionDescriptionInterface* sdesc) const {
3350 RTC_DCHECK(transceiver);
3351 RTC_DCHECK(sdesc);
3352 if (IsUnifiedPlan()) {
3353 if (!transceiver->internal()->mid()) {
3354 // This transceiver is not associated with a media section yet.
3355 return nullptr;
3356 }
3357 return sdesc->description()->GetContentByName(
3358 *transceiver->internal()->mid());
3359 } else {
3360 // Plan B only allows at most one audio and one video section, so use the
3361 // first media section of that type.
3362 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003363 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003364 }
3365}
3366
deadbeef46c73892016-11-16 19:42:04 -08003367PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003368 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003369 return configuration_;
3370}
3371
deadbeef293e9262017-01-11 12:28:30 -08003372bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3373 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003374 RTC_DCHECK_RUN_ON(signaling_thread());
3375 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003376 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003377 if (IsClosed()) {
3378 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3379 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3380 }
3381
Qingsi Wanga2d60672018-04-11 16:57:45 -07003382 // According to JSEP, after setLocalDescription, changing the candidate pool
3383 // size is not allowed, and changing the set of ICE servers will not result
3384 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003385 if (local_description() && configuration.ice_candidate_pool_size !=
3386 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003387 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3388 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003389 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003390 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003391
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003392 if (local_description() &&
3393 configuration.use_media_transport != configuration_.use_media_transport) {
3394 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3395 "SetLocalDescription.";
3396 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3397 }
3398
3399 if (remote_description() &&
3400 configuration.use_media_transport != configuration_.use_media_transport) {
3401 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3402 "SetRemoteDescription.";
3403 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3404 }
3405
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003406 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003407 configuration.use_media_transport_for_data_channels !=
3408 configuration_.use_media_transport_for_data_channels) {
3409 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3410 "after calling SetLocalDescription.";
3411 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3412 }
3413
3414 if (remote_description() &&
3415 configuration.use_media_transport_for_data_channels !=
3416 configuration_.use_media_transport_for_data_channels) {
3417 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3418 "after calling SetRemoteDescription.";
3419 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3420 }
3421
3422 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003423 configuration.crypto_options != configuration_.crypto_options) {
3424 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3425 "SetLocalDescription.";
3426 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3427 }
3428
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003429 if (configuration.use_media_transport_for_data_channels ||
3430 configuration.use_media_transport) {
3431 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3432 << "Media transport requires MaxBundle policy.";
3433 }
3434
deadbeef293e9262017-01-11 12:28:30 -08003435 // The simplest (and most future-compatible) way to tell if the config was
3436 // modified in an invalid way is to copy each property we do support
3437 // modifying, then use operator==. There are far more properties we don't
3438 // support modifying than those we do, and more could be added.
3439 RTCConfiguration modified_config = configuration_;
3440 modified_config.servers = configuration.servers;
3441 modified_config.type = configuration.type;
3442 modified_config.ice_candidate_pool_size =
3443 configuration.ice_candidate_pool_size;
3444 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003445 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003446 modified_config.ice_check_interval_strong_connectivity =
3447 configuration.ice_check_interval_strong_connectivity;
3448 modified_config.ice_check_interval_weak_connectivity =
3449 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003450 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3451 modified_config.ice_unwritable_min_checks =
3452 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003453 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003454 modified_config.stun_candidate_keepalive_interval =
3455 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003456 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003457 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003458 modified_config.active_reset_srtp_params =
3459 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003460 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003461 modified_config.use_media_transport_for_data_channels =
3462 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003463 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003464 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003465 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3466 }
3467
Steve Anton038834f2017-07-14 15:59:59 -07003468 // Validate the modified configuration.
3469 RTCError validate_error = ValidateConfiguration(modified_config);
3470 if (!validate_error.ok()) {
3471 return SafeSetError(std::move(validate_error), error);
3472 }
3473
deadbeef293e9262017-01-11 12:28:30 -08003474 // Note that this isn't possible through chromium, since it's an unsigned
3475 // short in WebIDL.
3476 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003477 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003478 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3479 }
3480
3481 // Parse ICE servers before hopping to network thread.
3482 cricket::ServerAddresses stun_servers;
3483 std::vector<cricket::RelayServerConfig> turn_servers;
3484 RTCErrorType parse_error =
3485 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3486 if (parse_error != RTCErrorType::NONE) {
3487 return SafeSetError(parse_error, error);
3488 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003489 // Note if STUN or TURN servers were supplied.
3490 if (!stun_servers.empty()) {
3491 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3492 }
3493 if (!turn_servers.empty()) {
3494 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3495 }
deadbeef293e9262017-01-11 12:28:30 -08003496
3497 // In theory this shouldn't fail.
3498 if (!network_thread()->Invoke<bool>(
3499 RTC_FROM_HERE,
3500 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3501 stun_servers, turn_servers, modified_config.type,
3502 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003503 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003504 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003505 modified_config.stun_candidate_keepalive_interval,
3506 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003507 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003508 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3509 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003510
deadbeefd1a38b52016-12-10 13:15:33 -08003511 // As described in JSEP, calling setConfiguration with new ICE servers or
3512 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3513 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003514 if (modified_config.servers != configuration_.servers ||
3515 modified_config.type != configuration_.type ||
3516 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003517 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003518 }
skvladd1f5fda2017-02-03 16:54:05 -08003519
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003520 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003521 transport_controller_->SetMediaTransportSettings(
3522 modified_config.use_media_transport,
3523 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003524
Zhi Huangb57e1692018-06-12 11:41:11 -07003525 if (configuration_.active_reset_srtp_params !=
3526 modified_config.active_reset_srtp_params) {
3527 transport_controller_->SetActiveResetSrtpParams(
3528 modified_config.active_reset_srtp_params);
3529 }
3530
deadbeef293e9262017-01-11 12:28:30 -08003531 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003532 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003533 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003534}
3535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003536bool PeerConnection::AddIceCandidate(
3537 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003538 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003539 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003540 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003541 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003542 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003543 return false;
3544 }
Steve Antond25da372017-11-06 14:50:29 -08003545
3546 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003547 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003548 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003549 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003550 return false;
3551 }
3552
3553 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003554 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003555 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003556 return false;
3557 }
3558
3559 bool valid = false;
3560 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3561 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003562 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003563 return false;
3564 }
3565
3566 // Add this candidate to the remote session description.
3567 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003568 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003569 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003570 return false;
3571 }
3572
3573 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003574 bool result = UseCandidate(ice_candidate);
3575 if (result) {
3576 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3577 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3578 } else {
3579 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3580 }
3581 return result;
Steve Antond25da372017-11-06 14:50:29 -08003582 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003583 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003584 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003585 return true;
3586 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003587}
3588
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003589bool PeerConnection::RemoveIceCandidates(
3590 const std::vector<cricket::Candidate>& candidates) {
3591 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003592 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003593 if (IsClosed()) {
3594 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3595 return false;
3596 }
3597
Steve Antond25da372017-11-06 14:50:29 -08003598 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003599 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3600 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003601 return false;
3602 }
3603
3604 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003605 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003606 return false;
3607 }
3608
3609 size_t number_removed =
3610 mutable_remote_description()->RemoveCandidates(candidates);
3611 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003612 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003613 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003614 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003615 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003616 }
3617
3618 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003619 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3620 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003621 RTC_LOG(LS_ERROR)
3622 << "RemoveIceCandidates: Error when removing remote candidates: "
3623 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003624 }
3625 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003626}
3627
Niels Möller0c4f7be2018-05-07 14:01:37 +02003628RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003629 if (!worker_thread()->IsCurrent()) {
3630 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003631 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003632 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003633 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003634
Niels Möller0c4f7be2018-05-07 14:01:37 +02003635 const bool has_min = bitrate.min_bitrate_bps.has_value();
3636 const bool has_start = bitrate.start_bitrate_bps.has_value();
3637 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003638 if (has_min && *bitrate.min_bitrate_bps < 0) {
3639 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3640 "min_bitrate_bps <= 0");
3641 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003642 if (has_start) {
3643 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003644 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003645 "start_bitrate_bps < min_bitrate_bps");
3646 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3648 "curent_bitrate_bps < 0");
3649 }
3650 }
3651 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003652 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003653 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003654 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003655 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3657 "max_bitrate_bps < min_bitrate_bps");
3658 } else if (*bitrate.max_bitrate_bps < 0) {
3659 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3660 "max_bitrate_bps < 0");
3661 }
3662 }
3663
zstein4b979802017-06-02 14:37:37 -07003664 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003665 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003666
3667 return RTCError::OK();
3668}
3669
Alex Narest78609d52017-10-20 10:37:47 +02003670void PeerConnection::SetBitrateAllocationStrategy(
3671 std::unique_ptr<rtc::BitrateAllocationStrategy>
3672 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003673 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003674 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3675 // move-capture values in lambdas.
3676 struct Task {
3677 PeerConnection* const pc;
3678 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3679 void operator()() {
3680 RTC_DCHECK_RUN_ON(pc->worker_thread());
3681 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3682 }
3683 };
3684 worker_thread()->Invoke<void>(
3685 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003686 return;
3687 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003688 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003689 RTC_DCHECK(call_.get());
3690 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3691}
3692
henrika5f6bf242017-11-01 11:06:56 +01003693void PeerConnection::SetAudioPlayout(bool playout) {
3694 if (!worker_thread()->IsCurrent()) {
3695 worker_thread()->Invoke<void>(
3696 RTC_FROM_HERE,
3697 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3698 return;
3699 }
3700 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003701 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003702 audio_state->SetPlayout(playout);
3703}
3704
3705void PeerConnection::SetAudioRecording(bool recording) {
3706 if (!worker_thread()->IsCurrent()) {
3707 worker_thread()->Invoke<void>(
3708 RTC_FROM_HERE,
3709 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3710 return;
3711 }
3712 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003713 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003714 audio_state->SetRecording(recording);
3715}
3716
Steve Anton8c0f7a72017-10-03 10:03:10 -07003717std::unique_ptr<rtc::SSLCertificate>
3718PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003719 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3720 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003721 return nullptr;
3722 }
Steve Antonf25303e2018-10-16 15:23:31 -07003723 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003724}
3725
Zhi Huang70b820f2018-01-27 14:16:15 -08003726std::unique_ptr<rtc::SSLCertChain>
3727PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003728 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003729 auto audio_transceiver = GetFirstAudioTransceiver();
3730 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003731 return nullptr;
3732 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003733 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003734 audio_transceiver->internal()->channel()->transport_name());
3735}
3736
3737rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3738PeerConnection::GetFirstAudioTransceiver() const {
3739 for (auto transceiver : transceivers_) {
3740 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3741 return transceiver;
3742 }
3743 }
3744 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003745}
3746
ivoc14d5dbe2016-07-04 07:06:55 -07003747bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3748 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003749 // TODO(eladalon): It would be better to not allow negative values into PC.
3750 const size_t max_size = (max_size_bytes < 0)
3751 ? RtcEventLog::kUnlimitedOutput
3752 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003753 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3754 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3755 output_period_ms = 5000;
3756 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003757 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003758 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003759 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003760}
3761
Bjorn Tereliusde939432017-11-20 17:38:14 +01003762bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3763 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003764 // TODO(eladalon): In C++14, this can be done with a lambda.
3765 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003766 bool operator()() {
3767 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3768 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003769 PeerConnection* const pc;
3770 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003771 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003772 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003773 return worker_thread()->Invoke<bool>(
3774 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003775}
3776
3777void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003778 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003779 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3780}
3781
Harald Alvestrandad88c882018-11-28 16:47:46 +01003782rtc::scoped_refptr<DtlsTransportInterface>
3783PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003784 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003785 return transport_controller_->LookupDtlsTransportByMid(mid);
3786}
3787
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003788rtc::scoped_refptr<DtlsTransport>
3789PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003790 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003791 return transport_controller_->LookupDtlsTransportByMid(mid);
3792}
3793
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003794rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3795 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003796 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003797 return sctp_transport_;
3798}
3799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003800const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003801 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003802 return pending_local_description_ ? pending_local_description_.get()
3803 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003804}
3805
3806const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003807 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003808 return pending_remote_description_ ? pending_remote_description_.get()
3809 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003810}
3811
deadbeeffe4a8a42016-12-20 17:56:17 -08003812const SessionDescriptionInterface* PeerConnection::current_local_description()
3813 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003814 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003815 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003816}
3817
3818const SessionDescriptionInterface* PeerConnection::current_remote_description()
3819 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003820 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003821 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003822}
3823
3824const SessionDescriptionInterface* PeerConnection::pending_local_description()
3825 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003826 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003827 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003828}
3829
3830const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3831 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003832 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003833 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003834}
3835
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003836void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003837 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003838 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003839 // Update stats here so that we have the most recent stats for tracks and
3840 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003841 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003842
Steve Anton75737c02017-11-06 10:37:17 -08003843 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003844 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003845
Mirko Bonadei739baf02019-01-27 17:29:42 +01003846 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003847 transceiver->Stop();
3848 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003849
3850 // Ensure that all asynchronous stats requests are completed before destroying
3851 // the transport controller below.
3852 if (stats_collector_) {
3853 stats_collector_->WaitForPendingRequest();
3854 }
3855
3856 // Don't destroy BaseChannels until after stats has been cleaned up so that
3857 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003858 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003859
Qingsi Wang93a84392018-01-30 17:13:09 -08003860 // The event log is used in the transport controller, which must be outlived
3861 // by the former. CreateOffer by the peer connection is implemented
3862 // asynchronously and if the peer connection is closed without resetting the
3863 // WebRTC session description factory, the session description factory would
3864 // call the transport controller.
3865 webrtc_session_desc_factory_.reset();
3866 transport_controller_.reset();
3867
deadbeef42a42632017-03-10 15:18:00 -08003868 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003869 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3870 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003871
Steve Anton978b8762017-09-29 12:15:02 -07003872 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003873 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003874 call_.reset();
3875 // The event log must outlive call (and any other object that uses it).
3876 event_log_.reset();
3877 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003878 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003879 // The .h file says that observer can be discarded after close() returns.
3880 // Make sure this is true.
3881 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003882}
3883
Steve Antonad182762018-09-05 20:22:40 +00003884void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003885 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003886 switch (msg->message_id) {
3887 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3888 SetSessionDescriptionMsg* param =
3889 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3890 param->observer->OnSuccess();
3891 delete param;
3892 break;
3893 }
3894 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3895 SetSessionDescriptionMsg* param =
3896 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3897 param->observer->OnFailure(std::move(param->error));
3898 delete param;
3899 break;
3900 }
3901 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3902 CreateSessionDescriptionMsg* param =
3903 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3904 param->observer->OnFailure(std::move(param->error));
3905 delete param;
3906 break;
3907 }
3908 case MSG_GETSTATS: {
3909 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3910 StatsReports reports;
3911 stats_->GetStats(param->track, &reports);
3912 param->observer->OnComplete(reports);
3913 delete param;
3914 break;
3915 }
3916 case MSG_FREE_DATACHANNELS: {
3917 sctp_data_channels_to_free_.clear();
3918 break;
3919 }
3920 case MSG_REPORT_USAGE_PATTERN: {
3921 ReportUsagePattern();
3922 break;
3923 }
3924 default:
3925 RTC_NOTREACHED() << "Not implemented";
3926 break;
3927 }
3928}
3929
Steve Antonafb0bb72018-02-20 11:35:37 -08003930cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3931 RTC_DCHECK(!IsUnifiedPlan());
3932 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3933 GetAudioTransceiver()->internal()->channel());
3934 if (voice_channel) {
3935 return voice_channel->media_channel();
3936 } else {
3937 return nullptr;
3938 }
3939}
3940
3941cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3942 RTC_DCHECK(!IsUnifiedPlan());
3943 auto* video_channel = static_cast<cricket::VideoChannel*>(
3944 GetVideoTransceiver()->internal()->channel());
3945 if (video_channel) {
3946 return video_channel->media_channel();
3947 } else {
3948 return nullptr;
3949 }
3950}
3951
Steve Anton4171afb2017-11-20 10:20:22 -08003952void PeerConnection::CreateAudioReceiver(
3953 MediaStreamInterface* stream,
3954 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003955 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3956 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003957 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3958 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003959 auto* audio_receiver = new AudioRtpReceiver(
3960 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003961 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003962 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3963 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3964 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003965 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003966 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003967 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970void PeerConnection::CreateVideoReceiver(
3971 MediaStreamInterface* stream,
3972 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003973 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3974 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003975 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3976 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003977 auto* video_receiver = new VideoRtpReceiver(
3978 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003979 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003980 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3981 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3982 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003983 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003984 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003985 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003986}
3987
deadbeef70ab1a12015-09-28 16:53:55 -07003988// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3989// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003990rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003991 const RtpSenderInfo& remote_sender_info) {
3992 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3993 if (!receiver) {
3994 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3995 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003996 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003997 }
Steve Anton4171afb2017-11-20 10:20:22 -08003998 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3999 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4000 } else {
4001 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4002 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004003 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004004}
4005
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004006void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4007 MediaStreamInterface* stream) {
4008 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004009 RTC_DCHECK(track);
4010 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004011 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004012 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004013 // We already have a sender for this track, so just change the stream_id
4014 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004015 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004016 return;
4017 }
4018
4019 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004020 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004021 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004022 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004023 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004024 // If the sender has already been configured in SDP, we call SetSsrc,
4025 // which will connect the sender to the underlying transport. This can
4026 // occur if a local session description that contains the ID of the sender
4027 // is set before AddStream is called. It can also occur if the local
4028 // session description is not changed and RemoveStream is called, and
4029 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004030 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004031 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004032 if (sender_info) {
4033 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 }
4035}
4036
4037// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4038// indefinitely, when we have unified plan SDP.
4039void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4040 MediaStreamInterface* stream) {
4041 RTC_DCHECK(!IsClosed());
4042 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004043 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004044 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4045 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004046 return;
4047 }
Steve Anton4171afb2017-11-20 10:20:22 -08004048 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004049}
4050
4051void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4052 MediaStreamInterface* stream) {
4053 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004054 RTC_DCHECK(track);
4055 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004056 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004057 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004058 // We already have a sender for this track, so just change the stream_id
4059 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004060 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004061 return;
4062 }
4063
4064 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004065 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004066 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004067 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004068 GetVideoTransceiver()->internal()->AddSender(new_sender);
4069 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004070 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004071 if (sender_info) {
4072 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004073 }
4074}
4075
4076void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4077 MediaStreamInterface* stream) {
4078 RTC_DCHECK(!IsClosed());
4079 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004080 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004081 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4082 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004083 return;
4084 }
Steve Anton4171afb2017-11-20 10:20:22 -08004085 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004086}
4087
Steve Antonba818672017-11-06 10:21:57 -08004088void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004089 if (ice_connection_state_ == new_state) {
4090 return;
4091 }
4092
deadbeefcbecd352015-09-23 11:50:27 -07004093 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004094 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004095 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004096 return;
4097 }
Steve Antonba818672017-11-06 10:21:57 -08004098
Mirko Bonadei675513b2017-11-09 11:09:25 +01004099 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4100 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004101 RTC_DCHECK(ice_connection_state_ !=
4102 PeerConnectionInterface::kIceConnectionClosed);
4103
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004104 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004105 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004106}
4107
Alex Loiko9289eda2018-11-23 16:18:59 +00004108void PeerConnection::SetStandardizedIceConnectionState(
4109 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004110 if (standardized_ice_connection_state_ == new_state)
4111 return;
4112 if (IsClosed())
4113 return;
4114 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004115 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004116}
4117
Jonas Olsson635474e2018-10-18 15:58:17 +02004118void PeerConnection::SetConnectionState(
4119 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004120 if (connection_state_ == new_state)
4121 return;
4122 if (IsClosed())
4123 return;
4124 connection_state_ = new_state;
4125 Observer()->OnConnectionChange(new_state);
4126}
4127
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004128void PeerConnection::OnIceGatheringChange(
4129 PeerConnectionInterface::IceGatheringState new_state) {
4130 if (IsClosed()) {
4131 return;
4132 }
4133 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004134 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004135}
4136
jbauch81bf7b02017-03-25 08:31:12 -07004137void PeerConnection::OnIceCandidate(
4138 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004139 if (IsClosed()) {
4140 return;
4141 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004142 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004143 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4144 candidate->candidate().address().IsPrivateIP()) {
4145 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4146 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004147 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004148}
4149
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004150void PeerConnection::OnIceCandidatesRemoved(
4151 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004152 if (IsClosed()) {
4153 return;
4154 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004155 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004156}
4157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004158void PeerConnection::ChangeSignalingState(
4159 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004160 if (signaling_state_ == signaling_state) {
4161 return;
4162 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004163 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4164 << GetSignalingStateString(signaling_state_)
4165 << " New state: "
4166 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004167 signaling_state_ = signaling_state;
4168 if (signaling_state == kClosed) {
4169 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004170 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004171 standardized_ice_connection_state_ =
4172 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004173 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4174 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004175 if (ice_gathering_state_ != kIceGatheringComplete) {
4176 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004177 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004178 }
4179 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004180 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004181}
4182
deadbeefeb459812015-12-15 19:24:43 -08004183void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4184 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004185 if (IsClosed()) {
4186 return;
4187 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004188 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004189 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004190}
4191
deadbeefeb459812015-12-15 19:24:43 -08004192void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4193 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004194 if (IsClosed()) {
4195 return;
4196 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004197 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004198 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004199}
4200
4201void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4202 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004203 if (IsClosed()) {
4204 return;
4205 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004206 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004207 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004208}
4209
4210void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4211 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004212 if (IsClosed()) {
4213 return;
4214 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004215 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004216 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004217}
4218
Henrik Boström31638672017-11-23 17:48:32 +01004219void PeerConnection::PostSetSessionDescriptionSuccess(
4220 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004221 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4222 signaling_thread()->Post(RTC_FROM_HERE, this,
4223 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004224}
4225
deadbeefab9b2d12015-10-14 11:33:11 -07004226void PeerConnection::PostSetSessionDescriptionFailure(
4227 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004228 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004229 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004230 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4231 msg->error = std::move(error);
4232 signaling_thread()->Post(RTC_FROM_HERE, this,
4233 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004234}
4235
4236void PeerConnection::PostCreateSessionDescriptionFailure(
4237 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004238 RTCError error) {
4239 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004240 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4241 msg->error = std::move(error);
4242 signaling_thread()->Post(RTC_FROM_HERE, this,
4243 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004244}
4245
zhihuang1c378ed2017-08-17 14:10:50 -07004246void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004247 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004248 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004249 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004250
Steve Antondcc3c022017-12-22 16:02:54 -08004251 if (IsUnifiedPlan()) {
4252 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4253 } else {
4254 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4255 }
4256
Steve Antonfa2260d2017-12-28 16:38:23 -08004257 // Intentionally unset the data channel type for RTP data channel with the
4258 // second condition. Otherwise the RTP data channels would be successfully
4259 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4260 // when building with chromium. We want to leave RTP data channels broken, so
4261 // people won't try to use them.
4262 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4263 session_options->data_channel_type = data_channel_type();
4264 }
4265
Steve Antondcc3c022017-12-22 16:02:54 -08004266 // Apply ICE restart flag and renomination flag.
4267 for (auto& options : session_options->media_description_options) {
4268 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4269 options.transport_options.enable_ice_renomination =
4270 configuration_.enable_ice_renomination;
4271 }
4272
4273 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004274 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004275 session_options->pooled_ice_credentials =
4276 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4277 RTC_FROM_HERE,
4278 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4279 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004280 session_options->offer_extmap_allow_mixed =
4281 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004282
4283 if (configuration_.enable_dtls_srtp &&
4284 !configuration_.enable_dtls_srtp.value()) {
4285 session_options->media_transport_settings =
4286 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4287 }
Steve Antondcc3c022017-12-22 16:02:54 -08004288}
4289
4290void PeerConnection::GetOptionsForPlanBOffer(
4291 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4292 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004293 // Figure out transceiver directional preferences.
4294 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4295 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4296
4297 // By default, generate sendrecv/recvonly m= sections.
4298 bool recv_audio = true;
4299 bool recv_video = true;
4300
4301 // By default, only offer a new m= section if we have media to send with it.
4302 bool offer_new_audio_description = send_audio;
4303 bool offer_new_video_description = send_video;
4304 bool offer_new_data_description = HasDataChannels();
4305
4306 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004307 if (offer_answer_options.offer_to_receive_audio !=
4308 RTCOfferAnswerOptions::kUndefined) {
4309 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004310 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004311 offer_new_audio_description ||
4312 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004313 }
Steve Antondcc3c022017-12-22 16:02:54 -08004314 if (offer_answer_options.offer_to_receive_video !=
4315 RTCOfferAnswerOptions::kUndefined) {
4316 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004317 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004318 offer_new_video_description ||
4319 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004320 }
4321
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004322 absl::optional<size_t> audio_index;
4323 absl::optional<size_t> video_index;
4324 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004325 // If a current description exists, generate m= sections in the same order,
4326 // using the first audio/video/data section that appears and rejecting
4327 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004328 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004329 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004330 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004331 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4332 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4333 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004334 }
4335
zhihuang1c378ed2017-08-17 14:10:50 -07004336 // Add audio/video/data m= sections to the end if needed.
4337 if (!audio_index && offer_new_audio_description) {
4338 session_options->media_description_options.push_back(
4339 cricket::MediaDescriptionOptions(
4340 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004341 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4342 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004343 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004344 }
zhihuang1c378ed2017-08-17 14:10:50 -07004345 if (!video_index && offer_new_video_description) {
4346 session_options->media_description_options.push_back(
4347 cricket::MediaDescriptionOptions(
4348 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004349 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4350 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004351 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004352 }
zhihuang1c378ed2017-08-17 14:10:50 -07004353 if (!data_index && offer_new_data_description) {
4354 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004355 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004356 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004357 }
4358
4359 cricket::MediaDescriptionOptions* audio_media_description_options =
4360 !audio_index ? nullptr
4361 : &session_options->media_description_options[*audio_index];
4362 cricket::MediaDescriptionOptions* video_media_description_options =
4363 !video_index ? nullptr
4364 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004365
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004366 AddPlanBRtpSenderOptions(GetSendersInternal(),
4367 audio_media_description_options,
4368 video_media_description_options,
4369 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004370}
4371
Steve Antondcc3c022017-12-22 16:02:54 -08004372static cricket::MediaDescriptionOptions
4373GetMediaDescriptionOptionsForTransceiver(
4374 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4375 transceiver,
4376 const std::string& mid) {
4377 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004378 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004379 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004380 // This behavior is specified in JSEP. The gist is that:
4381 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4382 // sendrecv.
4383 // 2. If the MSID is included, then it must be included in any subsequent
4384 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004385 if (transceiver->stopped() ||
4386 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4387 !transceiver->internal()->has_ever_been_used_to_send())) {
4388 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004389 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004390
4391 cricket::SenderOptions sender_options;
4392 sender_options.track_id = transceiver->sender()->id();
4393 sender_options.stream_ids = transceiver->sender()->stream_ids();
4394
4395 // The following sets up RIDs and Simulcast.
4396 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004397 RtpParameters send_parameters =
4398 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004399 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4400 send_parameters.encodings.end(),
4401 [](const RtpEncodingParameters& encoding) {
4402 return !encoding.rid.empty();
4403 });
4404
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004405 std::vector<RidDescription> send_rids;
4406 SimulcastLayerList send_layers;
4407 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4408 if (encoding.rid.empty()) {
4409 continue;
4410 }
4411 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4412 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4413 }
4414
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004415 if (has_rids) {
4416 sender_options.rids = send_rids;
4417 }
4418
4419 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004420 // When RIDs are configured, we must set num_sim_layers to 0 to.
4421 // Otherwise, num_sim_layers must be 1 because either there is no
4422 // simulcast, or simulcast is acheived by munging the SDP.
4423 sender_options.num_sim_layers = has_rids ? 0 : 1;
4424 media_description_options.sender_options.push_back(sender_options);
4425
Steve Antondcc3c022017-12-22 16:02:54 -08004426 return media_description_options;
4427}
4428
Steve Anton5c72e712018-12-10 14:25:30 -08004429// Returns the ContentInfo at mline index |i|, or null if none exists.
4430static const ContentInfo* GetContentByIndex(
4431 const SessionDescriptionInterface* sdesc,
4432 size_t i) {
4433 if (!sdesc) {
4434 return nullptr;
4435 }
4436 const ContentInfos& contents = sdesc->description()->contents();
4437 return (i < contents.size() ? &contents[i] : nullptr);
4438}
4439
Steve Antondcc3c022017-12-22 16:02:54 -08004440void PeerConnection::GetOptionsForUnifiedPlanOffer(
4441 const RTCOfferAnswerOptions& offer_answer_options,
4442 cricket::MediaSessionOptions* session_options) {
4443 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4444 // Offers) and 5.2.2 (Subsequent Offers).
4445 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4446 const ContentInfos& local_contents =
4447 (local_description() ? local_description()->description()->contents()
4448 : ContentInfos());
4449 const ContentInfos& remote_contents =
4450 (remote_description() ? remote_description()->description()->contents()
4451 : ContentInfos());
4452 // The mline indices that can be recycled. New transceivers should reuse these
4453 // slots first.
4454 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004455 // First, go through each media section that exists in either the local or
4456 // remote description and generate a media section in this offer for the
4457 // associated transceiver. If a media section can be recycled, generate a
4458 // default, rejected media section here that can be later overwritten.
4459 for (size_t i = 0;
4460 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4461 // Either |local_content| or |remote_content| is non-null.
4462 const ContentInfo* local_content =
4463 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004464 const ContentInfo* current_local_content =
4465 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004466 const ContentInfo* remote_content =
4467 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004468 const ContentInfo* current_remote_content =
4469 GetContentByIndex(current_remote_description(), i);
4470 bool had_been_rejected =
4471 (current_local_content && current_local_content->rejected) ||
4472 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004473 const std::string& mid =
4474 (local_content ? local_content->name : remote_content->name);
4475 cricket::MediaType media_type =
4476 (local_content ? local_content->media_description()->type()
4477 : remote_content->media_description()->type());
4478 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4479 media_type == cricket::MEDIA_TYPE_VIDEO) {
4480 auto transceiver = GetAssociatedTransceiver(mid);
4481 RTC_CHECK(transceiver);
4482 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004483 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004484 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004485 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004486 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4487 RtpTransceiverDirection::kInactive,
4488 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004489 recycleable_mline_indices.push(i);
4490 } else {
4491 session_options->media_description_options.push_back(
4492 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4493 // CreateOffer shouldn't really cause any state changes in
4494 // PeerConnection, but we need a way to match new transceivers to new
4495 // media sections in SetLocalDescription and JSEP specifies this is done
4496 // by recording the index of the media section generated for the
4497 // transceiver in the offer.
4498 transceiver->internal()->set_mline_index(i);
4499 }
4500 } else {
4501 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004502 RTC_CHECK(GetDataMid());
4503 if (had_been_rejected || mid != *GetDataMid()) {
4504 session_options->media_description_options.push_back(
4505 GetMediaDescriptionOptionsForRejectedData(mid));
4506 } else {
4507 session_options->media_description_options.push_back(
4508 GetMediaDescriptionOptionsForActiveData(mid));
4509 }
Steve Antondcc3c022017-12-22 16:02:54 -08004510 }
4511 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004512
Steve Antondcc3c022017-12-22 16:02:54 -08004513 // Next, look for transceivers that are newly added (that is, are not stopped
4514 // and not associated). Reuse media sections marked as recyclable first,
4515 // otherwise append to the end of the offer. New media sections should be
4516 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004517 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004518 if (transceiver->mid() || transceiver->stopped()) {
4519 continue;
4520 }
4521 size_t mline_index;
4522 if (!recycleable_mline_indices.empty()) {
4523 mline_index = recycleable_mline_indices.front();
4524 recycleable_mline_indices.pop();
4525 session_options->media_description_options[mline_index] =
4526 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004527 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004528 } else {
4529 mline_index = session_options->media_description_options.size();
4530 session_options->media_description_options.push_back(
4531 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004532 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004533 }
4534 // See comment above for why CreateOffer changes the transceiver's state.
4535 transceiver->internal()->set_mline_index(mline_index);
4536 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004537 // Lastly, add a m-section if we have local data channels and an m section
4538 // does not already exist.
4539 if (!GetDataMid() && HasDataChannels()) {
4540 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004541 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004542 }
Steve Antondcc3c022017-12-22 16:02:54 -08004543}
4544
4545void PeerConnection::GetOptionsForAnswer(
4546 const RTCOfferAnswerOptions& offer_answer_options,
4547 cricket::MediaSessionOptions* session_options) {
4548 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4549
4550 if (IsUnifiedPlan()) {
4551 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4552 } else {
4553 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4554 }
4555
Steve Antonfa2260d2017-12-28 16:38:23 -08004556 // Intentionally unset the data channel type for RTP data channel. Otherwise
4557 // the RTP data channels would be successfully negotiated by default and the
4558 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4559 // We want to leave RTP data channels broken, so people won't try to use them.
4560 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4561 session_options->data_channel_type = data_channel_type();
4562 }
4563
Steve Antondcc3c022017-12-22 16:02:54 -08004564 // Apply ICE renomination flag.
4565 for (auto& options : session_options->media_description_options) {
4566 options.transport_options.enable_ice_renomination =
4567 configuration_.enable_ice_renomination;
4568 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004569
4570 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004571 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004572 session_options->pooled_ice_credentials =
4573 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4574 RTC_FROM_HERE,
4575 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4576 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004577}
4578
Steve Antondcc3c022017-12-22 16:02:54 -08004579void PeerConnection::GetOptionsForPlanBAnswer(
4580 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004581 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004582 // Figure out transceiver directional preferences.
4583 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4584 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4585
4586 // By default, generate sendrecv/recvonly m= sections. The direction is also
4587 // restricted by the direction in the offer.
4588 bool recv_audio = true;
4589 bool recv_video = true;
4590
4591 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004592 if (offer_answer_options.offer_to_receive_audio !=
4593 RTCOfferAnswerOptions::kUndefined) {
4594 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004595 }
Steve Antondcc3c022017-12-22 16:02:54 -08004596 if (offer_answer_options.offer_to_receive_video !=
4597 RTCOfferAnswerOptions::kUndefined) {
4598 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004599 }
4600
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004601 absl::optional<size_t> audio_index;
4602 absl::optional<size_t> video_index;
4603 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004604
4605 // Generate m= sections that match those in the offer.
4606 // Note that mediasession.cc will handle intersection our preferred
4607 // direction with the offered direction.
4608 GenerateMediaDescriptionOptions(
4609 remote_description(),
4610 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4611 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4612 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004613
4614 cricket::MediaDescriptionOptions* audio_media_description_options =
4615 !audio_index ? nullptr
4616 : &session_options->media_description_options[*audio_index];
4617 cricket::MediaDescriptionOptions* video_media_description_options =
4618 !video_index ? nullptr
4619 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004620
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004621 AddPlanBRtpSenderOptions(GetSendersInternal(),
4622 audio_media_description_options,
4623 video_media_description_options,
4624 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004625}
zhihuangaf388472016-11-02 16:49:48 -07004626
Steve Antondcc3c022017-12-22 16:02:54 -08004627void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4628 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4629 cricket::MediaSessionOptions* session_options) {
4630 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4631 // Answers) and 5.3.2 (Subsequent Answers).
4632 RTC_DCHECK(remote_description());
4633 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4634 for (const ContentInfo& content :
4635 remote_description()->description()->contents()) {
4636 cricket::MediaType media_type = content.media_description()->type();
4637 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4638 media_type == cricket::MEDIA_TYPE_VIDEO) {
4639 auto transceiver = GetAssociatedTransceiver(content.name);
4640 RTC_CHECK(transceiver);
4641 session_options->media_description_options.push_back(
4642 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4643 } else {
4644 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004645 // Reject all data sections if data channels are disabled.
4646 // Reject a data section if it has already been rejected.
4647 // Reject all data sections except for the first one.
4648 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4649 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004650 session_options->media_description_options.push_back(
4651 GetMediaDescriptionOptionsForRejectedData(content.name));
4652 } else {
4653 session_options->media_description_options.push_back(
4654 GetMediaDescriptionOptionsForActiveData(content.name));
4655 }
Steve Antondcc3c022017-12-22 16:02:54 -08004656 }
4657 }
htaa2a49d92016-03-04 02:51:39 -08004658}
4659
zhihuang1c378ed2017-08-17 14:10:50 -07004660void PeerConnection::GenerateMediaDescriptionOptions(
4661 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004662 RtpTransceiverDirection audio_direction,
4663 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004664 absl::optional<size_t>* audio_index,
4665 absl::optional<size_t>* video_index,
4666 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004667 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004668 for (const cricket::ContentInfo& content :
4669 session_desc->description()->contents()) {
4670 if (IsAudioContent(&content)) {
4671 // If we already have an audio m= section, reject this extra one.
4672 if (*audio_index) {
4673 session_options->media_description_options.push_back(
4674 cricket::MediaDescriptionOptions(
4675 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004676 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004677 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004678 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004679 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004680 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4681 content.name, audio_direction,
4682 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004683 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004684 }
4685 } else if (IsVideoContent(&content)) {
4686 // If we already have an video m= section, reject this extra one.
4687 if (*video_index) {
4688 session_options->media_description_options.push_back(
4689 cricket::MediaDescriptionOptions(
4690 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004691 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004692 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004693 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004694 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004695 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4696 content.name, video_direction,
4697 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004698 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004699 }
4700 } else {
4701 RTC_DCHECK(IsDataContent(&content));
4702 // If we already have an data m= section, reject this extra one.
4703 if (*data_index) {
4704 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004705 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004706 } else {
4707 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004708 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004709 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004710 }
4711 }
htaa2a49d92016-03-04 02:51:39 -08004712 }
deadbeefab9b2d12015-10-14 11:33:11 -07004713}
4714
Steve Antonfa2260d2017-12-28 16:38:23 -08004715cricket::MediaDescriptionOptions
4716PeerConnection::GetMediaDescriptionOptionsForActiveData(
4717 const std::string& mid) const {
4718 // Direction for data sections is meaningless, but legacy endpoints might
4719 // expect sendrecv.
4720 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4721 RtpTransceiverDirection::kSendRecv,
4722 /*stopped=*/false);
4723 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4724 return options;
4725}
4726
4727cricket::MediaDescriptionOptions
4728PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4729 const std::string& mid) const {
4730 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4731 RtpTransceiverDirection::kInactive,
4732 /*stopped=*/true);
4733 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4734 return options;
4735}
4736
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004737absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004738 switch (data_channel_type_) {
4739 case cricket::DCT_RTP:
4740 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004741 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004742 }
4743 return rtp_data_channel_->content_name();
4744 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004745 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004746 case cricket::DCT_MEDIA_TRANSPORT:
4747 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004748 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004749 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004750 }
4751}
4752
Steve Anton4171afb2017-11-20 10:20:22 -08004753void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4754 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4755 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004756 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004757}
4758
Steve Anton4171afb2017-11-20 10:20:22 -08004759void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004760 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004761 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004762 cricket::MediaType media_type,
4763 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004764 RTC_DCHECK(!IsUnifiedPlan());
4765
Steve Anton4171afb2017-11-20 10:20:22 -08004766 std::vector<RtpSenderInfo>* current_senders =
4767 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004768
Steve Anton4171afb2017-11-20 10:20:22 -08004769 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004770 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004771 for (auto sender_it = current_senders->begin();
4772 sender_it != current_senders->end();
4773 /* incremented manually */) {
4774 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004775 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004776 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004777 std::string params_stream_id;
4778 if (params) {
4779 params_stream_id =
4780 (!params->first_stream_id().empty() ? params->first_stream_id()
4781 : kDefaultStreamId);
4782 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004783 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004784 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004785 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004786 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004787 sender_exists) {
4788 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004789 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004790 OnRemoteSenderRemoved(info, media_type);
4791 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004792 }
4793 }
4794
Steve Anton4171afb2017-11-20 10:20:22 -08004795 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004796 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004797 if (!params.has_ssrcs()) {
4798 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4799 // sender, this means it is coming from a Unified Plan endpoint,so we just
4800 // create a default.
4801 default_sender_needed = true;
4802 break;
4803 }
4804
Seth Hampson845e8782018-03-02 11:34:10 -08004805 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004806 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004807 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4808 // not supported in Plan B, we just take the first here and create the
4809 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004810 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004811 (!params.first_stream_id().empty() ? params.first_stream_id()
4812 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004813 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004814 uint32_t ssrc = params.first_ssrc();
4815
4816 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004817 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004818 if (!stream) {
4819 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004820 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004821 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004822 remote_streams_->AddStream(stream);
4823 new_streams->AddStream(stream);
4824 }
4825
Steve Anton4171afb2017-11-20 10:20:22 -08004826 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004827 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004828 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004829 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004830 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004831 }
4832 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004833
Steve Anton4171afb2017-11-20 10:20:22 -08004834 // Add default sender if necessary.
4835 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004836 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004837 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004838 if (!default_stream) {
4839 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004840 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004841 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004842 remote_streams_->AddStream(default_stream);
4843 new_streams->AddStream(default_stream);
4844 }
Steve Anton4171afb2017-11-20 10:20:22 -08004845 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4846 ? kDefaultAudioSenderId
4847 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004848 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004849 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004850 if (!default_sender_info) {
4851 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004852 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004853 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004854 }
4855 }
deadbeefab9b2d12015-10-14 11:33:11 -07004856}
4857
Steve Anton4171afb2017-11-20 10:20:22 -08004858void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4859 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004860 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4861 << " receiver for track_id=" << sender_info.sender_id
4862 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004863
Steve Anton3d954a62018-04-02 11:27:23 -07004864 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004865 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004866 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004867 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004868 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004869 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004870 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004871 }
4872}
4873
Steve Anton4171afb2017-11-20 10:20:22 -08004874void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4875 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004876 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4877 << " receiver for track_id=" << sender_info.sender_id
4878 << " and stream_id=" << sender_info.stream_id;
4879
Seth Hampson845e8782018-03-02 11:34:10 -08004880 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004881
Henrik Boström933d8b02017-10-10 10:05:16 -07004882 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004883 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004884 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4885 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004886 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004887 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004888 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004889 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004890 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004891 }
4892 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004893 // Stopping or destroying a VideoRtpReceiver will end the
4894 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004895 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004896 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004897 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004898 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004899 // There's no guarantee the track is still available, e.g. the track may
4900 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004901 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004902 }
4903 } else {
nisseede5da42017-01-12 05:15:36 -08004904 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004905 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004906 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004907 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004908 }
deadbeefab9b2d12015-10-14 11:33:11 -07004909}
4910
4911void PeerConnection::UpdateEndedRemoteMediaStreams() {
4912 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4913 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4914 MediaStreamInterface* stream = remote_streams_->at(i);
4915 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4916 streams_to_remove.push_back(stream);
4917 }
4918 }
4919
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004920 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004921 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004922 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004923 }
4924}
4925
Steve Anton4171afb2017-11-20 10:20:22 -08004926void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004927 const std::vector<cricket::StreamParams>& streams,
4928 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004929 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004930
Seth Hampson845e8782018-03-02 11:34:10 -08004931 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004932 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004933 for (auto sender_it = current_senders->begin();
4934 sender_it != current_senders->end();
4935 /* incremented manually */) {
4936 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004937 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004938 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4939 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004940 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004941 OnLocalSenderRemoved(info, media_type);
4942 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004943 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004944 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004945 }
4946 }
4947
Steve Anton4171afb2017-11-20 10:20:22 -08004948 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004949 for (const cricket::StreamParams& params : streams) {
4950 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004951 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004952 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004953 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004954 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004955 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004956 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004957 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004958 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004959 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004960 }
4961 }
4962}
4963
Steve Anton4171afb2017-11-20 10:20:22 -08004964void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4965 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004966 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004967 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004968 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004969 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4970 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004971 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004972 return;
4973 }
4974
deadbeeffac06552015-11-25 11:26:01 -08004975 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004976 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004977 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004978 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004979 }
deadbeeffac06552015-11-25 11:26:01 -08004980
Seth Hampson5b4f0752018-04-02 16:31:36 -07004981 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004982 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004983}
4984
Steve Anton4171afb2017-11-20 10:20:22 -08004985void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4986 cricket::MediaType media_type) {
4987 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004988 if (!sender) {
4989 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004990 // SessionDescriptions has been renegotiated.
4991 return;
4992 }
deadbeeffac06552015-11-25 11:26:01 -08004993
4994 // A sender has been removed from the SessionDescription but it's still
4995 // associated with the PeerConnection. This only occurs if the SDP doesn't
4996 // match with the calls to CreateSender, AddStream and RemoveStream.
4997 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004998 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004999 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005000 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005001 }
deadbeeffac06552015-11-25 11:26:01 -08005002
Steve Anton4171afb2017-11-20 10:20:22 -08005003 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005004}
5005
5006void PeerConnection::UpdateLocalRtpDataChannels(
5007 const cricket::StreamParamsVec& streams) {
5008 std::vector<std::string> existing_channels;
5009
5010 // Find new and active data channels.
5011 for (const cricket::StreamParams& params : streams) {
5012 // |it->sync_label| is actually the data channel label. The reason is that
5013 // we use the same naming of data channels as we do for
5014 // MediaStreams and Tracks.
5015 // For MediaStreams, the sync_label is the MediaStream label and the
5016 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005017 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005018 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005019 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005020 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005021 continue;
5022 }
5023 // Set the SSRC the data channel should use for sending.
5024 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5025 existing_channels.push_back(data_channel_it->first);
5026 }
5027
5028 UpdateClosingRtpDataChannels(existing_channels, true);
5029}
5030
5031void PeerConnection::UpdateRemoteRtpDataChannels(
5032 const cricket::StreamParamsVec& streams) {
5033 std::vector<std::string> existing_channels;
5034
5035 // Find new and active data channels.
5036 for (const cricket::StreamParams& params : streams) {
5037 // The data channel label is either the mslabel or the SSRC if the mslabel
5038 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005039 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005040 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005041 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005042 auto data_channel_it = rtp_data_channels_.find(label);
5043 if (data_channel_it == rtp_data_channels_.end()) {
5044 // This is a new data channel.
5045 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5046 } else {
5047 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5048 }
5049 existing_channels.push_back(label);
5050 }
5051
5052 UpdateClosingRtpDataChannels(existing_channels, false);
5053}
5054
5055void PeerConnection::UpdateClosingRtpDataChannels(
5056 const std::vector<std::string>& active_channels,
5057 bool is_local_update) {
5058 auto it = rtp_data_channels_.begin();
5059 while (it != rtp_data_channels_.end()) {
5060 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005061 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005062 ++it;
5063 continue;
5064 }
5065
5066 if (is_local_update) {
5067 data_channel->SetSendSsrc(0);
5068 } else {
5069 data_channel->RemotePeerRequestClose();
5070 }
5071
5072 if (data_channel->state() == DataChannel::kClosed) {
5073 rtp_data_channels_.erase(it);
5074 it = rtp_data_channels_.begin();
5075 } else {
5076 ++it;
5077 }
5078 }
5079}
5080
5081void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5082 uint32_t remote_ssrc) {
5083 rtc::scoped_refptr<DataChannel> channel(
5084 InternalCreateDataChannel(label, nullptr));
5085 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005086 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005087 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005088 return;
5089 }
5090 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005091 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5092 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005093 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005094}
5095
5096rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5097 const std::string& label,
5098 const InternalDataChannelInit* config) {
5099 if (IsClosed()) {
5100 return nullptr;
5101 }
Steve Anton75737c02017-11-06 10:37:17 -08005102 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005103 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005104 << "InternalCreateDataChannel: Data is not supported in this call.";
5105 return nullptr;
5106 }
5107 InternalDataChannelInit new_config =
5108 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005109 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005110 if (new_config.id < 0) {
5111 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005112 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005113 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005114 RTC_LOG(LS_ERROR)
5115 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005116 return nullptr;
5117 }
5118 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005119 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005120 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005121 return nullptr;
5122 }
5123 }
5124
Steve Anton75737c02017-11-06 10:37:17 -08005125 rtc::scoped_refptr<DataChannel> channel(
5126 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005127 if (!channel) {
5128 sid_allocator_.ReleaseSid(new_config.id);
5129 return nullptr;
5130 }
5131
5132 if (channel->data_channel_type() == cricket::DCT_RTP) {
5133 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005134 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5135 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005136 return nullptr;
5137 }
5138 rtp_data_channels_[channel->label()] = channel;
5139 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005140 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005141 sctp_data_channels_.push_back(channel);
5142 channel->SignalClosed.connect(this,
5143 &PeerConnection::OnSctpDataChannelClosed);
5144 }
5145
Steve Anton2d8609c2018-01-23 16:38:46 -08005146 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005147 return channel;
5148}
5149
5150bool PeerConnection::HasDataChannels() const {
5151 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5152}
5153
5154void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005155 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005156 for (const auto& channel : sctp_data_channels_) {
5157 if (channel->id() < 0) {
5158 int sid;
5159 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005160 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5161 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005162 continue;
5163 }
5164 channel->SetSctpSid(sid);
5165 }
5166 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005167 // Since closing modifies the list of channels, we have to do the actual
5168 // closing outside the loop.
5169 for (const auto& channel : channels_to_close) {
5170 channel->CloseAbruptly();
5171 }
deadbeefab9b2d12015-10-14 11:33:11 -07005172}
5173
5174void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005175 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005176 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5177 ++it) {
5178 if (it->get() == channel) {
5179 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005180 // After the closing procedure is done, it's safe to use this ID for
5181 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005182 sid_allocator_.ReleaseSid(channel->id());
5183 }
deadbeefbd292462015-12-14 18:15:29 -08005184 // Since this method is triggered by a signal from the DataChannel,
5185 // we can't free it directly here; we need to free it asynchronously.
5186 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005187 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005188 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5189 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005190 return;
5191 }
5192 }
5193}
5194
deadbeefab9b2d12015-10-14 11:33:11 -07005195void PeerConnection::OnDataChannelDestroyed() {
5196 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5197 // DataChannel may callback to us and try to modify the list.
5198 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5199 temp_rtp_dcs.swap(rtp_data_channels_);
5200 for (const auto& kv : temp_rtp_dcs) {
5201 kv.second->OnTransportChannelDestroyed();
5202 }
5203
5204 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5205 temp_sctp_dcs.swap(sctp_data_channels_);
5206 for (const auto& channel : temp_sctp_dcs) {
5207 channel->OnTransportChannelDestroyed();
5208 }
5209}
5210
5211void PeerConnection::OnDataChannelOpenMessage(
5212 const std::string& label,
5213 const InternalDataChannelInit& config) {
5214 rtc::scoped_refptr<DataChannel> channel(
5215 InternalCreateDataChannel(label, &config));
5216 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005217 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005218 return;
5219 }
5220
deadbeefa601f5c2016-06-06 14:27:39 -07005221 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5222 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005223 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005224 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005225}
5226
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005227bool PeerConnection::HandleOpenMessage_s(
5228 const cricket::ReceiveDataParams& params,
5229 const rtc::CopyOnWriteBuffer& buffer) {
5230 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5231 // Received OPEN message; parse and signal that a new data channel should
5232 // be created.
5233 std::string label;
5234 InternalDataChannelInit config;
5235 config.id = params.ssrc;
5236 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5237 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5238 << params.ssrc;
5239 return true;
5240 }
5241 config.open_handshake_role = InternalDataChannelInit::kAcker;
5242 OnDataChannelOpenMessage(label, config);
5243 return true;
5244 }
5245 return false;
5246}
5247
Steve Anton4171afb2017-11-20 10:20:22 -08005248rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5249PeerConnection::GetAudioTransceiver() const {
5250 // This method only works with Plan B SDP, where there is a single
5251 // audio/video transceiver.
5252 RTC_DCHECK(!IsUnifiedPlan());
5253 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005254 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005255 return transceiver;
5256 }
5257 }
5258 RTC_NOTREACHED();
5259 return nullptr;
5260}
5261
5262rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5263PeerConnection::GetVideoTransceiver() const {
5264 // This method only works with Plan B SDP, where there is a single
5265 // audio/video transceiver.
5266 RTC_DCHECK(!IsUnifiedPlan());
5267 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005268 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005269 return transceiver;
5270 }
5271 }
5272 RTC_NOTREACHED();
5273 return nullptr;
5274}
5275
5276// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5277// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005278bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005279 switch (type) {
5280 case cricket::MEDIA_TYPE_AUDIO:
5281 return !GetAudioTransceiver()->internal()->senders().empty();
5282 case cricket::MEDIA_TYPE_VIDEO:
5283 return !GetVideoTransceiver()->internal()->senders().empty();
5284 case cricket::MEDIA_TYPE_DATA:
5285 return false;
5286 }
5287 RTC_NOTREACHED();
5288 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005289}
5290
Steve Anton4171afb2017-11-20 10:20:22 -08005291rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5292PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005293 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005294 for (auto sender : transceiver->internal()->senders()) {
5295 if (sender->track() == track) {
5296 return sender;
5297 }
5298 }
5299 }
5300 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005301}
5302
Steve Anton4171afb2017-11-20 10:20:22 -08005303rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5304PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005305 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005306 for (auto sender : transceiver->internal()->senders()) {
5307 if (sender->id() == sender_id) {
5308 return sender;
5309 }
5310 }
5311 }
5312 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005313}
5314
Steve Anton4171afb2017-11-20 10:20:22 -08005315rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5316PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005317 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005318 for (auto receiver : transceiver->internal()->receivers()) {
5319 if (receiver->id() == receiver_id) {
5320 return receiver;
5321 }
5322 }
5323 }
5324 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005325}
5326
Steve Anton4171afb2017-11-20 10:20:22 -08005327std::vector<PeerConnection::RtpSenderInfo>*
5328PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5329 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5330 media_type == cricket::MEDIA_TYPE_VIDEO);
5331 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5332 ? &remote_audio_sender_infos_
5333 : &remote_video_sender_infos_;
5334}
5335
5336std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005337 cricket::MediaType media_type) {
5338 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5339 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005340 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5341 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005342}
5343
Steve Anton4171afb2017-11-20 10:20:22 -08005344const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5345 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005346 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005347 const std::string sender_id) const {
5348 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005349 if (sender_info.stream_id == stream_id &&
5350 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005351 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005352 }
5353 }
5354 return nullptr;
5355}
5356
5357DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5358 for (const auto& channel : sctp_data_channels_) {
5359 if (channel->id() == sid) {
5360 return channel;
5361 }
5362 }
5363 return nullptr;
5364}
5365
Karl Wibergfb3be392019-03-22 14:13:22 +01005366PeerConnection::InitializePortAllocatorResult
5367PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005368 const cricket::ServerAddresses& stun_servers,
5369 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005370 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005371 RTC_DCHECK_RUN_ON(network_thread());
5372
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005373 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005374 // To handle both internal and externally created port allocator, we will
5375 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005376 int port_allocator_flags = port_allocator_->flags();
5377 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5378 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5379 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005380 // If the disable-IPv6 flag was specified, we'll not override it
5381 // by experiment.
5382 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005383 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005384 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5385 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005386 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005387 }
5388
zhihuangb09b3f92017-03-07 14:40:51 -08005389 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005390 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005391 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005392 }
5393
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005394 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005395 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005396 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005397 }
5398
honghaiz60347052016-05-31 18:29:12 -07005399 if (configuration.candidate_network_policy ==
5400 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005401 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005402 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005403 }
5404
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005405 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005406 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005407 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5408 }
5409
Karl Wibergfb3be392019-03-22 14:13:22 +01005410 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005411 // No step delay is used while allocating ports.
5412 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005413 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005414 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005415 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005416
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005417 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005418 for (auto& turn_server : turn_servers_copy) {
5419 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005420 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005421 // Call this last since it may create pooled allocator sessions using the
5422 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005423 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005424 stun_servers, std::move(turn_servers_copy),
5425 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5426 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005427 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005428
5429 InitializePortAllocatorResult res;
5430 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5431 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005432}
5433
deadbeef91dd5672016-05-18 16:55:30 -07005434bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005435 const cricket::ServerAddresses& stun_servers,
5436 const std::vector<cricket::RelayServerConfig>& turn_servers,
5437 IceTransportsType type,
5438 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005439 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005440 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005441 absl::optional<int> stun_candidate_keepalive_interval,
5442 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005443 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005444 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005445 // According to JSEP, after setLocalDescription, changing the candidate pool
5446 // size is not allowed, and changing the set of ICE servers will not result
5447 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005448 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005449 port_allocator_->FreezeCandidatePool();
5450 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005451 // Add the custom tls turn servers if they exist.
5452 auto turn_servers_copy = turn_servers;
5453 for (auto& turn_server : turn_servers_copy) {
5454 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5455 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005456 // Call this last since it may create pooled allocator sessions using the
5457 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005458 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005459 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5460 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005461}
5462
Steve Antonba818672017-11-06 10:21:57 -08005463cricket::ChannelManager* PeerConnection::channel_manager() const {
5464 return factory_->channel_manager();
5465}
5466
Elad Alon99c3fe52017-10-13 16:29:40 +02005467bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005468 std::unique_ptr<RtcEventLogOutput> output,
5469 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005470 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005471 if (!event_log_) {
5472 return false;
5473 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005474 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005475}
5476
5477void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005478 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005479 if (event_log_) {
5480 event_log_->StopLogging();
5481 }
ivoc14d5dbe2016-07-04 07:06:55 -07005482}
nisseeaabdf62017-05-05 02:23:02 -07005483
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005484cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005485 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005486 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005487 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005488 if (channel && channel->content_name() == content_name) {
5489 return channel;
5490 }
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492 if (rtp_data_channel() &&
5493 rtp_data_channel()->content_name() == content_name) {
5494 return rtp_data_channel();
5495 }
5496 return nullptr;
5497}
5498
5499bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005500 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005501 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005502 RTC_LOG(LS_INFO)
5503 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005504 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005505 return false;
5506 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005507 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005508 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005509 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005510 return false;
5511 }
5512
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005513 absl::optional<rtc::SSLRole> dtls_role;
5514 if (sctp_mid_) {
5515 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5516 } else if (is_caller_) {
5517 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5518 }
Zhi Huange830e682018-03-30 10:48:35 -07005519 if (dtls_role) {
5520 *role = *dtls_role;
5521 return true;
5522 }
5523 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005524}
5525
5526bool PeerConnection::GetSslRole(const std::string& content_name,
5527 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005528 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005529 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005530 RTC_LOG(LS_INFO)
5531 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005532 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005533 return false;
5534 }
5535
Zhi Huange830e682018-03-30 10:48:35 -07005536 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5537 if (dtls_role) {
5538 *role = *dtls_role;
5539 return true;
5540 }
5541 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Steve Antonf8470812017-12-04 10:46:21 -08005544void PeerConnection::SetSessionError(SessionError error,
5545 const std::string& error_desc) {
5546 RTC_DCHECK_RUN_ON(signaling_thread());
5547 if (error != session_error_) {
5548 session_error_ = error;
5549 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005550 }
5551}
5552
Zhi Huange830e682018-03-30 10:48:35 -07005553RTCError PeerConnection::UpdateSessionState(
5554 SdpType type,
5555 cricket::ContentSource source,
5556 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005557 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005558
5559 // If there's already a pending error then no state transition should happen.
5560 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005561 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005562
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005563 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005564 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005565 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005566 }
5567
5568 // Update the signaling state according to the specified state machine (see
5569 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005570 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005571 ChangeSignalingState(source == cricket::CS_LOCAL
5572 ? PeerConnectionInterface::kHaveLocalOffer
5573 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005574 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005575 ChangeSignalingState(source == cricket::CS_LOCAL
5576 ? PeerConnectionInterface::kHaveLocalPrAnswer
5577 : PeerConnectionInterface::kHaveRemotePrAnswer);
5578 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005579 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005580 ChangeSignalingState(PeerConnectionInterface::kStable);
5581 }
5582
5583 // Update internal objects according to the session description's media
5584 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005585 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005586 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005587 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005588 }
5589
Steve Anton8a006912017-12-04 15:25:56 -08005590 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005591}
5592
Steve Anton8a006912017-12-04 15:25:56 -08005593RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005594 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005595 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005596 const SessionDescriptionInterface* sdesc =
5597 (source == cricket::CS_LOCAL ? local_description()
5598 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005599 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005600
5601 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005602 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005603 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005604 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005605 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005606 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005607 continue;
5608 }
5609 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005610 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005611 if (!content_desc) {
5612 continue;
5613 }
5614 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005615 bool success = (source == cricket::CS_LOCAL)
5616 ? channel->SetLocalContent(content_desc, type, &error)
5617 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005618 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005619 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005620 }
5621 }
5622
5623 // If using the RtpDataChannel, push down the new SDP section for it too.
5624 if (rtp_data_channel_) {
5625 const ContentInfo* data_content =
5626 cricket::GetFirstDataContent(sdesc->description());
5627 if (data_content && !data_content->rejected) {
5628 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005629 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005630 if (data_desc) {
5631 std::string error;
5632 bool success =
5633 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005634 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005635 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005636 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005637 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005638 }
Steve Anton75737c02017-11-06 10:37:17 -08005639 }
5640 }
5641 }
Steve Antoned10bd92017-12-05 10:52:59 -08005642
Steve Anton75737c02017-11-06 10:37:17 -08005643 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5644 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5645 if (sctp_transport_ && local_description() && remote_description() &&
5646 cricket::GetFirstDataContent(local_description()->description()) &&
5647 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005648 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005649 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005650 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5651 GetSctpPort(local_description()->description()),
5652 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005653 if (!success) {
5654 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5655 "Failed to push down SCTP parameters.");
5656 }
Steve Anton75737c02017-11-06 10:37:17 -08005657 }
Steve Antoned10bd92017-12-05 10:52:59 -08005658
Steve Anton8a006912017-12-04 15:25:56 -08005659 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005660}
5661
Karl Wiberg739506e2019-04-03 11:37:28 +02005662bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5663 int local_sctp_port,
5664 int remote_sctp_port) {
5665 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005666 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5667 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005668 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005669}
5670
Steve Anton8a006912017-12-04 15:25:56 -08005671RTCError PeerConnection::PushdownTransportDescription(
5672 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005673 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005674 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005675
Zhi Huange830e682018-03-30 10:48:35 -07005676 if (source == cricket::CS_LOCAL) {
5677 const SessionDescriptionInterface* sdesc = local_description();
5678 RTC_DCHECK(sdesc);
5679 return transport_controller_->SetLocalDescription(type,
5680 sdesc->description());
5681 } else {
5682 const SessionDescriptionInterface* sdesc = remote_description();
5683 RTC_DCHECK(sdesc);
5684 return transport_controller_->SetRemoteDescription(type,
5685 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005686 }
Steve Anton75737c02017-11-06 10:37:17 -08005687}
5688
5689bool PeerConnection::GetTransportDescription(
5690 const SessionDescription* description,
5691 const std::string& content_name,
5692 cricket::TransportDescription* tdesc) {
5693 if (!description || !tdesc) {
5694 return false;
5695 }
5696 const TransportInfo* transport_info =
5697 description->GetTransportInfoByName(content_name);
5698 if (!transport_info) {
5699 return false;
5700 }
5701 *tdesc = transport_info->description;
5702 return true;
5703}
5704
Steve Anton75737c02017-11-06 10:37:17 -08005705cricket::IceConfig PeerConnection::ParseIceConfig(
5706 const PeerConnectionInterface::RTCConfiguration& config) const {
5707 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005708 switch (config.continual_gathering_policy) {
5709 case PeerConnectionInterface::GATHER_ONCE:
5710 gathering_policy = cricket::GATHER_ONCE;
5711 break;
5712 case PeerConnectionInterface::GATHER_CONTINUALLY:
5713 gathering_policy = cricket::GATHER_CONTINUALLY;
5714 break;
5715 default:
5716 RTC_NOTREACHED();
5717 gathering_policy = cricket::GATHER_ONCE;
5718 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005719
Steve Anton75737c02017-11-06 10:37:17 -08005720 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005721 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5722 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005723 ice_config.prioritize_most_likely_candidate_pairs =
5724 config.prioritize_most_likely_ice_candidate_pairs;
5725 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005726 RTCConfigurationToIceConfigOptionalInt(
5727 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005728 ice_config.continual_gathering_policy = gathering_policy;
5729 ice_config.presume_writable_when_fully_relayed =
5730 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005731 ice_config.ice_check_interval_strong_connectivity =
5732 config.ice_check_interval_strong_connectivity;
5733 ice_config.ice_check_interval_weak_connectivity =
5734 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005735 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005736 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5737 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005738 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005739 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005740 ice_config.regather_all_networks_interval_range =
5741 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005742 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005743 return ice_config;
5744}
5745
Steve Anton75737c02017-11-06 10:37:17 -08005746bool PeerConnection::SendData(const cricket::SendDataParams& params,
5747 const rtc::CopyOnWriteBuffer& payload,
5748 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005749 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005750 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5751 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5752 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005753 return false;
5754 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005755 if (media_transport_) {
5756 SendDataParams send_params;
5757 send_params.type = ToWebrtcDataMessageType(params.type);
5758 send_params.ordered = params.ordered;
5759 if (params.max_rtx_count >= 0) {
5760 send_params.max_rtx_count = params.max_rtx_count;
5761 } else if (params.max_rtx_ms >= 0) {
5762 send_params.max_rtx_ms = params.max_rtx_ms;
5763 }
5764 return media_transport_->SendData(params.sid, send_params, payload).ok();
5765 }
Steve Anton75737c02017-11-06 10:37:17 -08005766 return rtp_data_channel_
5767 ? rtp_data_channel_->SendData(params, payload, result)
5768 : network_thread()->Invoke<bool>(
5769 RTC_FROM_HERE,
5770 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005771 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005772}
5773
5774bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005775 RTC_DCHECK_RUN_ON(signaling_thread());
5776 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005777 // Don't log an error here, because DataChannels are expected to call
5778 // ConnectDataChannel in this state. It's the only way to initially tell
5779 // whether or not the underlying transport is ready.
5780 return false;
5781 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005782 if (media_transport_) {
5783 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5784 &DataChannel::OnChannelReady);
5785 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5786 &DataChannel::OnDataReceived);
5787 SignalMediaTransportChannelClosing_s.connect(
5788 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5789 SignalMediaTransportChannelClosed_s.connect(
5790 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5791 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005792 rtp_data_channel_->SignalReadyToSendData.connect(
5793 webrtc_data_channel, &DataChannel::OnChannelReady);
5794 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5795 &DataChannel::OnDataReceived);
5796 } else {
5797 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5798 &DataChannel::OnChannelReady);
5799 SignalSctpDataReceived.connect(webrtc_data_channel,
5800 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005801 SignalSctpClosingProcedureStartedRemotely.connect(
5802 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5803 SignalSctpClosingProcedureComplete.connect(
5804 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005805 }
5806 return true;
5807}
5808
5809void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005810 RTC_DCHECK_RUN_ON(signaling_thread());
5811 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005812 RTC_LOG(LS_ERROR)
5813 << "DisconnectDataChannel called when rtp_data_channel_ and "
5814 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005815 return;
5816 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005817 if (media_transport_) {
5818 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5819 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5820 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5821 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5822 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005823 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5824 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5825 } else {
5826 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5827 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005828 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5829 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005830 }
5831}
5832
5833void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005834 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005835 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005836 return;
5837 }
Steve Anton75737c02017-11-06 10:37:17 -08005838 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005839 RTC_LOG(LS_ERROR)
5840 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005841 return;
5842 }
5843 network_thread()->Invoke<void>(
5844 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005845 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005846}
5847
5848void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005849 if (media_transport_) {
5850 media_transport_->CloseChannel(sid);
5851 return;
5852 }
Steve Anton75737c02017-11-06 10:37:17 -08005853 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005854 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005855 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005856 return;
5857 }
5858 network_thread()->Invoke<void>(
5859 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005860 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005861}
5862
5863bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005864 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005865 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005866 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005867 sctp_ready_to_send_data_;
5868}
5869
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005870void PeerConnection::OnDataReceived(int channel_id,
5871 DataMessageType type,
5872 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005873 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005874 cricket::ReceiveDataParams params;
5875 params.sid = channel_id;
5876 params.type = ToCricketDataMessageType(type);
5877 media_transport_invoker_->AsyncInvoke<void>(
5878 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5879 RTC_DCHECK_RUN_ON(signaling_thread());
5880 if (!HandleOpenMessage_s(params, buffer)) {
5881 SignalMediaTransportReceivedData_s(params, buffer);
5882 }
5883 });
5884}
5885
5886void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005887 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005888 media_transport_invoker_->AsyncInvoke<void>(
5889 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5890 RTC_DCHECK_RUN_ON(signaling_thread());
5891 SignalMediaTransportChannelClosing_s(channel_id);
5892 });
5893}
5894
5895void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005896 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005897 media_transport_invoker_->AsyncInvoke<void>(
5898 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5899 RTC_DCHECK_RUN_ON(signaling_thread());
5900 SignalMediaTransportChannelClosed_s(channel_id);
5901 });
5902}
5903
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005904absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005905 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005906 if (sctp_mid_ && transport_controller_) {
5907 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5908 if (dtls_transport) {
5909 return dtls_transport->transport_name();
5910 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005911 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005912 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005913 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005914}
5915
Qingsi Wang72a43a12018-02-20 16:03:18 -08005916cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5917 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005918 network_thread()->Invoke<void>(
5919 RTC_FROM_HERE,
5920 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5921 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005922 return candidate_states_list;
5923}
5924
Steve Anton5dfde182018-02-06 10:34:40 -08005925std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5926 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005927 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005928 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005929 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005930 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005931 if (channel) {
5932 transport_names_by_mid[channel->content_name()] =
5933 channel->transport_name();
5934 }
Steve Anton75737c02017-11-06 10:37:17 -08005935 }
Steve Anton5dfde182018-02-06 10:34:40 -08005936 if (rtp_data_channel_) {
5937 transport_names_by_mid[rtp_data_channel_->content_name()] =
5938 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005939 }
5940 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005941 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005942 RTC_DCHECK(transport_name);
5943 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005944 }
Steve Anton5dfde182018-02-06 10:34:40 -08005945 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005946}
5947
Steve Anton5dfde182018-02-06 10:34:40 -08005948std::map<std::string, cricket::TransportStats>
5949PeerConnection::GetTransportStatsByNames(
5950 const std::set<std::string>& transport_names) {
5951 if (!network_thread()->IsCurrent()) {
5952 return network_thread()
5953 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5954 RTC_FROM_HERE,
5955 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005956 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005957 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005958 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5959 for (const std::string& transport_name : transport_names) {
5960 cricket::TransportStats transport_stats;
5961 bool success =
5962 transport_controller_->GetStats(transport_name, &transport_stats);
5963 if (success) {
5964 transport_stats_by_name[transport_name] = std::move(transport_stats);
5965 } else {
5966 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5967 << transport_name;
5968 }
5969 }
5970 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005971}
5972
5973bool PeerConnection::GetLocalCertificate(
5974 const std::string& transport_name,
5975 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005976 if (!certificate) {
5977 return false;
5978 }
5979 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5980 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005981}
5982
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005983std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005984 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005985 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005986}
5987
5988cricket::DataChannelType PeerConnection::data_channel_type() const {
5989 return data_channel_type_;
5990}
5991
5992bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02005993 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005994 return pending_ice_restarts_.find(content_name) !=
5995 pending_ice_restarts_.end();
5996}
5997
Steve Anton75737c02017-11-06 10:37:17 -08005998bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5999 return transport_controller_->NeedsIceRestart(content_name);
6000}
6001
6002void PeerConnection::OnCertificateReady(
6003 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6004 transport_controller_->SetLocalCertificate(certificate);
6005}
6006
6007void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006008 SetSessionError(SessionError::kTransport,
6009 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006010}
6011
Alex Loiko9289eda2018-11-23 16:18:59 +00006012void PeerConnection::OnTransportControllerConnectionState(
6013 cricket::IceConnectionState state) {
6014 switch (state) {
6015 case cricket::kIceConnectionConnecting:
6016 // If the current state is Connected or Completed, then there were
6017 // writable channels but now there are not, so the next state must
6018 // be Disconnected.
6019 // kIceConnectionConnecting is currently used as the default,
6020 // un-connected state by the TransportController, so its only use is
6021 // detecting disconnections.
6022 if (ice_connection_state_ ==
6023 PeerConnectionInterface::kIceConnectionConnected ||
6024 ice_connection_state_ ==
6025 PeerConnectionInterface::kIceConnectionCompleted) {
6026 SetIceConnectionState(
6027 PeerConnectionInterface::kIceConnectionDisconnected);
6028 }
6029 break;
6030 case cricket::kIceConnectionFailed:
6031 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6032 break;
6033 case cricket::kIceConnectionConnected:
6034 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6035 "all transports are writable.";
6036 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6037 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6038 break;
6039 case cricket::kIceConnectionCompleted:
6040 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6041 "all transports are complete.";
6042 if (ice_connection_state_ !=
6043 PeerConnectionInterface::kIceConnectionConnected) {
6044 // If jumping directly from "checking" to "connected",
6045 // signal "connected" first.
6046 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6047 }
6048 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6049 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6050 ReportTransportStats();
6051 break;
6052 default:
6053 RTC_NOTREACHED();
6054 }
6055}
6056
Steve Anton75737c02017-11-06 10:37:17 -08006057void PeerConnection::OnTransportControllerCandidatesGathered(
6058 const std::string& transport_name,
6059 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006060 int sdp_mline_index;
6061 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006062 RTC_LOG(LS_ERROR)
6063 << "OnTransportControllerCandidatesGathered: content name "
6064 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006065 return;
6066 }
6067
6068 for (cricket::Candidates::const_iterator citer = candidates.begin();
6069 citer != candidates.end(); ++citer) {
6070 // Use transport_name as the candidate media id.
6071 std::unique_ptr<JsepIceCandidate> candidate(
6072 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6073 if (local_description()) {
6074 mutable_local_description()->AddCandidate(candidate.get());
6075 }
6076 OnIceCandidate(std::move(candidate));
6077 }
6078}
6079
6080void PeerConnection::OnTransportControllerCandidatesRemoved(
6081 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006082 // Sanity check.
6083 for (const cricket::Candidate& candidate : candidates) {
6084 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006085 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006086 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006087 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006088 return;
6089 }
6090 }
6091
6092 if (local_description()) {
6093 mutable_local_description()->RemoveCandidates(candidates);
6094 }
6095 OnIceCandidatesRemoved(candidates);
6096}
6097
6098void PeerConnection::OnTransportControllerDtlsHandshakeError(
6099 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006100 RTC_HISTOGRAM_ENUMERATION(
6101 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6102 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006103}
6104
Steve Antoned10bd92017-12-05 10:52:59 -08006105void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006106 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006107 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006108 if (channel && !channel->enabled()) {
6109 channel->Enable(true);
6110 }
Steve Anton75737c02017-11-06 10:37:17 -08006111 }
6112
Steve Anton4171afb2017-11-20 10:20:22 -08006113 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006114 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006115 }
Steve Anton75737c02017-11-06 10:37:17 -08006116}
6117
6118// Returns the media index for a local ice candidate given the content name.
6119bool PeerConnection::GetLocalCandidateMediaIndex(
6120 const std::string& content_name,
6121 int* sdp_mline_index) {
6122 if (!local_description() || !sdp_mline_index) {
6123 return false;
6124 }
6125
6126 bool content_found = false;
6127 const ContentInfos& contents = local_description()->description()->contents();
6128 for (size_t index = 0; index < contents.size(); ++index) {
6129 if (contents[index].name == content_name) {
6130 *sdp_mline_index = static_cast<int>(index);
6131 content_found = true;
6132 break;
6133 }
6134 }
6135 return content_found;
6136}
6137
6138bool PeerConnection::UseCandidatesInSessionDescription(
6139 const SessionDescriptionInterface* remote_desc) {
6140 if (!remote_desc) {
6141 return true;
6142 }
6143 bool ret = true;
6144
6145 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6146 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6147 for (size_t n = 0; n < candidates->count(); ++n) {
6148 const IceCandidateInterface* candidate = candidates->at(n);
6149 bool valid = false;
6150 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6151 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006152 RTC_LOG(LS_INFO)
6153 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006154 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006155 }
6156 continue;
6157 }
6158 ret = UseCandidate(candidate);
6159 if (!ret) {
6160 break;
6161 }
6162 }
6163 }
6164 return ret;
6165}
6166
6167bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6168 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6169 size_t remote_content_size =
6170 remote_description()->description()->contents().size();
6171 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006172 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006173 return false;
6174 }
6175
6176 cricket::ContentInfo content =
6177 remote_description()->description()->contents()[mediacontent_index];
6178 std::vector<cricket::Candidate> candidates;
6179 candidates.push_back(candidate->candidate());
6180 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006181 RTCError error =
6182 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006183 if (error.ok()) {
6184 // Candidates successfully submitted for checking.
6185 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6186 ice_connection_state_ ==
6187 PeerConnectionInterface::kIceConnectionDisconnected) {
6188 // If state is New, then the session has just gotten its first remote ICE
6189 // candidates, so go to Checking.
6190 // If state is Disconnected, the session is re-using old candidates or
6191 // receiving additional ones, so go to Checking.
6192 // If state is Connected, stay Connected.
6193 // TODO(bemasc): If state is Connected, and the new candidates are for a
6194 // newly added transport, then the state actually _should_ move to
6195 // checking. Add a way to distinguish that case.
6196 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6197 }
6198 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006199 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006200 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006201 }
6202 return true;
6203}
6204
6205void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006206 // Destroy video channel first since it may have a pointer to the
6207 // voice channel.
6208 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006209 if (!video_info || video_info->rejected) {
6210 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006211 }
6212
Steve Anton6fec8802017-12-04 10:37:29 -08006213 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6214 if (!audio_info || audio_info->rejected) {
6215 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006216 }
6217
6218 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6219 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006220 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006221 }
6222}
6223
Steve Antondcc3c022017-12-22 16:02:54 -08006224RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6225 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006226 const cricket::ContentGroup* bundle_group = nullptr;
6227 if (configuration_.bundle_policy ==
6228 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006229 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006230 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6232 "max-bundle configured but session description "
6233 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006234 }
6235 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006236 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006237}
6238
6239RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006240 // Creating the media channels. Transports should already have been created
6241 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006242 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006243 if (voice && !voice->rejected &&
6244 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006245 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006246 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006247 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6248 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006249 }
6250 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6251 }
6252
Steve Antondcc3c022017-12-22 16:02:54 -08006253 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006254 if (video && !video->rejected &&
6255 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006256 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006257 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006258 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6259 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006260 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006261 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006262 }
6263
Steve Antondcc3c022017-12-22 16:02:54 -08006264 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006265 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006266 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006267 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006268 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6269 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006270 }
6271 }
6272
Steve Anton8a006912017-12-04 15:25:56 -08006273 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006274}
6275
Steve Anton4171afb2017-11-20 10:20:22 -08006276// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006277cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006278 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006279 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006280 MediaTransportInterface* media_transport = nullptr;
6281 if (configuration_.use_media_transport) {
6282 media_transport = GetMediaTransport(mid);
6283 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006284
Steve Anton75737c02017-11-06 10:37:17 -08006285 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006286 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006287 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006288 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006289 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006290 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006291 }
Steve Anton75737c02017-11-06 10:37:17 -08006292 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6293 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006294 voice_channel->SignalSentPacket.connect(this,
6295 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006296 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006297
Steve Antoneda6ccd2017-12-04 10:21:55 -08006298 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006299}
6300
Steve Anton4171afb2017-11-20 10:20:22 -08006301// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006302cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006303 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006304 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006305 MediaTransportInterface* media_transport = nullptr;
6306 if (configuration_.use_media_transport) {
6307 media_transport = GetMediaTransport(mid);
6308 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006309
Steve Anton75737c02017-11-06 10:37:17 -08006310 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006311 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006312 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02006313 &ssrc_generator_, video_options_, video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006314 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006315 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006316 }
Steve Anton75737c02017-11-06 10:37:17 -08006317 video_channel->SignalDtlsSrtpSetupFailure.connect(
6318 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006319 video_channel->SignalSentPacket.connect(this,
6320 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006321 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006322
Steve Antoneda6ccd2017-12-04 10:21:55 -08006323 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006324}
6325
Zhi Huange830e682018-03-30 10:48:35 -07006326bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006327 switch (data_channel_type_) {
6328 case cricket::DCT_MEDIA_TRANSPORT:
6329 if (network_thread()->Invoke<bool>(
6330 RTC_FROM_HERE,
6331 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6332 this, mid))) {
6333 for (const auto& channel : sctp_data_channels_) {
6334 channel->OnTransportChannelCreated();
6335 }
6336 return true;
6337 }
Steve Anton75737c02017-11-06 10:37:17 -08006338 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006339 case cricket::DCT_SCTP:
6340 if (!sctp_factory_) {
6341 RTC_LOG(LS_ERROR)
6342 << "Trying to create SCTP transport, but didn't compile with "
6343 "SCTP support (HAVE_SCTP)";
6344 return false;
6345 }
6346 if (!network_thread()->Invoke<bool>(
6347 RTC_FROM_HERE,
6348 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6349 return false;
6350 }
6351 for (const auto& channel : sctp_data_channels_) {
6352 channel->OnTransportChannelCreated();
6353 }
6354 return true;
6355 case cricket::DCT_RTP:
6356 default:
6357 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6358 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6359 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006360 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006361 if (!rtp_data_channel_) {
6362 return false;
6363 }
6364 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6365 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6366 rtp_data_channel_->SignalSentPacket.connect(
6367 this, &PeerConnection::OnSentPacket_w);
6368 rtp_data_channel_->SetRtpTransport(rtp_transport);
6369 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006370 }
6371
Steve Anton75737c02017-11-06 10:37:17 -08006372 return true;
6373}
6374
6375Call::Stats PeerConnection::GetCallStats() {
6376 if (!worker_thread()->IsCurrent()) {
6377 return worker_thread()->Invoke<Call::Stats>(
6378 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6379 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006380 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006381 if (call_) {
6382 return call_->GetStats();
6383 } else {
6384 return Call::Stats();
6385 }
6386}
6387
Zhi Huange830e682018-03-30 10:48:35 -07006388bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006389 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006390 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006391 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6392 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006393 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006394 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006395 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006396 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6397 sctp_factory_->CreateSctpTransport(dtls_transport);
6398 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006399 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006400 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006401 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006402 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006403 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006404 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6405 // another thread. Would be nice if there was a helper class similar to
6406 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6407 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006408 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006409 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006410 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006411 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006412 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006413 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6414 std::move(cricket_sctp_transport));
6415 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006416 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006417}
6418
6419void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006420 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006421 sctp_transport_->Clear();
6422 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006423 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006424 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006425}
6426
6427void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006428 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006429 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006430 // Note: Cannot use rtc::Bind here because it will grab a reference to
6431 // PeerConnection and potentially cause PeerConnection to live longer than
6432 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6433 // be destroyed before PeerConnection is destroyed, and at that point all
6434 // pending tasks will be cleared.
6435 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6436 OnSctpTransportReadyToSendData_s(true);
6437 });
6438}
6439
6440void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006441 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006442 sctp_ready_to_send_data_ = ready;
6443 SignalSctpReadyToSendData(ready);
6444}
6445
6446void PeerConnection::OnSctpTransportDataReceived_n(
6447 const cricket::ReceiveDataParams& params,
6448 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006449 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006450 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006451 // Note: Cannot use rtc::Bind here because it will grab a reference to
6452 // PeerConnection and potentially cause PeerConnection to live longer than
6453 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6454 // be destroyed before PeerConnection is destroyed, and at that point all
6455 // pending tasks will be cleared.
6456 sctp_invoker_->AsyncInvoke<void>(
6457 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6458 OnSctpTransportDataReceived_s(params, payload);
6459 });
6460}
6461
6462void PeerConnection::OnSctpTransportDataReceived_s(
6463 const cricket::ReceiveDataParams& params,
6464 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006465 RTC_DCHECK_RUN_ON(signaling_thread());
6466 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006467 SignalSctpDataReceived(params, payload);
6468 }
6469}
6470
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006471void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006472 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006473 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006474 sctp_invoker_->AsyncInvoke<void>(
6475 RTC_FROM_HERE, signaling_thread(),
6476 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006477 &SignalSctpClosingProcedureStartedRemotely, sid));
6478}
6479
6480void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006481 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006482 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006483 sctp_invoker_->AsyncInvoke<void>(
6484 RTC_FROM_HERE, signaling_thread(),
6485 rtc::Bind(&sigslot::signal1<int>::operator(),
6486 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006487}
6488
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006489bool PeerConnection::SetupMediaTransportForDataChannels_n(
6490 const std::string& mid) {
6491 media_transport_ = transport_controller_->GetMediaTransport(mid);
6492 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006493 RTC_LOG(LS_ERROR)
6494 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006495 return false;
6496 }
6497
6498 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6499 media_transport_->SetDataSink(this);
6500 media_transport_data_mid_ = mid;
6501 transport_controller_->SignalMediaTransportStateChanged.connect(
6502 this, &PeerConnection::OnMediaTransportStateChanged_n);
6503 // Check the initial state right away, in case transport is already writable.
6504 OnMediaTransportStateChanged_n();
6505 return true;
6506}
6507
6508void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6509 if (!media_transport_) {
6510 return;
6511 }
6512 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6513 media_transport_data_mid_.reset();
6514 media_transport_->SetDataSink(nullptr);
6515 media_transport_invoker_ = nullptr;
6516 media_transport_ = nullptr;
6517}
6518
6519void PeerConnection::OnMediaTransportStateChanged_n() {
6520 if (!media_transport_data_mid_ ||
6521 transport_controller_->GetMediaTransportState(
6522 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6523 return;
6524 }
6525 media_transport_invoker_->AsyncInvoke<void>(
6526 RTC_FROM_HERE, signaling_thread(), [this] {
6527 RTC_DCHECK_RUN_ON(signaling_thread());
6528 media_transport_ready_to_send_data_ = true;
6529 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6530 });
6531}
6532
Steve Anton75737c02017-11-06 10:37:17 -08006533// Returns false if bundle is enabled and rtcp_mux is disabled.
6534bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6535 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6536 if (!bundle_enabled)
6537 return true;
6538
6539 const cricket::ContentGroup* bundle_group =
6540 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6541 RTC_DCHECK(bundle_group != NULL);
6542
6543 const cricket::ContentInfos& contents = desc->contents();
6544 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6545 citer != contents.end(); ++citer) {
6546 const cricket::ContentInfo* content = (&*citer);
6547 RTC_DCHECK(content != NULL);
6548 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006549 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006550 if (!HasRtcpMuxEnabled(content))
6551 return false;
6552 }
6553 }
6554 // RTCP-MUX is enabled in all the contents.
6555 return true;
6556}
6557
6558bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006559 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006560}
6561
Steve Anton06817cd2018-12-18 15:55:30 -08006562static RTCError ValidateMids(const cricket::SessionDescription& description) {
6563 std::set<std::string> mids;
6564 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006565 if (content.name.empty()) {
6566 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6567 "A media section is missing a MID attribute.");
6568 }
Steve Anton06817cd2018-12-18 15:55:30 -08006569 if (!mids.insert(content.name).second) {
6570 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6571 "Duplicate a=mid value '" + content.name + "'.");
6572 }
6573 }
6574 return RTCError::OK();
6575}
6576
Steve Anton8a006912017-12-04 15:25:56 -08006577RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006578 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006579 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006580 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006581 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006582 }
6583
6584 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006585 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006586 }
6587
Steve Anton3828c062017-12-06 10:34:51 -08006588 SdpType type = sdesc->GetType();
6589 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6590 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006591 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006592 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006593 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006594 }
6595
Steve Anton06817cd2018-12-18 15:55:30 -08006596 RTCError error = ValidateMids(*sdesc->description());
6597 if (!error.ok()) {
6598 return error;
6599 }
6600
Steve Anton75737c02017-11-06 10:37:17 -08006601 // Verify crypto settings.
6602 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006603 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6604 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006605 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006606 if (!crypto_error.ok()) {
6607 return crypto_error;
6608 }
Steve Anton75737c02017-11-06 10:37:17 -08006609 }
6610
6611 // Verify ice-ufrag and ice-pwd.
6612 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006613 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6614 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006615 }
6616
6617 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006618 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6619 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006620 }
6621
6622 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6623 // m-lines that do not rtcp-mux enabled.
6624
6625 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006626 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006627 // With an answer we want to compare the new answer session description with
6628 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006629 const cricket::SessionDescription* offer_desc =
6630 (source == cricket::CS_LOCAL) ? remote_description()->description()
6631 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006632 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6633 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6634 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006635 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6636 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006637 }
6638 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006639 // The re-offers should respect the order of m= sections in current
6640 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006641 // With a re-offer, either the current local or current remote descriptions
6642 // could be the most up to date, so we would like to check against both of
6643 // them if they exist. It could be the case that one of them has a 0 port
6644 // for a media section, but the other does not. This is important to check
6645 // against in the case that we are recycling an m= section.
6646 const cricket::SessionDescription* current_desc = nullptr;
6647 const cricket::SessionDescription* secondary_current_desc = nullptr;
6648 if (local_description()) {
6649 current_desc = local_description()->description();
6650 if (remote_description()) {
6651 secondary_current_desc = remote_description()->description();
6652 }
6653 } else if (remote_description()) {
6654 current_desc = remote_description()->description();
6655 }
Steve Anton75737c02017-11-06 10:37:17 -08006656 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006657 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6658 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006659 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6660 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006661 }
6662 }
6663
Steve Antonba42e992018-04-09 14:10:01 -07006664 if (IsUnifiedPlan()) {
6665 // Ensure that each audio and video media section has at most one
6666 // "StreamParams". This will return an error if receiving a session
6667 // description from a "Plan B" endpoint which adds multiple tracks of the
6668 // same type. With Unified Plan, there can only be at most one track per
6669 // media section.
6670 for (const ContentInfo& content : sdesc->description()->contents()) {
6671 const MediaContentDescription& desc = *content.description;
6672 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6673 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6674 desc.streams().size() > 1u) {
6675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6676 "Media section has more than one track specified "
6677 "with a=ssrc lines which is not supported with "
6678 "Unified Plan.");
6679 }
6680 }
6681 }
6682
Steve Anton8a006912017-12-04 15:25:56 -08006683 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006684}
6685
Steve Anton3828c062017-12-06 10:34:51 -08006686bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006687 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006688 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006689 return (state == PeerConnectionInterface::kStable) ||
6690 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006691 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006692 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006693 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6694 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6695 }
6696}
6697
Steve Anton3828c062017-12-06 10:34:51 -08006698bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006699 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006700 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006701 return (state == PeerConnectionInterface::kStable) ||
6702 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006703 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006704 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006705 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6706 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6707 }
6708}
6709
Steve Antonf8470812017-12-04 10:46:21 -08006710const char* PeerConnection::SessionErrorToString(SessionError error) const {
6711 switch (error) {
6712 case SessionError::kNone:
6713 return "ERROR_NONE";
6714 case SessionError::kContent:
6715 return "ERROR_CONTENT";
6716 case SessionError::kTransport:
6717 return "ERROR_TRANSPORT";
6718 }
6719 RTC_NOTREACHED();
6720 return "";
6721}
6722
Steve Anton75737c02017-11-06 10:37:17 -08006723std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006724 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006725 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6726 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006727 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006728}
6729
Steve Anton8e20f172018-03-06 10:55:04 -08006730void PeerConnection::ReportSdpFormatReceived(
6731 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006732 int num_audio_mlines = 0;
6733 int num_video_mlines = 0;
6734 int num_audio_tracks = 0;
6735 int num_video_tracks = 0;
6736 for (const ContentInfo& content : remote_offer.description()->contents()) {
6737 cricket::MediaType media_type = content.media_description()->type();
6738 int num_tracks = std::max(
6739 1, static_cast<int>(content.media_description()->streams().size()));
6740 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6741 num_audio_mlines += 1;
6742 num_audio_tracks += num_tracks;
6743 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6744 num_video_mlines += 1;
6745 num_video_tracks += num_tracks;
6746 }
6747 }
6748 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6749 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6750 format = kSdpFormatReceivedComplexUnifiedPlan;
6751 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6752 format = kSdpFormatReceivedComplexPlanB;
6753 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6754 format = kSdpFormatReceivedSimple;
6755 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006756 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6757 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006758}
6759
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006760void PeerConnection::NoteUsageEvent(UsageEvent event) {
6761 RTC_DCHECK_RUN_ON(signaling_thread());
6762 usage_event_accumulator_ |= static_cast<int>(event);
6763}
6764
6765void PeerConnection::ReportUsagePattern() const {
6766 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006767 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6768 usage_event_accumulator_,
6769 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006770 const int bad_bits =
6771 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6772 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6773 const int good_bits =
6774 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6775 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6776 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6777 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6778 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006779 // If called after close(), we can't report, because observer may have
6780 // been deallocated, and therefore pointer is null. Write to log instead.
6781 if (observer_) {
6782 Observer()->OnInterestingUsage(usage_event_accumulator_);
6783 } else {
6784 RTC_LOG(LS_INFO) << "Interesting usage signature "
6785 << usage_event_accumulator_
6786 << " observed after observer shutdown";
6787 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006788 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006789}
6790
Steve Anton0ffaaa22018-02-23 10:31:30 -08006791void PeerConnection::ReportNegotiatedSdpSemantics(
6792 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006793 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006794 switch (answer.description()->msid_signaling()) {
6795 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006796 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006797 break;
6798 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006799 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006800 break;
6801 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006802 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006803 break;
6804 case cricket::kMsidSignalingMediaSection |
6805 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006806 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006807 break;
6808 default:
6809 RTC_NOTREACHED();
6810 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006811 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6812 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006813}
6814
Steve Anton75737c02017-11-06 10:37:17 -08006815// We need to check the local/remote description for the Transport instead of
6816// the session, because a new Transport added during renegotiation may have
6817// them unset while the session has them set from the previous negotiation.
6818// Not doing so may trigger the auto generation of transport description and
6819// mess up DTLS identity information, ICE credential, etc.
6820bool PeerConnection::ReadyToUseRemoteCandidate(
6821 const IceCandidateInterface* candidate,
6822 const SessionDescriptionInterface* remote_desc,
6823 bool* valid) {
6824 *valid = true;
6825
6826 const SessionDescriptionInterface* current_remote_desc =
6827 remote_desc ? remote_desc : remote_description();
6828
6829 if (!current_remote_desc) {
6830 return false;
6831 }
6832
6833 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6834 size_t remote_content_size =
6835 current_remote_desc->description()->contents().size();
6836 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006837 RTC_LOG(LS_ERROR)
6838 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6839 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006840
6841 *valid = false;
6842 return false;
6843 }
6844
6845 cricket::ContentInfo content =
6846 current_remote_desc->description()->contents()[mediacontent_index];
6847
6848 const std::string transport_name = GetTransportName(content.name);
6849 if (transport_name.empty()) {
6850 return false;
6851 }
Zhi Huange830e682018-03-30 10:48:35 -07006852 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006853}
6854
6855bool PeerConnection::SrtpRequired() const {
6856 return dtls_enabled_ ||
6857 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6858}
6859
6860void PeerConnection::OnTransportControllerGatheringState(
6861 cricket::IceGatheringState state) {
6862 RTC_DCHECK(signaling_thread()->IsCurrent());
6863 if (state == cricket::kIceGatheringGathering) {
6864 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6865 } else if (state == cricket::kIceGatheringComplete) {
6866 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6867 }
6868}
6869
6870void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006871 std::map<std::string, std::set<cricket::MediaType>>
6872 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006873 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006874 if (transceiver->internal()->channel()) {
6875 const std::string& transport_name =
6876 transceiver->internal()->channel()->transport_name();
6877 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006878 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006879 }
Steve Anton75737c02017-11-06 10:37:17 -08006880 }
6881 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006882 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6883 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006884 }
Zhi Huange830e682018-03-30 10:48:35 -07006885
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006886 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006887 if (transport_name) {
6888 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006889 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006890 }
Zhi Huange830e682018-03-30 10:48:35 -07006891
Steve Antonc7b964c2018-02-01 14:39:45 -08006892 for (const auto& entry : media_types_by_transport_name) {
6893 const std::string& transport_name = entry.first;
6894 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006895 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006896 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006897 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006898 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006899 }
6900 }
6901}
6902// Walk through the ConnectionInfos to gather best connection usage
6903// for IPv4 and IPv6.
6904void PeerConnection::ReportBestConnectionState(
6905 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006906 for (const cricket::TransportChannelStats& channel_stats :
6907 stats.channel_stats) {
6908 for (const cricket::ConnectionInfo& connection_info :
6909 channel_stats.connection_infos) {
6910 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006911 continue;
6912 }
6913
Steve Antonc7b964c2018-02-01 14:39:45 -08006914 const cricket::Candidate& local = connection_info.local_candidate;
6915 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006916
6917 // Increment the counter for IceCandidatePairType.
6918 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6919 (local.type() == RELAY_PORT_TYPE &&
6920 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006921 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6922 GetIceCandidatePairCounter(local, remote),
6923 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006924 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006925 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6926 GetIceCandidatePairCounter(local, remote),
6927 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006928 } else {
6929 RTC_CHECK(0);
6930 }
Steve Anton75737c02017-11-06 10:37:17 -08006931
6932 // Increment the counter for IP type.
6933 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006934 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6935 kBestConnections_IPv4,
6936 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006937 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006938 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6939 kBestConnections_IPv6,
6940 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006941 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006942 RTC_CHECK(!local.address().hostname().empty() &&
6943 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006944 }
6945
6946 return;
6947 }
6948 }
6949}
6950
6951void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006952 const cricket::TransportStats& stats,
6953 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006954 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6955 return;
6956 }
6957
6958 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6959 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6960 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6961 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6962 return;
6963 }
6964
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006965 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6966 for (cricket::MediaType media_type : media_types) {
6967 switch (media_type) {
6968 case cricket::MEDIA_TYPE_AUDIO:
6969 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6970 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6971 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6972 break;
6973 case cricket::MEDIA_TYPE_VIDEO:
6974 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6975 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6976 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6977 break;
6978 case cricket::MEDIA_TYPE_DATA:
6979 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6980 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6981 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6982 break;
6983 default:
6984 RTC_NOTREACHED();
6985 continue;
6986 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006987 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006988 }
6989
6990 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6991 for (cricket::MediaType media_type : media_types) {
6992 switch (media_type) {
6993 case cricket::MEDIA_TYPE_AUDIO:
6994 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6995 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6996 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6997 break;
6998 case cricket::MEDIA_TYPE_VIDEO:
6999 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7000 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7001 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7002 break;
7003 case cricket::MEDIA_TYPE_DATA:
7004 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7005 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7006 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7007 break;
7008 default:
7009 RTC_NOTREACHED();
7010 continue;
7011 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007012 }
Steve Anton75737c02017-11-06 10:37:17 -08007013 }
7014}
7015
7016void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007017 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007018 RTC_DCHECK(call_);
7019 call_->OnSentPacket(sent_packet);
7020}
7021
7022const std::string PeerConnection::GetTransportName(
7023 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007024 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007025 if (channel) {
7026 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007027 }
Steve Anton6fec8802017-12-04 10:37:29 -08007028 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007029 RTC_DCHECK(sctp_mid_);
7030 if (content_name == *sctp_mid_) {
7031 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007032 }
7033 }
7034 // Return an empty string if failed to retrieve the transport name.
7035 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007036}
7037
Steve Anton6fec8802017-12-04 10:37:29 -08007038void PeerConnection::DestroyTransceiverChannel(
7039 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7040 transceiver) {
7041 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007042
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007043 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007044 if (channel) {
7045 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007046 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007047 }
7048}
7049
7050void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007051 if (rtp_data_channel_) {
7052 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007053 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007054 rtp_data_channel_ = nullptr;
7055 }
7056
7057 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7058 // grab a reference to this PeerConnection. If this is called from the
7059 // PeerConnection destructor, the RefCountedObject vtable will have already
7060 // been destroyed (since it is a subclass of PeerConnection) and using
7061 // rtc::Bind will cause "Pure virtual function called" error to appear.
7062
7063 if (sctp_transport_) {
7064 OnDataChannelDestroyed();
7065 network_thread()->Invoke<void>(RTC_FROM_HERE,
7066 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007067 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007068 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007069
7070 if (media_transport_) {
7071 OnDataChannelDestroyed();
7072 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7073 RTC_DCHECK_RUN_ON(network_thread());
7074 TeardownMediaTransportForDataChannels_n();
7075 });
7076 }
Steve Anton6fec8802017-12-04 10:37:29 -08007077}
7078
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007079void PeerConnection::DestroyChannelInterface(
7080 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007081 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007082 switch (channel->media_type()) {
7083 case cricket::MEDIA_TYPE_AUDIO:
7084 channel_manager()->DestroyVoiceChannel(
7085 static_cast<cricket::VoiceChannel*>(channel));
7086 break;
7087 case cricket::MEDIA_TYPE_VIDEO:
7088 channel_manager()->DestroyVideoChannel(
7089 static_cast<cricket::VideoChannel*>(channel));
7090 break;
7091 case cricket::MEDIA_TYPE_DATA:
7092 channel_manager()->DestroyRtpDataChannel(
7093 static_cast<cricket::RtpDataChannel*>(channel));
7094 break;
7095 default:
7096 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7097 break;
7098 }
Zhi Huange830e682018-03-30 10:48:35 -07007099}
Steve Anton6fec8802017-12-04 10:37:29 -08007100
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007101bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007102 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007103 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007104 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007105 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007106 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007107 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007108 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007109 auto base_channel = GetChannel(mid);
7110 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007111 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007112 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007113 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007114 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007115 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007116
Karl Wiberg5966c502019-02-21 23:55:09 +01007117 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007118 // Only pass media transport to call object if media transport is used
7119 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007120 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007121 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007122
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007123 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007124}
7125
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007126PeerConnectionObserver* PeerConnection::Observer() const {
7127 // In earlier production code, the pointer was not cleared on close,
7128 // which might have led to undefined behavior if the observer was not
7129 // deallocated, or strange crashes if it was.
7130 // We use CHECK in order to catch such behavior if it exists.
7131 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7132 RTC_CHECK(observer_);
7133 return observer_;
7134}
7135
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007136CryptoOptions PeerConnection::GetCryptoOptions() {
7137 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7138 // after it has been removed.
7139 return configuration_.crypto_options.has_value()
7140 ? *configuration_.crypto_options
7141 : factory_->options().crypto_options;
7142}
7143
Harald Alvestrand89061872018-01-02 14:08:34 +01007144void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007145 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007146 if (stats_collector_) {
7147 stats_collector_->ClearCachedStatsReport();
7148 }
7149}
7150
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007151void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007152 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7153 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007154}
7155
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007156void PeerConnection::UpdateNegotiationNeeded() {
7157 RTC_DCHECK_RUN_ON(signaling_thread());
7158 if (!IsUnifiedPlan()) {
7159 Observer()->OnRenegotiationNeeded();
7160 return;
7161 }
7162
7163 // If connection's [[IsClosed]] slot is true, abort these steps.
7164 if (IsClosed())
7165 return;
7166
7167 // If connection's signaling state is not "stable", abort these steps.
7168 if (signaling_state() != kStable)
7169 return;
7170
7171 // NOTE
7172 // The negotiation-needed flag will be updated once the state transitions to
7173 // "stable", as part of the steps for setting an RTCSessionDescription.
7174
7175 // If the result of checking if negotiation is needed is false, clear the
7176 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7177 // to false, and abort these steps.
7178 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7179 if (!is_negotiation_needed) {
7180 is_negotiation_needed_ = false;
7181 return;
7182 }
7183
7184 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7185 // steps.
7186 if (is_negotiation_needed_)
7187 return;
7188
7189 // Set connection's [[NegotiationNeeded]] slot to true.
7190 is_negotiation_needed_ = true;
7191
7192 // Queue a task that runs the following steps:
7193 // If connection's [[IsClosed]] slot is true, abort these steps.
7194 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7195 // Fire an event named negotiationneeded at connection.
7196 Observer()->OnRenegotiationNeeded();
7197}
7198
7199bool PeerConnection::CheckIfNegotiationIsNeeded() {
7200 RTC_DCHECK_RUN_ON(signaling_thread());
7201 // 1. If any implementation-specific negotiation is required, as described at
7202 // the start of this section, return true.
7203
7204 // 2. Let description be connection.[[CurrentLocalDescription]].
7205 const SessionDescriptionInterface* description = current_local_description();
7206 if (!description)
7207 return true;
7208
7209 // 3. If connection has created any RTCDataChannels, and no m= section in
7210 // description has been negotiated yet for data, return true.
7211 if (!sctp_data_channels_.empty()) {
7212 if (!cricket::GetFirstDataContent(description->description()->contents()))
7213 return true;
7214 }
7215
7216 // 4. For each transceiver in connection's set of transceivers, perform the
7217 // following checks:
7218 for (const auto& transceiver : transceivers_) {
7219 const ContentInfo* current_local_msection =
7220 FindTransceiverMSection(transceiver.get(), description);
7221
7222 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7223 transceiver.get(), current_remote_description());
7224
7225 // 4.3 If transceiver is stopped and is associated with an m= section,
7226 // but the associated m= section is not yet rejected in
7227 // connection.[[CurrentLocalDescription]] or
7228 // connection.[[CurrentRemoteDescription]], return true.
7229 if (transceiver->stopped()) {
7230 if (current_local_msection && !current_local_msection->rejected &&
7231 ((current_remote_msection && !current_remote_msection->rejected) ||
7232 !current_remote_msection)) {
7233 return true;
7234 }
7235 continue;
7236 }
7237
7238 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7239 // section in description, return true.
7240 if (!current_local_msection)
7241 return true;
7242
7243 const MediaContentDescription* current_local_media_description =
7244 current_local_msection->media_description();
7245 // 4.2 If transceiver isn't stopped and is associated with an m= section
7246 // in description then perform the following checks:
7247
7248 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7249 // associated m= section in description either doesn't contain a single
7250 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7251 // m= section, or the MSID values themselves, differ from what is in
7252 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7253 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7254 if (current_local_media_description->streams().size() == 0)
7255 return true;
7256
7257 std::vector<std::string> msection_msids;
7258 for (const auto& stream : current_local_media_description->streams()) {
7259 for (const std::string& msid : stream.stream_ids())
7260 msection_msids.push_back(msid);
7261 }
7262
7263 std::vector<std::string> transceiver_msids =
7264 transceiver->sender()->stream_ids();
7265 if (msection_msids.size() != transceiver_msids.size())
7266 return true;
7267
7268 absl::c_sort(transceiver_msids);
7269 absl::c_sort(msection_msids);
7270 if (transceiver_msids != msection_msids)
7271 return true;
7272 }
7273
7274 // 4.2.2 If description is of type "offer", and the direction of the
7275 // associated m= section in neither connection.[[CurrentLocalDescription]]
7276 // nor connection.[[CurrentRemoteDescription]] matches
7277 // transceiver.[[Direction]], return true.
7278 if (description->GetType() == SdpType::kOffer) {
7279 if (!current_remote_description())
7280 return true;
7281
7282 if (!current_remote_msection)
7283 return true;
7284
7285 RtpTransceiverDirection current_local_direction =
7286 current_local_media_description->direction();
7287 RtpTransceiverDirection current_remote_direction =
7288 current_remote_msection->media_description()->direction();
7289 if (transceiver->direction() != current_local_direction &&
7290 transceiver->direction() !=
7291 RtpTransceiverDirectionReversed(current_remote_direction)) {
7292 return true;
7293 }
7294 }
7295
7296 // 4.2.3 If description is of type "answer", and the direction of the
7297 // associated m= section in the description does not match
7298 // transceiver.[[Direction]] intersected with the offered direction (as
7299 // described in [JSEP] (section 5.3.1.)), return true.
7300 if (description->GetType() == SdpType::kAnswer) {
7301 if (!remote_description())
7302 return true;
7303
7304 const ContentInfo* offered_remote_msection =
7305 FindTransceiverMSection(transceiver.get(), remote_description());
7306
7307 RtpTransceiverDirection offered_direction =
7308 offered_remote_msection
7309 ? offered_remote_msection->media_description()->direction()
7310 : RtpTransceiverDirection::kInactive;
7311
7312 if (current_local_media_description->direction() !=
7313 (RtpTransceiverDirectionIntersection(
7314 transceiver->direction(),
7315 RtpTransceiverDirectionReversed(offered_direction)))) {
7316 return true;
7317 }
7318 }
7319 }
7320
7321 // If all the preceding checks were performed and true was not returned,
7322 // nothing remains to be negotiated; return false.
7323 return false;
7324}
7325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007326} // namespace webrtc