blob: 14c868325607650bd3326de40bf0add3d5ef35fa [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"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.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;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
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// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200596 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200599 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800600}
601
Seth Hampson5b4f0752018-04-02 16:31:36 -0700602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200613absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200617 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700618 }
619 return rtc_configuration_parameter;
620}
621
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800622cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
623 switch (type) {
624 case DataMessageType::kText:
625 return cricket::DMT_TEXT;
626 case DataMessageType::kBinary:
627 return cricket::DMT_BINARY;
628 case DataMessageType::kControl:
629 return cricket::DMT_CONTROL;
630 default:
631 return cricket::DMT_NONE;
632 }
633 return cricket::DMT_NONE;
634}
635
636DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
637 switch (type) {
638 case cricket::DMT_TEXT:
639 return DataMessageType::kText;
640 case cricket::DMT_BINARY:
641 return DataMessageType::kBinary;
642 case cricket::DMT_CONTROL:
643 return DataMessageType::kControl;
644 case cricket::DMT_NONE:
645 default:
646 RTC_NOTREACHED();
647 }
648 return DataMessageType::kControl;
649}
650
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800651void ReportSimulcastApiVersion(const char* name,
652 const SessionDescription& session) {
653 bool has_legacy = false;
654 bool has_spec_compliant = false;
655 for (const ContentInfo& content : session.contents()) {
656 if (!content.description) {
657 continue;
658 }
659 has_spec_compliant |= content.description->HasSimulcast();
660 for (const StreamParams& sp : content.description->streams()) {
661 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
662 }
663 }
664
665 if (has_legacy) {
666 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
667 kSimulcastApiVersionMax);
668 }
669 if (has_spec_compliant) {
670 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
671 kSimulcastApiVersionMax);
672 }
673 if (!has_legacy && !has_spec_compliant) {
674 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
675 kSimulcastApiVersionMax);
676 }
677}
678
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200679const ContentInfo* FindTransceiverMSection(
680 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
681 const SessionDescriptionInterface* session_description) {
682 return transceiver->mid()
683 ? session_description->description()->GetContentByName(
684 *transceiver->mid())
685 : nullptr;
686}
687
Steve Anton75737c02017-11-06 10:37:17 -0800688} // namespace
689
Henrik Boström31638672017-11-23 17:48:32 +0100690// Upon completion, posts a task to execute the callback of the
691// SetSessionDescriptionObserver asynchronously on the same thread. At this
692// point, the state of the peer connection might no longer reflect the effects
693// of the SetRemoteDescription operation, as the peer connection could have been
694// modified during the post.
695// TODO(hbos): Remove this class once we remove the version of
696// PeerConnectionInterface::SetRemoteDescription() that takes a
697// SetSessionDescriptionObserver as an argument.
698class PeerConnection::SetRemoteDescriptionObserverAdapter
699 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
700 public:
701 SetRemoteDescriptionObserverAdapter(
702 rtc::scoped_refptr<PeerConnection> pc,
703 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
704 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
705
706 // SetRemoteDescriptionObserverInterface implementation.
707 void OnSetRemoteDescriptionComplete(RTCError error) override {
708 if (error.ok())
709 pc_->PostSetSessionDescriptionSuccess(wrapper_);
710 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100711 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100712 }
713
714 private:
715 rtc::scoped_refptr<PeerConnection> pc_;
716 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
717};
718
deadbeef293e9262017-01-11 12:28:30 -0800719bool PeerConnectionInterface::RTCConfiguration::operator==(
720 const PeerConnectionInterface::RTCConfiguration& o) const {
721 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700722 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800723 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000724 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700725 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800726 BundlePolicy bundle_policy;
727 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700728 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
729 int ice_candidate_pool_size;
730 bool disable_ipv6;
731 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700732 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100733 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<int> screencast_min_bitrate;
736 absl::optional<bool> combined_audio_video_bwe;
737 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800738 TcpCandidatePolicy tcp_candidate_policy;
739 CandidateNetworkPolicy candidate_network_policy;
740 int audio_jitter_buffer_max_packets;
741 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100742 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100743 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800744 int ice_connection_receiving_timeout;
745 int ice_backup_candidate_pair_ping_interval;
746 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800747 bool prioritize_most_likely_ice_candidate_pairs;
748 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800749 bool prune_turn_ports;
750 bool presume_writable_when_fully_relayed;
751 bool enable_ice_renomination;
752 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200753 absl::optional<int> ice_check_interval_strong_connectivity;
754 absl::optional<int> ice_check_interval_weak_connectivity;
755 absl::optional<int> ice_check_min_interval;
756 absl::optional<int> ice_unwritable_timeout;
757 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800758 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200759 absl::optional<int> stun_candidate_keepalive_interval;
760 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200761 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800762 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700764 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700765 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700767 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700768 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100769 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770 };
771 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
772 "Did you add something to RTCConfiguration and forget to "
773 "update operator==?");
774 return type == o.type && servers == o.servers &&
775 bundle_policy == o.bundle_policy &&
776 rtcp_mux_policy == o.rtcp_mux_policy &&
777 tcp_candidate_policy == o.tcp_candidate_policy &&
778 candidate_network_policy == o.candidate_network_policy &&
779 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
780 audio_jitter_buffer_fast_accelerate ==
781 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 audio_jitter_buffer_min_delay_ms ==
783 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100784 audio_jitter_buffer_enable_rtx_handling ==
785 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800786 ice_connection_receiving_timeout ==
787 o.ice_connection_receiving_timeout &&
788 ice_backup_candidate_pair_ping_interval ==
789 o.ice_backup_candidate_pair_ping_interval &&
790 continual_gathering_policy == o.continual_gathering_policy &&
791 certificates == o.certificates &&
792 prioritize_most_likely_ice_candidate_pairs ==
793 o.prioritize_most_likely_ice_candidate_pairs &&
794 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800795 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700796 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100797 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800798 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800799 screencast_min_bitrate == o.screencast_min_bitrate &&
800 combined_audio_video_bwe == o.combined_audio_video_bwe &&
801 enable_dtls_srtp == o.enable_dtls_srtp &&
802 ice_candidate_pool_size == o.ice_candidate_pool_size &&
803 prune_turn_ports == o.prune_turn_ports &&
804 presume_writable_when_fully_relayed ==
805 o.presume_writable_when_fully_relayed &&
806 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800807 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800808 ice_check_interval_strong_connectivity ==
809 o.ice_check_interval_strong_connectivity &&
810 ice_check_interval_weak_connectivity ==
811 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700812 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700813 ice_unwritable_timeout == o.ice_unwritable_timeout &&
814 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800815 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800816 stun_candidate_keepalive_interval ==
817 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200818 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800819 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800820 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700821 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700822 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700823 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700824 use_media_transport_for_data_channels ==
825 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700826 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100827 crypto_options == o.crypto_options &&
828 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800829}
830
831bool PeerConnectionInterface::RTCConfiguration::operator!=(
832 const PeerConnectionInterface::RTCConfiguration& o) const {
833 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800834}
835
zhihuang8f65cdf2016-05-06 18:40:30 -0700836// Generate a RTCP CNAME when a PeerConnection is created.
837std::string GenerateRtcpCname() {
838 std::string cname;
839 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800841 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700842 }
843 return cname;
844}
845
zhihuang1c378ed2017-08-17 14:10:50 -0700846bool ValidateOfferAnswerOptions(
847 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
848 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
849 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700850}
851
zhihuang1c378ed2017-08-17 14:10:50 -0700852// From |rtc_options|, fill parts of |session_options| shared by all generated
853// m= sections (in other words, nothing that involves a map/array).
854void ExtractSharedMediaSessionOptions(
855 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
856 cricket::MediaSessionOptions* session_options) {
857 session_options->vad_enabled = rtc_options.voice_activity_detection;
858 session_options->bundle_enabled = rtc_options.use_rtp_mux;
859}
zhihuanga77e6bb2017-08-14 18:17:48 -0700860
zhihuang38ede132017-06-15 12:52:32 -0700861PeerConnection::PeerConnection(PeerConnectionFactory* factory,
862 std::unique_ptr<RtcEventLog> event_log,
863 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700865 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100866 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700867 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700868 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700869 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100870 call_(std::move(call)),
871 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872
873PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100874 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800875 RTC_DCHECK_RUN_ON(signaling_thread());
876
Steve Anton8af21862017-12-15 11:20:13 -0800877 // Need to stop transceivers before destroying the stats collector because
878 // AudioRtpSender has a reference to the StatsCollector it will update when
879 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100880 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800881 transceiver->Stop();
882 }
Steve Anton4171afb2017-11-20 10:20:22 -0800883
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700884 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800885 if (stats_collector_) {
886 stats_collector_->WaitForPendingRequest();
887 stats_collector_ = nullptr;
888 }
Steve Anton75737c02017-11-06 10:37:17 -0800889
Steve Anton8af21862017-12-15 11:20:13 -0800890 // Don't destroy BaseChannels until after stats has been cleaned up so that
891 // the last stats request can still read from the channels.
892 DestroyAllChannels();
893
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800895
896 webrtc_session_desc_factory_.reset();
897 sctp_invoker_.reset();
898 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800899 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800900 transport_controller_.reset();
901
deadbeef91dd5672016-05-18 16:55:30 -0700902 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100903 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
904 RTC_DCHECK_RUN_ON(network_thread());
905 port_allocator_.reset();
906 });
eladalon248fd4f2017-09-06 05:18:15 -0700907 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700908 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100909 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700910 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800911 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700912 event_log_.reset();
913 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914}
915
Steve Anton8af21862017-12-15 11:20:13 -0800916void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800917 // Destroy video channels first since they may have a pointer to a voice
918 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100919 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800920 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800921 DestroyTransceiverChannel(transceiver);
922 }
923 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100924 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800925 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800926 DestroyTransceiverChannel(transceiver);
927 }
928 }
929 DestroyDataChannel();
930}
931
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000933 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700934 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100935 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100936 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100937 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700938
939 RTCError config_error = ValidateConfiguration(configuration);
940 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100941 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700942 return false;
943 }
944
Benjamin Wrightcab58882018-05-02 15:12:47 -0700945 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100946 RTC_LOG(LS_ERROR)
947 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100948 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800949 return false;
950 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200951
Benjamin Wrightcab58882018-05-02 15:12:47 -0700952 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800953 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100955 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800956 return false;
957 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700958
Benjamin Wrightcab58882018-05-02 15:12:47 -0700959 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700960 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700961 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700962 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800963
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200964 cricket::ServerAddresses stun_servers;
965 std::vector<cricket::RelayServerConfig> turn_servers;
966
967 RTCErrorType parse_error =
968 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
969 if (parse_error != RTCErrorType::NONE) {
970 return false;
971 }
972
deadbeef91dd5672016-05-18 16:55:30 -0700973 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700974 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100975 const auto pa_result =
976 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200977 RTC_FROM_HERE,
978 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100979 stun_servers, turn_servers, configuration));
980
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200981 // If initialization was successful, note if STUN or TURN servers
982 // were supplied.
983 if (!stun_servers.empty()) {
984 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
985 }
986 if (!turn_servers.empty()) {
987 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
988 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700990 // Send information about IPv4/IPv6 status.
991 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100992 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700993 address_family = kPeerConnection_IPv6;
994 } else {
995 address_family = kPeerConnection_IPv4;
996 }
997 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
998 kPeerConnectionAddressFamilyCounter_Max);
999
Zhi Huange830e682018-03-30 10:48:35 -07001000 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1001
Steve Anton75737c02017-11-06 10:37:17 -08001002 // RFC 3264: The numeric value of the session id and version in the
1003 // o line MUST be representable with a "64 bit signed integer".
1004 // Due to this constraint session id |session_id_| is max limited to
1005 // LLONG_MAX.
1006 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001007 JsepTransportController::Config config;
1008 config.redetermine_role_on_ice_restart =
1009 configuration.redetermine_role_on_ice_restart;
1010 config.ssl_max_version = factory_->options().ssl_max_version;
1011 config.disable_encryption = options.disable_encryption;
1012 config.bundle_policy = configuration.bundle_policy;
1013 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001014 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1015 // stub.
1016 config.crypto_options = configuration.crypto_options.has_value()
1017 ? *configuration.crypto_options
1018 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001019 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001020 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001021#if defined(ENABLE_EXTERNAL_AUTH)
1022 config.enable_external_auth = true;
1023#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001024 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001025
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001026 if (configuration.use_datagram_transport ||
1027 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001028 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001029 if (!factory_->media_transport_factory()) {
1030 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001031 << "PeerConnecton is initialized with use_media_transport = true or "
1032 << "use_media_transport_for_data_channels = true "
1033 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001034 return false;
1035 }
1036
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001037 if (configuration.use_media_transport ||
1038 configuration.use_media_transport_for_data_channels) {
1039 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1040 // RTP media transport is introduced. But until then, we require SDES to
1041 // be enabled.
1042 if (configuration.enable_dtls_srtp.has_value() &&
1043 configuration.enable_dtls_srtp.value()) {
1044 RTC_LOG(LS_WARNING)
1045 << "When media transport is used, SDES must be enabled. Set "
1046 "configuration.enable_dtls_srtp to false. use_media_transport="
1047 << configuration.use_media_transport
1048 << ", use_media_transport_for_data_channels="
1049 << configuration.use_media_transport_for_data_channels;
1050 return false;
1051 }
1052 }
1053
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001054 config.use_media_transport_for_media = configuration.use_media_transport;
1055 config.use_media_transport_for_data_channels =
1056 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001057 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001058 config.media_transport_factory = factory_->media_transport_factory();
1059 }
1060
Zhi Huange830e682018-03-30 10:48:35 -07001061 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001062 signaling_thread(), network_thread(), port_allocator_.get(),
1063 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001064 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001065 this, &PeerConnection::OnTransportControllerConnectionState);
1066 transport_controller_->SignalStandardizedIceConnectionState.connect(
1067 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001068 transport_controller_->SignalConnectionState.connect(
1069 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001070 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001071 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001072 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001073 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001074 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001075 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1076 transport_controller_->SignalDtlsHandshakeError.connect(
1077 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1078
1079 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001080
deadbeefab9b2d12015-10-14 11:33:11 -07001081 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001082 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083
Steve Antonba818672017-11-06 10:21:57 -08001084 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001085 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001086
Steve Anton75737c02017-11-06 10:37:17 -08001087 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1088 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1089 if (!configuration.certificates.empty()) {
1090 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1091 // just picking the first one. The decision should be made based on the DTLS
1092 // handshake. The DTLS negotiations need to know about all certificates.
1093 certificate = configuration.certificates[0];
1094 }
1095
Steve Antond25da372017-11-06 14:50:29 -08001096 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001097
1098 if (options.disable_encryption) {
1099 dtls_enabled_ = false;
1100 } else {
1101 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001102 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001103 // |configuration| can override the default |dtls_enabled_| value.
1104 if (configuration.enable_dtls_srtp) {
1105 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1106 }
1107 }
1108
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001109 if (configuration.use_media_transport_for_data_channels) {
1110 if (configuration.enable_rtp_data_channel) {
1111 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1112 "use_media_transport_for_data_channels are "
1113 "incompatible and cannot both be set to true";
1114 return false;
1115 }
1116 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1117 } else if (configuration.enable_rtp_data_channel) {
1118 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1119 // set. It takes precendence over the disable_sctp_data_channels
1120 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001121 data_channel_type_ = cricket::DCT_RTP;
1122 } else {
1123 // DTLS has to be enabled to use SCTP.
1124 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1125 data_channel_type_ = cricket::DCT_SCTP;
1126 }
1127 }
1128
1129 video_options_.screencast_min_bitrate_kbps =
1130 configuration.screencast_min_bitrate;
1131 audio_options_.combined_audio_video_bwe =
1132 configuration.combined_audio_video_bwe;
1133
1134 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001135 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001136
1137 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001138 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001139
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001140 audio_options_.audio_jitter_buffer_min_delay_ms =
1141 configuration.audio_jitter_buffer_min_delay_ms;
1142
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001143 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1144 configuration.audio_jitter_buffer_enable_rtx_handling;
1145
Steve Anton75737c02017-11-06 10:37:17 -08001146 // Whether the certificate generator/certificate is null or not determines
1147 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1148 // the right instructions by clearing the variables if needed.
1149 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001150 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001151 certificate = nullptr;
1152 } else if (certificate) {
1153 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001154 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001155 }
1156
1157 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1158 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001159 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001160 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1161 this, &PeerConnection::OnCertificateReady);
1162
1163 if (options.disable_encryption) {
1164 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1165 }
1166
1167 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001168 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001169 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170
Steve Anton4171afb2017-11-20 10:20:22 -08001171 // Add default audio/video transceivers for Plan B SDP.
1172 if (!IsUnifiedPlan()) {
1173 transceivers_.push_back(
1174 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1175 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1176 transceivers_.push_back(
1177 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1178 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1179 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001180 int delay_ms =
1181 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001182 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1183 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001184
1185 if (dependencies.video_bitrate_allocator_factory) {
1186 video_bitrate_allocator_factory_ =
1187 std::move(dependencies.video_bitrate_allocator_factory);
1188 } else {
1189 video_bitrate_allocator_factory_ =
1190 CreateBuiltinVideoBitrateAllocatorFactory();
1191 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001192 return true;
1193}
1194
Steve Anton038834f2017-07-14 15:59:59 -07001195RTCError PeerConnection::ValidateConfiguration(
1196 const RTCConfiguration& config) const {
1197 if (config.ice_regather_interval_range &&
1198 config.continual_gathering_policy == GATHER_ONCE) {
1199 return RTCError(RTCErrorType::INVALID_PARAMETER,
1200 "ice_regather_interval_range specified but continual "
1201 "gathering policy is GATHER_ONCE");
1202 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001203 auto result =
1204 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1205 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001206}
1207
Yves Gerey665174f2018-06-19 15:03:05 +02001208rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001209 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001210 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1211 "Plan SdpSemantics. Please use GetSenders "
1212 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001213 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214}
1215
Yves Gerey665174f2018-06-19 15:03:05 +02001216rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_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()) << "remote_streams is not available with Unified "
1219 "Plan SdpSemantics. Please use GetReceivers "
1220 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001221 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222}
1223
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001224bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001225 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001226 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1227 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001228 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229 if (IsClosed()) {
1230 return false;
1231 }
deadbeefab9b2d12015-10-14 11:33:11 -07001232 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 return false;
1234 }
deadbeefab9b2d12015-10-14 11:33:11 -07001235
1236 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001237 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1238 observer->SignalAudioTrackAdded.connect(this,
1239 &PeerConnection::OnAudioTrackAdded);
1240 observer->SignalAudioTrackRemoved.connect(
1241 this, &PeerConnection::OnAudioTrackRemoved);
1242 observer->SignalVideoTrackAdded.connect(this,
1243 &PeerConnection::OnVideoTrackAdded);
1244 observer->SignalVideoTrackRemoved.connect(
1245 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001246 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001247
deadbeefab9b2d12015-10-14 11:33:11 -07001248 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001249 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001250 }
1251 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001252 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001253 }
1254
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001255 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001256 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257 return true;
1258}
1259
1260void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001261 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001262 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1263 "Plan SdpSemantics. Please use RemoveTrack "
1264 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001265 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001266 if (!IsClosed()) {
1267 for (const auto& track : local_stream->GetAudioTracks()) {
1268 RemoveAudioTrack(track.get(), local_stream);
1269 }
1270 for (const auto& track : local_stream->GetVideoTracks()) {
1271 RemoveVideoTrack(track.get(), local_stream);
1272 }
deadbeefab9b2d12015-10-14 11:33:11 -07001273 }
deadbeefab9b2d12015-10-14 11:33:11 -07001274 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001275 stream_observers_.erase(
1276 std::remove_if(
1277 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001278 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001279 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001280 }),
1281 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 if (IsClosed()) {
1284 return;
1285 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001286 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287}
1288
Steve Anton2d6c76a2018-01-05 17:10:52 -08001289RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001290 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001291 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001292 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001293 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001294 if (!track) {
1295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1296 }
1297 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1298 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1300 "Track has invalid kind: " + track->kind());
1301 }
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (IsClosed()) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1304 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001305 }
Steve Anton4171afb2017-11-20 10:20:22 -08001306 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001307 LOG_AND_RETURN_ERROR(
1308 RTCErrorType::INVALID_PARAMETER,
1309 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001310 }
Steve Antonf9381f02017-12-14 10:23:57 -08001311 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001312 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1313 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001314 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001315 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001316 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001317 }
1318 return sender_or_error;
1319}
deadbeefe1f9d832016-01-14 15:35:42 -08001320
Steve Antonf9381f02017-12-14 10:23:57 -08001321RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1322PeerConnection::AddTrackPlanB(
1323 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001324 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001325 if (stream_ids.size() > 1u) {
1326 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1327 "AddTrack with more than one stream is not "
1328 "supported with Plan B semantics.");
1329 }
1330 std::vector<std::string> adjusted_stream_ids = stream_ids;
1331 if (adjusted_stream_ids.empty()) {
1332 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1333 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001334 cricket::MediaType media_type =
1335 (track->kind() == MediaStreamTrackInterface::kAudioKind
1336 ? cricket::MEDIA_TYPE_AUDIO
1337 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001338 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001339 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001340 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001341 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001342 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001343 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001344 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001345 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001346 if (sender_info) {
1347 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001348 }
Steve Antonf9381f02017-12-14 10:23:57 -08001349 } else {
1350 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001351 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001353 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001354 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001355 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001356 if (sender_info) {
1357 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001358 }
deadbeefe1f9d832016-01-14 15:35:42 -08001359 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001360 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001361}
deadbeefe1f9d832016-01-14 15:35:42 -08001362
Steve Antonf9381f02017-12-14 10:23:57 -08001363RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1364PeerConnection::AddTrackUnifiedPlan(
1365 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001366 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001367 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1368 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001369 RTC_LOG(LS_INFO) << "Reusing an existing "
1370 << cricket::MediaTypeToString(transceiver->media_type())
1371 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001372 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001379 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001380 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 } else {
1382 cricket::MediaType media_type =
1383 (track->kind() == MediaStreamTrackInterface::kAudioKind
1384 ? cricket::MEDIA_TYPE_AUDIO
1385 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001386 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1387 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001388 std::string sender_id = track->id();
1389 // Avoid creating a sender with an existing ID by generating a random ID.
1390 // This can happen if this is the second time AddTrack has created a sender
1391 // for this track.
1392 if (FindSenderById(sender_id)) {
1393 sender_id = rtc::CreateRandomUuid();
1394 }
Florent Castelli892acf02018-10-01 22:47:20 +02001395 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001396 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1397 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001398 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001399 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001400 }
Steve Antonf9381f02017-12-14 10:23:57 -08001401 return transceiver->sender();
1402}
1403
1404rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1405PeerConnection::FindFirstTransceiverForAddedTrack(
1406 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1407 RTC_DCHECK(track);
1408 for (auto transceiver : transceivers_) {
1409 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001410 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001411 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001412 !transceiver->internal()->has_ever_been_used_to_send() &&
1413 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001414 return transceiver;
1415 }
1416 }
1417 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001418}
1419
1420bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1421 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001422 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001423}
1424
Steve Anton24db5732018-07-23 10:27:33 -07001425RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001426 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001427 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001428 if (!sender) {
1429 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1430 }
deadbeefe1f9d832016-01-14 15:35:42 -08001431 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1433 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001434 }
Steve Antonf9381f02017-12-14 10:23:57 -08001435 if (IsUnifiedPlan()) {
1436 auto transceiver = FindTransceiverBySender(sender);
1437 if (!transceiver || !sender->track()) {
1438 return RTCError::OK();
1439 }
1440 sender->SetTrack(nullptr);
1441 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001442 transceiver->internal()->set_direction(
1443 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001444 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001445 transceiver->internal()->set_direction(
1446 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001447 }
Steve Anton4171afb2017-11-20 10:20:22 -08001448 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001449 bool removed;
1450 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1451 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1452 } else {
1453 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1454 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1455 }
1456 if (!removed) {
1457 LOG_AND_RETURN_ERROR(
1458 RTCErrorType::INVALID_PARAMETER,
1459 "Couldn't find sender " + sender->id() + " to remove.");
1460 }
Steve Anton4171afb2017-11-20 10:20:22 -08001461 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001462 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001463 return RTCError::OK();
1464}
1465
1466rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1467PeerConnection::FindTransceiverBySender(
1468 rtc::scoped_refptr<RtpSenderInterface> sender) {
1469 for (auto transceiver : transceivers_) {
1470 if (transceiver->sender() == sender) {
1471 return transceiver;
1472 }
1473 }
1474 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001475}
1476
Steve Anton9158ef62017-11-27 13:01:52 -08001477RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1478PeerConnection::AddTransceiver(
1479 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1480 return AddTransceiver(track, RtpTransceiverInit());
1481}
1482
1483RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1484PeerConnection::AddTransceiver(
1485 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1486 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001487 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001488 RTC_CHECK(IsUnifiedPlan())
1489 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001490 if (!track) {
1491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1492 }
1493 cricket::MediaType media_type;
1494 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1495 media_type = cricket::MEDIA_TYPE_AUDIO;
1496 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1497 media_type = cricket::MEDIA_TYPE_VIDEO;
1498 } else {
1499 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1500 "Track kind is not audio or video");
1501 }
1502 return AddTransceiver(media_type, track, init);
1503}
1504
1505RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1506PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1507 return AddTransceiver(media_type, RtpTransceiverInit());
1508}
1509
1510RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1511PeerConnection::AddTransceiver(cricket::MediaType media_type,
1512 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001513 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001514 RTC_CHECK(IsUnifiedPlan())
1515 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001516 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1517 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1519 "media type is not audio or video");
1520 }
1521 return AddTransceiver(media_type, nullptr, init);
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(
1526 cricket::MediaType media_type,
1527 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001528 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001529 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001530 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1531 media_type == cricket::MEDIA_TYPE_VIDEO));
1532 if (track) {
1533 RTC_DCHECK_EQ(media_type,
1534 (track->kind() == MediaStreamTrackInterface::kAudioKind
1535 ? cricket::MEDIA_TYPE_AUDIO
1536 : cricket::MEDIA_TYPE_VIDEO));
1537 }
1538
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001539 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1540 init.send_encodings.size(), 0, 7, 8);
1541
Amit Hilbuchaa584152019-02-06 17:09:52 -08001542 size_t num_rids = absl::c_count_if(init.send_encodings,
1543 [](const RtpEncodingParameters& encoding) {
1544 return !encoding.rid.empty();
1545 });
1546 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001547 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001548 RTCErrorType::INVALID_PARAMETER,
1549 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001550 }
1551
Amit Hilbuchf4770402019-04-08 14:11:57 -07001552 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1553 [](const RtpEncodingParameters& encoding) {
1554 return !IsLegalRsidName(encoding.rid);
1555 })) {
1556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1557 "Invalid RID value provided.");
1558 }
1559
Amit Hilbuchaa584152019-02-06 17:09:52 -08001560 if (absl::c_any_of(init.send_encodings,
1561 [](const RtpEncodingParameters& encoding) {
1562 return encoding.ssrc.has_value();
1563 })) {
1564 LOG_AND_RETURN_ERROR(
1565 RTCErrorType::UNSUPPORTED_PARAMETER,
1566 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001567 }
1568
1569 RtpParameters parameters;
1570 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001571
1572 // Encodings are dropped from the tail if too many are provided.
1573 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1574 parameters.encodings.erase(
1575 parameters.encodings.begin() + kMaxSimulcastStreams,
1576 parameters.encodings.end());
1577 }
1578
1579 // Single RID should be removed.
1580 if (parameters.encodings.size() == 1 &&
1581 !parameters.encodings[0].rid.empty()) {
1582 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1583 parameters.encodings[0].rid.clear();
1584 }
1585
1586 // If RIDs were not provided, they are generated for simulcast scenario.
1587 if (parameters.encodings.size() > 1 && num_rids == 0) {
1588 rtc::UniqueStringGenerator rid_generator;
1589 for (RtpEncodingParameters& encoding : parameters.encodings) {
1590 encoding.rid = rid_generator();
1591 }
1592 }
1593
Florent Castelli892acf02018-10-01 22:47:20 +02001594 if (UnimplementedRtpParameterHasValue(parameters)) {
1595 LOG_AND_RETURN_ERROR(
1596 RTCErrorType::UNSUPPORTED_PARAMETER,
1597 "Attempted to set an unimplemented parameter of RtpParameters.");
1598 }
Steve Anton9158ef62017-11-27 13:01:52 -08001599
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001600 auto result = cricket::CheckRtpParametersValues(parameters);
1601 if (!result.ok()) {
1602 LOG_AND_RETURN_ERROR(result.type(), result.message());
1603 }
1604
Steve Anton3d954a62018-04-02 11:27:23 -07001605 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1606 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001607 // Set the sender ID equal to the track ID if the track is specified unless
1608 // that sender ID is already in use.
1609 std::string sender_id =
1610 (track && !FindSenderById(track->id()) ? track->id()
1611 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001612 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001613 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001614 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1615 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1616 transceiver->internal()->set_direction(init.direction);
1617
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001618 if (update_negotiation_needed) {
1619 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001620 }
Steve Antonf9381f02017-12-14 10:23:57 -08001621
1622 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1623}
1624
Steve Anton02ee47c2018-01-10 16:26:06 -08001625rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1626PeerConnection::CreateSender(
1627 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001628 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001629 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001630 const std::vector<std::string>& stream_ids,
1631 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001632 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001633 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001634 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1635 RTC_DCHECK(!track ||
1636 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1637 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1638 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001639 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001640 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001641 } else {
1642 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1643 RTC_DCHECK(!track ||
1644 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1645 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001646 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001647 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001648 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001649 bool set_track_succeeded = sender->SetTrack(track);
1650 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001651 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001652 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001653 return sender;
1654}
1655
1656rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1657PeerConnection::CreateReceiver(cricket::MediaType media_type,
1658 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001659 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1660 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001661 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001662 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001663 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1664 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001665 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001666 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001668 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001669 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1670 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001671 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001672 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001673 return receiver;
1674}
1675
1676rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1677PeerConnection::CreateAndAddTransceiver(
1678 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1679 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1680 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001681 // Ensure that the new sender does not have an ID that is already in use by
1682 // another sender.
1683 // Allow receiver IDs to conflict since those come from remote SDP (which
1684 // could be invalid, but should not cause a crash).
1685 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001686 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001687 signaling_thread(),
1688 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001689 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001690 transceiver->internal()->SignalNegotiationNeeded.connect(
1691 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001692 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001693}
1694
Steve Anton52d86772018-02-20 15:48:12 -08001695void PeerConnection::OnNegotiationNeeded() {
1696 RTC_DCHECK_RUN_ON(signaling_thread());
1697 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001698 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001699}
1700
deadbeeffac06552015-11-25 11:26:01 -08001701rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001702 const std::string& kind,
1703 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001704 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001705 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1706 "Plan SdpSemantics. Please use AddTransceiver "
1707 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001708 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001709 if (IsClosed()) {
1710 return nullptr;
1711 }
Steve Anton4171afb2017-11-20 10:20:22 -08001712
Seth Hampson5b4f0752018-04-02 16:31:36 -07001713 // Internally we need to have one stream with Plan B semantics, so we
1714 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001715 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001716 if (stream_id.empty()) {
1717 stream_ids.push_back(rtc::CreateRandomUuid());
1718 RTC_LOG(LS_INFO)
1719 << "No stream_id specified for sender. Generated stream ID: "
1720 << stream_ids[0];
1721 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001722 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001723 }
1724
Steve Anton4171afb2017-11-20 10:20:22 -08001725 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001726 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001727 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001728 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001729 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001730 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001731 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001732 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001733 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001734 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001735 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001736 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001737 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001738 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001740 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001741 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001743 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001744 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001745 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001746
deadbeefe1f9d832016-01-14 15:35:42 -08001747 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001748}
1749
deadbeef70ab1a12015-09-28 16:53:55 -07001750std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1751 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001752 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001753 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001754 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001755 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001756 }
1757 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001758}
1759
Steve Anton4171afb2017-11-20 10:20:22 -08001760std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1761PeerConnection::GetSendersInternal() const {
1762 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1763 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001764 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001765 auto senders = transceiver->internal()->senders();
1766 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1767 }
1768 return all_senders;
1769}
1770
deadbeef70ab1a12015-09-28 16:53:55 -07001771std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1772PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001773 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001774 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001775 for (const auto& receiver : GetReceiversInternal()) {
1776 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001777 }
1778 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001779}
1780
Steve Anton4171afb2017-11-20 10:20:22 -08001781std::vector<
1782 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1783PeerConnection::GetReceiversInternal() const {
1784 std::vector<
1785 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1786 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001787 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001788 auto receivers = transceiver->internal()->receivers();
1789 all_receivers.insert(all_receivers.end(), receivers.begin(),
1790 receivers.end());
1791 }
1792 return all_receivers;
1793}
1794
Steve Anton9158ef62017-11-27 13:01:52 -08001795std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1796PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001797 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001798 RTC_CHECK(IsUnifiedPlan())
1799 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001800 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001801 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001802 all_transceivers.push_back(transceiver);
1803 }
1804 return all_transceivers;
1805}
1806
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001808 MediaStreamTrackInterface* track,
1809 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001810 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001811 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001812 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001813 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 return false;
1815 }
1816
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001817 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001818 // The StatsCollector is used to tell if a track is valid because it may
1819 // remember tracks that the PeerConnection previously removed.
1820 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001821 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1822 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001823 return false;
1824 }
Steve Antonad182762018-09-05 20:22:40 +00001825 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1826 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return true;
1828}
1829
hbos74e1a4f2016-09-15 23:33:01 -07001830void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001831 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001832 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001833 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001834 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001835 stats_collector_->GetStatsReport(callback);
1836}
1837
Henrik Boström1df1bf82018-03-20 13:24:20 +01001838void PeerConnection::GetStats(
1839 rtc::scoped_refptr<RtpSenderInterface> selector,
1840 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1841 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001842 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001843 RTC_DCHECK(callback);
1844 RTC_DCHECK(stats_collector_);
1845 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1846 if (selector) {
1847 for (const auto& proxy_transceiver : transceivers_) {
1848 for (const auto& proxy_sender :
1849 proxy_transceiver->internal()->senders()) {
1850 if (proxy_sender == selector) {
1851 internal_sender = proxy_sender->internal();
1852 break;
1853 }
1854 }
1855 if (internal_sender)
1856 break;
1857 }
1858 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001859 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001860 // belong to the PeerConnection (in Plan B, senders can be removed from the
1861 // PeerConnection). This means that "all the stats objects representing the
1862 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1863 // produces an empty stats report.
1864 stats_collector_->GetStatsReport(internal_sender, callback);
1865}
1866
1867void PeerConnection::GetStats(
1868 rtc::scoped_refptr<RtpReceiverInterface> selector,
1869 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1870 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001871 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001872 RTC_DCHECK(callback);
1873 RTC_DCHECK(stats_collector_);
1874 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1875 if (selector) {
1876 for (const auto& proxy_transceiver : transceivers_) {
1877 for (const auto& proxy_receiver :
1878 proxy_transceiver->internal()->receivers()) {
1879 if (proxy_receiver == selector) {
1880 internal_receiver = proxy_receiver->internal();
1881 break;
1882 }
1883 }
1884 if (internal_receiver)
1885 break;
1886 }
1887 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001888 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001889 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1890 // the PeerConnection). This means that "all the stats objects representing
1891 // the selector" is an empty set. Invoking GetStatsReport() with a null
1892 // selector produces an empty stats report.
1893 stats_collector_->GetStatsReport(internal_receiver, callback);
1894}
1895
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001897 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 return signaling_state_;
1899}
1900
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901PeerConnectionInterface::IceConnectionState
1902PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001903 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 return ice_connection_state_;
1905}
1906
Alex Loiko9289eda2018-11-23 16:18:59 +00001907PeerConnectionInterface::IceConnectionState
1908PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001909 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001910 return standardized_ice_connection_state_;
1911}
1912
Jonas Olsson635474e2018-10-18 15:58:17 +02001913PeerConnectionInterface::PeerConnectionState
1914PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001916 return connection_state_;
1917}
1918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919PeerConnectionInterface::IceGatheringState
1920PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 return ice_gathering_state_;
1923}
1924
Yves Gerey665174f2018-06-19 15:03:05 +02001925rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 const std::string& label,
1927 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001928 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001929 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001930
deadbeefab9b2d12015-10-14 11:33:11 -07001931 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001932
kwibergd1fe2812016-04-27 06:47:29 -07001933 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001934 if (config) {
1935 internal_config.reset(new InternalDataChannelInit(*config));
1936 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001937 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001938 InternalCreateDataChannel(label, internal_config.get()));
1939 if (!channel.get()) {
1940 return nullptr;
1941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001943 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1944 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001945 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001946 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001947 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001948 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 return DataChannelProxy::Create(signaling_thread(), channel.get());
1950}
1951
1952void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001953 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001954 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001955 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
nisse7ce109a2017-01-31 00:57:56 -08001957 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001958 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001959 return;
1960 }
deadbeefab9b2d12015-10-14 11:33:11 -07001961
Steve Anton8d3444d2017-10-20 15:30:51 -07001962 if (IsClosed()) {
1963 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001965 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001966 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001967 return;
1968 }
1969
zhihuang1c378ed2017-08-17 14:10:50 -07001970 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001971 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001973 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001974 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001975 return;
1976 }
1977
Steve Anton22da89f2018-01-25 13:58:07 -08001978 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1979 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1980 if (IsUnifiedPlan()) {
1981 RTCError error = HandleLegacyOfferOptions(options);
1982 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001983 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001984 return;
1985 }
1986 }
1987
zhihuang1c378ed2017-08-17 14:10:50 -07001988 cricket::MediaSessionOptions session_options;
1989 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001990 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991}
1992
Steve Anton22da89f2018-01-25 13:58:07 -08001993RTCError PeerConnection::HandleLegacyOfferOptions(
1994 const RTCOfferAnswerOptions& options) {
1995 RTC_DCHECK(IsUnifiedPlan());
1996
1997 if (options.offer_to_receive_audio == 0) {
1998 RemoveRecvDirectionFromReceivingTransceiversOfType(
1999 cricket::MEDIA_TYPE_AUDIO);
2000 } else if (options.offer_to_receive_audio == 1) {
2001 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2002 } else if (options.offer_to_receive_audio > 1) {
2003 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2004 "offer_to_receive_audio > 1 is not supported.");
2005 }
2006
2007 if (options.offer_to_receive_video == 0) {
2008 RemoveRecvDirectionFromReceivingTransceiversOfType(
2009 cricket::MEDIA_TYPE_VIDEO);
2010 } else if (options.offer_to_receive_video == 1) {
2011 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2012 } else if (options.offer_to_receive_video > 1) {
2013 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2014 "offer_to_receive_video > 1 is not supported.");
2015 }
2016
2017 return RTCError::OK();
2018}
2019
2020void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2021 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002022 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002023 RtpTransceiverDirection new_direction =
2024 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2025 if (new_direction != transceiver->direction()) {
2026 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2027 << " transceiver (MID="
2028 << transceiver->mid().value_or("<not set>") << ") from "
2029 << RtpTransceiverDirectionToString(
2030 transceiver->direction())
2031 << " to "
2032 << RtpTransceiverDirectionToString(new_direction)
2033 << " since CreateOffer specified offer_to_receive=0";
2034 transceiver->internal()->set_direction(new_direction);
2035 }
Steve Anton22da89f2018-01-25 13:58:07 -08002036 }
2037}
2038
2039void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2040 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002041 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002042 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002043 RTC_LOG(LS_INFO)
2044 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2045 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002046 RtpTransceiverInit init;
2047 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002048 AddTransceiver(media_type, nullptr, init,
2049 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002050 }
2051}
2052
2053std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2054PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2055 std::vector<
2056 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2057 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002058 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002059 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002060 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2061 receiving_transceivers.push_back(transceiver);
2062 }
2063 }
2064 return receiving_transceivers;
2065}
2066
htaa2a49d92016-03-04 02:51:39 -08002067void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2068 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002069 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002070 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002071 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002072 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002073 return;
2074 }
2075
Steve Antondffead82018-02-06 10:31:29 -08002076 if (!(signaling_state_ == kHaveRemoteOffer ||
2077 signaling_state_ == kHaveLocalPrAnswer)) {
2078 std::string error =
2079 "PeerConnection cannot create an answer in a state other than "
2080 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002081 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002082 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002083 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002084 return;
2085 }
2086
Steve Antondffead82018-02-06 10:31:29 -08002087 // The remote description should be set if we're in the right state.
2088 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002089
Steve Anton22da89f2018-01-25 13:58:07 -08002090 if (IsUnifiedPlan()) {
2091 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2092 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2093 "supported with Unified Plan semantics. Use the "
2094 "RtpTransceiver API instead.";
2095 }
2096 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2097 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2098 "supported with Unified Plan semantics. Use the "
2099 "RtpTransceiver API instead.";
2100 }
2101 }
2102
htaa2a49d92016-03-04 02:51:39 -08002103 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002104 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002105
Steve Antond25da372017-11-06 14:50:29 -08002106 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107}
2108
2109void PeerConnection::SetLocalDescription(
2110 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002111 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002112 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002113 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002114
Steve Anton80dd7b52018-02-16 17:08:42 -08002115 // The SetLocalDescription contract is that we take ownership of the session
2116 // description regardless of the outcome, so wrap it in a unique_ptr right
2117 // away. Ideally, SetLocalDescription's signature will be changed to take the
2118 // description as a unique_ptr argument to formalize this agreement.
2119 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2120
nisse7ce109a2017-01-31 00:57:56 -08002121 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002122 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123 return;
2124 }
Steve Anton8a006912017-12-04 15:25:56 -08002125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002127 PostSetSessionDescriptionFailure(
2128 observer,
2129 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 return;
2131 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002132
Steve Anton80dd7b52018-02-16 17:08:42 -08002133 // If a session error has occurred the PeerConnection is in a possibly
2134 // inconsistent state so fail right away.
2135 if (session_error() != SessionError::kNone) {
2136 std::string error_message = GetSessionErrorMsg();
2137 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002138 PostSetSessionDescriptionFailure(
2139 observer,
2140 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002141 return;
2142 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002143
Steve Anton80dd7b52018-02-16 17:08:42 -08002144 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2145 if (!error.ok()) {
2146 std::string error_message = GetSetDescriptionErrorMessage(
2147 cricket::CS_LOCAL, desc->GetType(), error);
2148 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002149 PostSetSessionDescriptionFailure(
2150 observer,
2151 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002152 return;
2153 }
2154
2155 // Grab the description type before moving ownership to ApplyLocalDescription,
2156 // which may destroy it before returning.
2157 const SdpType type = desc->GetType();
2158
2159 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002160 // |desc| may be destroyed at this point.
2161
2162 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002163 // If ApplyLocalDescription fails, the PeerConnection could be in an
2164 // inconsistent state, so act conservatively here and set the session error
2165 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2166 SetSessionError(SessionError::kContent, error.message());
2167 std::string error_message =
2168 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2169 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002170 PostSetSessionDescriptionFailure(
2171 observer,
2172 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002173 return;
2174 }
Steve Anton8a006912017-12-04 15:25:56 -08002175 RTC_DCHECK(local_description());
2176
2177 PostSetSessionDescriptionSuccess(observer);
2178
Steve Antonad182762018-09-05 20:22:40 +00002179 // MaybeStartGathering needs to be called after posting
2180 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2181 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002182 transport_controller_->MaybeStartGathering();
2183
Steve Antona3a92c22017-12-07 10:27:41 -08002184 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002185 // TODO(deadbeef): We already had to hop to the network thread for
2186 // MaybeStartGathering...
2187 network_thread()->Invoke<void>(
2188 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2189 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002190 // Make UMA notes about what was agreed to.
2191 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002192 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002193
2194 if (IsUnifiedPlan()) {
2195 bool was_negotiation_needed = is_negotiation_needed_;
2196 UpdateNegotiationNeeded();
2197 if (signaling_state() == kStable && was_negotiation_needed &&
2198 is_negotiation_needed_) {
2199 Observer()->OnRenegotiationNeeded();
2200 }
2201 }
2202
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002203 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002204}
2205
2206RTCError PeerConnection::ApplyLocalDescription(
2207 std::unique_ptr<SessionDescriptionInterface> desc) {
2208 RTC_DCHECK_RUN_ON(signaling_thread());
2209 RTC_DCHECK(desc);
2210
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 // Update stats here so that we have the most recent stats for tracks and
2212 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002213 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Take a reference to the old local description since it's used below to
2216 // compare against the new local description. When setting the new local
2217 // description, grab ownership of the replaced session description in case it
2218 // is the same as |old_local_description|, to keep it alive for the duration
2219 // of the method.
2220 const SessionDescriptionInterface* old_local_description =
2221 local_description();
2222 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002223 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002224 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002225 replaced_local_description = pending_local_description_
2226 ? std::move(pending_local_description_)
2227 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002228 current_local_description_ = std::move(desc);
2229 pending_local_description_ = nullptr;
2230 current_remote_description_ = std::move(pending_remote_description_);
2231 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002232 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002233 pending_local_description_ = std::move(desc);
2234 }
2235 // The session description to apply now must be accessed by
2236 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002237 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002238
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002239 // Report statistics about any use of simulcast.
2240 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2241 *local_description()->description());
2242
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002243 if (!is_caller_) {
2244 if (remote_description()) {
2245 // Remote description was applied first, so this PC is the callee.
2246 is_caller_ = false;
2247 } else {
2248 // Local description is applied first, so this PC is the caller.
2249 is_caller_ = true;
2250 }
2251 }
2252
Zhi Huange830e682018-03-30 10:48:35 -07002253 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2254 if (!error.ok()) {
2255 return error;
2256 }
2257
Steve Antondcc3c022017-12-22 16:02:54 -08002258 if (IsUnifiedPlan()) {
2259 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002260 cricket::CS_LOCAL, *local_description(), old_local_description,
2261 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002262 if (!error.ok()) {
2263 return error;
2264 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002265 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2266 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002267 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002268 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2269 // Note that code paths that don't set MID won't be able to use
2270 // information about DTLS transports.
2271 if (transceiver->mid()) {
2272 auto dtls_transport =
2273 LookupDtlsTransportByMidInternal(*transceiver->mid());
2274 transceiver->internal()->sender_internal()->set_transport(
2275 dtls_transport);
2276 transceiver->internal()->receiver_internal()->set_transport(
2277 dtls_transport);
2278 }
2279
Steve Antondcc3c022017-12-22 16:02:54 -08002280 const ContentInfo* content =
2281 FindMediaSectionForTransceiver(transceiver, local_description());
2282 if (!content) {
2283 continue;
2284 }
2285 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002286 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2287 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002288 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002289 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2290 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2291 // "recvonly", process the removal of a remote track for the media
2292 // description, given transceiver, removeList, and muteTracks.
2293 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2294 (transceiver->internal()->fired_direction() &&
2295 RtpTransceiverDirectionHasRecv(
2296 *transceiver->internal()->fired_direction()))) {
2297 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2298 &removed_streams);
2299 }
2300 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2301 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002302 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002303 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002304 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002305 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002306 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002307 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002308 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002309 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002310 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002311 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002312 }
2313 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002314 // Media channels will be created only when offer is set. These may use new
2315 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002316 if (type == SdpType::kOffer) {
2317 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2318 // description is applied. Restore back to old description.
2319 RTCError error = CreateChannels(*local_description()->description());
2320 if (!error.ok()) {
2321 return error;
2322 }
2323 }
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // Remove unused channels if MediaContentDescription is rejected.
2325 RemoveUnusedChannels(local_description()->description());
2326 }
Steve Anton8a006912017-12-04 15:25:56 -08002327
Zhi Huange830e682018-03-30 10:48:35 -07002328 error = UpdateSessionState(type, cricket::CS_LOCAL,
2329 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002330 if (!error.ok()) {
2331 return error;
2332 }
Steve Antondcc3c022017-12-22 16:02:54 -08002333
Steve Anton8a006912017-12-04 15:25:56 -08002334 if (remote_description()) {
2335 // Now that we have a local description, we can push down remote candidates.
2336 UseCandidatesInSessionDescription(remote_description());
2337 }
2338
2339 pending_ice_restarts_.clear();
2340 if (session_error() != SessionError::kNone) {
2341 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2342 }
2343
deadbeefab9b2d12015-10-14 11:33:11 -07002344 // If setting the description decided our SSL role, allocate any necessary
2345 // SCTP sids.
2346 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002347 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002348 AllocateSctpSids(role);
2349 }
2350
Steve Antond3679212018-01-17 17:41:02 -08002351 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002352 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002353 const ContentInfo* content =
2354 FindMediaSectionForTransceiver(transceiver, local_description());
2355 if (!content) {
2356 continue;
2357 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002358 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2359 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002360 // 0 is a special value meaning "this sender has no associated send
2361 // stream". Need to call this so the sender won't attempt to configure
2362 // a no longer existing stream and run into DCHECKs in the lower
2363 // layers.
2364 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002365 } else {
2366 // Get the StreamParams from the channel which could generate SSRCs.
2367 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002368 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002369 streams[0].stream_ids());
2370 transceiver->internal()->sender_internal()->SetSsrc(
2371 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002372 }
2373 }
2374 } else {
2375 // Plan B semantics.
2376
Steve Antondcc3c022017-12-22 16:02:54 -08002377 // Update state and SSRC of local MediaStreams and DataChannels based on the
2378 // local session description.
2379 const cricket::ContentInfo* audio_content =
2380 GetFirstAudioContent(local_description()->description());
2381 if (audio_content) {
2382 if (audio_content->rejected) {
2383 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2384 } else {
2385 const cricket::AudioContentDescription* audio_desc =
2386 audio_content->media_description()->as_audio();
2387 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2388 }
deadbeeffaac4972015-11-12 15:33:07 -08002389 }
deadbeefab9b2d12015-10-14 11:33:11 -07002390
Steve Antondcc3c022017-12-22 16:02:54 -08002391 const cricket::ContentInfo* video_content =
2392 GetFirstVideoContent(local_description()->description());
2393 if (video_content) {
2394 if (video_content->rejected) {
2395 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2396 } else {
2397 const cricket::VideoContentDescription* video_desc =
2398 video_content->media_description()->as_video();
2399 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2400 }
deadbeeffaac4972015-11-12 15:33:07 -08002401 }
deadbeefab9b2d12015-10-14 11:33:11 -07002402 }
2403
2404 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002405 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002406 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002407 const cricket::RtpDataContentDescription* rtp_data_desc =
2408 data_content->media_description()->as_rtp_data();
2409 // rtp_data_desc will be null if this is an SCTP description.
2410 if (rtp_data_desc) {
2411 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002412 }
2413 }
2414
Steve Anton8a006912017-12-04 15:25:56 -08002415 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416}
2417
Steve Anton06817cd2018-12-18 15:55:30 -08002418// The SDP parser used to populate these values by default for the 'content
2419// name' if an a=mid line was absent.
2420static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2421 switch (media_type) {
2422 case cricket::MEDIA_TYPE_AUDIO:
2423 return cricket::CN_AUDIO;
2424 case cricket::MEDIA_TYPE_VIDEO:
2425 return cricket::CN_VIDEO;
2426 case cricket::MEDIA_TYPE_DATA:
2427 return cricket::CN_DATA;
2428 }
2429 RTC_NOTREACHED();
2430 return "";
2431}
2432
2433void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002434 cricket::SessionDescription* new_remote_description) {
2435 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002436 const cricket::ContentInfos& local_contents =
2437 (local_description() ? local_description()->description()->contents()
2438 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002439 const cricket::ContentInfos& remote_contents =
2440 (remote_description() ? remote_description()->description()->contents()
2441 : cricket::ContentInfos());
2442 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2443 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002444 if (!content.name.empty()) {
2445 continue;
2446 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002447 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002448 absl::string_view source_explanation;
2449 if (IsUnifiedPlan()) {
2450 if (i < local_contents.size()) {
2451 new_mid = local_contents[i].name;
2452 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002453 } else if (i < remote_contents.size()) {
2454 new_mid = remote_contents[i].name;
2455 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002456 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002457 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002458 source_explanation = "generated just now";
2459 }
2460 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002461 new_mid = std::string(
2462 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002463 source_explanation = "to match pre-existing behavior";
2464 }
Steve Antond7180cc2019-02-07 10:44:53 -08002465 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002466 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002467 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002468 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2469 << " is missing an a=mid line. Filling in the value '"
2470 << new_mid << "' " << source_explanation << ".";
2471 }
2472}
2473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002475 SetSessionDescriptionObserver* observer,
2476 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002477 SetRemoteDescription(
2478 std::unique_ptr<SessionDescriptionInterface>(desc),
2479 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2480 new SetRemoteDescriptionObserverAdapter(this, observer)));
2481}
2482
2483void PeerConnection::SetRemoteDescription(
2484 std::unique_ptr<SessionDescriptionInterface> desc,
2485 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002486 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002487 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002488
nisse7ce109a2017-01-31 00:57:56 -08002489 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002490 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002491 return;
2492 }
Steve Anton8a006912017-12-04 15:25:56 -08002493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002495 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002496 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 return;
2498 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002499
Steve Anton80dd7b52018-02-16 17:08:42 -08002500 // If a session error has occurred the PeerConnection is in a possibly
2501 // inconsistent state so fail right away.
2502 if (session_error() != SessionError::kNone) {
2503 std::string error_message = GetSessionErrorMsg();
2504 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2505 observer->OnSetRemoteDescriptionComplete(
2506 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2507 return;
2508 }
Steve Anton71439a62018-02-15 11:53:06 -08002509
Steve Antonba42e992018-04-09 14:10:01 -07002510 if (desc->GetType() == SdpType::kOffer) {
2511 // Report to UMA the format of the received offer.
2512 ReportSdpFormatReceived(*desc);
2513 }
2514
Steve Anton06817cd2018-12-18 15:55:30 -08002515 // Handle remote descriptions missing a=mid lines for interop with legacy end
2516 // points.
2517 FillInMissingRemoteMids(desc->description());
2518
Steve Anton80dd7b52018-02-16 17:08:42 -08002519 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002520 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002521 std::string error_message = GetSetDescriptionErrorMessage(
2522 cricket::CS_REMOTE, desc->GetType(), error);
2523 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002524 observer->OnSetRemoteDescriptionComplete(
2525 RTCError(error.type(), std::move(error_message)));
2526 return;
2527 }
Steve Anton71439a62018-02-15 11:53:06 -08002528
Steve Anton80dd7b52018-02-16 17:08:42 -08002529 // Grab the description type before moving ownership to
2530 // ApplyRemoteDescription, which may destroy it before returning.
2531 const SdpType type = desc->GetType();
2532
2533 error = ApplyRemoteDescription(std::move(desc));
2534 // |desc| may be destroyed at this point.
2535
2536 if (!error.ok()) {
2537 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2538 // inconsistent state, so act conservatively here and set the session error
2539 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2540 SetSessionError(SessionError::kContent, error.message());
2541 std::string error_message =
2542 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2543 RTC_LOG(LS_ERROR) << error_message;
2544 observer->OnSetRemoteDescriptionComplete(
2545 RTCError(error.type(), std::move(error_message)));
2546 return;
2547 }
2548 RTC_DCHECK(remote_description());
2549
2550 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002551 // TODO(deadbeef): We already had to hop to the network thread for
2552 // MaybeStartGathering...
2553 network_thread()->Invoke<void>(
2554 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2555 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002556 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002557 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002558 }
2559
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002560 if (IsUnifiedPlan()) {
2561 bool was_negotiation_needed = is_negotiation_needed_;
2562 UpdateNegotiationNeeded();
2563 if (signaling_state() == kStable && was_negotiation_needed &&
2564 is_negotiation_needed_) {
2565 Observer()->OnRenegotiationNeeded();
2566 }
2567 }
2568
Steve Anton8a006912017-12-04 15:25:56 -08002569 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002570 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002571}
2572
2573RTCError PeerConnection::ApplyRemoteDescription(
2574 std::unique_ptr<SessionDescriptionInterface> desc) {
2575 RTC_DCHECK_RUN_ON(signaling_thread());
2576 RTC_DCHECK(desc);
2577
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 // Update stats here so that we have the most recent stats for tracks and
2579 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002580 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002581
Steve Antondcc3c022017-12-22 16:02:54 -08002582 // Take a reference to the old remote description since it's used below to
2583 // compare against the new remote description. When setting the new remote
2584 // description, grab ownership of the replaced session description in case it
2585 // is the same as |old_remote_description|, to keep it alive for the duration
2586 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002587 const SessionDescriptionInterface* old_remote_description =
2588 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002589 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002590 SdpType type = desc->GetType();
2591 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002592 replaced_remote_description = pending_remote_description_
2593 ? std::move(pending_remote_description_)
2594 : std::move(current_remote_description_);
2595 current_remote_description_ = std::move(desc);
2596 pending_remote_description_ = nullptr;
2597 current_local_description_ = std::move(pending_local_description_);
2598 } else {
2599 replaced_remote_description = std::move(pending_remote_description_);
2600 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 }
Steve Anton8a006912017-12-04 15:25:56 -08002602 // The session description to apply now must be accessed by
2603 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002604 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002605
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002606 // Report statistics about any use of simulcast.
2607 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2608 *remote_description()->description());
2609
Zhi Huange830e682018-03-30 10:48:35 -07002610 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2611 if (!error.ok()) {
2612 return error;
2613 }
Steve Anton8a006912017-12-04 15:25:56 -08002614 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002615 if (IsUnifiedPlan()) {
2616 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002617 cricket::CS_REMOTE, *remote_description(), local_description(),
2618 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002619 if (!error.ok()) {
2620 return error;
2621 }
Steve Antondcc3c022017-12-22 16:02:54 -08002622 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002623 // Media channels will be created only when offer is set. These may use new
2624 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002625 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002626 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002627 // description is applied. Restore back to old description.
2628 RTCError error = CreateChannels(*remote_description()->description());
2629 if (!error.ok()) {
2630 return error;
2631 }
2632 }
Steve Antondcc3c022017-12-22 16:02:54 -08002633 // Remove unused channels if MediaContentDescription is rejected.
2634 RemoveUnusedChannels(remote_description()->description());
2635 }
Steve Anton8a006912017-12-04 15:25:56 -08002636
Zhi Huange830e682018-03-30 10:48:35 -07002637 // NOTE: Candidates allocation will be initiated only when
2638 // SetLocalDescription is called.
2639 error = UpdateSessionState(type, cricket::CS_REMOTE,
2640 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002641 if (!error.ok()) {
2642 return error;
2643 }
2644
2645 if (local_description() &&
2646 !UseCandidatesInSessionDescription(remote_description())) {
2647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2648 }
2649
2650 if (old_remote_description) {
2651 for (const cricket::ContentInfo& content :
2652 old_remote_description->description()->contents()) {
2653 // Check if this new SessionDescription contains new ICE ufrag and
2654 // password that indicates the remote peer requests an ICE restart.
2655 // TODO(deadbeef): When we start storing both the current and pending
2656 // remote description, this should reset pending_ice_restarts and compare
2657 // against the current description.
2658 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2659 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002660 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002661 pending_ice_restarts_.insert(content.name);
2662 }
2663 } else {
2664 // We retain all received candidates only if ICE is not restarted.
2665 // When ICE is restarted, all previous candidates belong to an old
2666 // generation and should not be kept.
2667 // TODO(deadbeef): This goes against the W3C spec which says the remote
2668 // description should only contain candidates from the last set remote
2669 // description plus any candidates added since then. We should remove
2670 // this once we're sure it won't break anything.
2671 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2672 old_remote_description, content.name, mutable_remote_description());
2673 }
2674 }
2675 }
2676
2677 if (session_error() != SessionError::kNone) {
2678 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2679 }
2680
2681 // Set the the ICE connection state to connecting since the connection may
2682 // become writable with peer reflexive candidates before any remote candidate
2683 // is signaled.
2684 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2685 // is to have a new signal the indicates a change in checking state from the
2686 // transport and expose a new checking() member from transport that can be
2687 // read to determine the current checking state. The existing SignalConnecting
2688 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002689 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002690 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002691 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2692 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2693 }
2694
deadbeefab9b2d12015-10-14 11:33:11 -07002695 // If setting the description decided our SSL role, allocate any necessary
2696 // SCTP sids.
2697 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002698 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002699 AllocateSctpSids(role);
2700 }
2701
Steve Antondcc3c022017-12-22 16:02:54 -08002702 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002703 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002704 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002705 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002706 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002707 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002708 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002709 const ContentInfo* content =
2710 FindMediaSectionForTransceiver(transceiver, remote_description());
2711 if (!content) {
2712 continue;
2713 }
2714 const MediaContentDescription* media_desc = content->media_description();
2715 RtpTransceiverDirection local_direction =
2716 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002717 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2718 // RTCSessionDescription: Set the associated remote streams given
2719 // transceiver.[[Receiver]], msids, addList, and removeList".
2720 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2721 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2722 std::vector<std::string> stream_ids;
2723 if (!media_desc->streams().empty()) {
2724 // The remote description has signaled the stream IDs.
2725 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002726 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002727 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2728 << " (" << GetStreamIdsString(stream_ids) << ").";
2729 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2730 stream_ids, &added_streams,
2731 &removed_streams);
2732 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2733 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2734 // and transceiver's current direction is neither sendrecv nor recvonly,
2735 // process the addition of a remote track for the media description.
2736 if (!transceiver->fired_direction() ||
2737 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2738 RTC_LOG(LS_INFO)
2739 << "Processing the addition of a remote track for MID="
2740 << content->name << ".";
2741 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002742 }
Steve Antondcc3c022017-12-22 16:02:54 -08002743 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002744 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002745 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2746 // removal of a remote track for the media description, given transceiver,
2747 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002748 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002749 (transceiver->fired_direction() &&
2750 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2751 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2752 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002753 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002754 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002755 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002756 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002757 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002758 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002759 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002760 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002761 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2763 if (transceiver->mid()) {
2764 auto dtls_transport =
2765 LookupDtlsTransportByMidInternal(*transceiver->mid());
2766 transceiver->internal()->sender_internal()->set_transport(
2767 dtls_transport);
2768 transceiver->internal()->receiver_internal()->set_transport(
2769 dtls_transport);
2770 }
Steve Antondcc3c022017-12-22 16:02:54 -08002771 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002772 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002773 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002774 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002775 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2776 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002777 transceiver->Stop();
2778 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002779 if (!content->rejected &&
2780 RtpTransceiverDirectionHasRecv(local_direction)) {
2781 // Set ssrc to 0 in the case of an unsignalled ssrc.
2782 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002783 if (!media_desc->streams().empty() &&
2784 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002785 ssrc = media_desc->streams()[0].first_ssrc();
2786 }
2787 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002788 }
Steve Antondcc3c022017-12-22 16:02:54 -08002789 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002790 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002791 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002792 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002793 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002794 observer->OnTrack(transceiver);
2795 observer->OnAddTrack(transceiver->receiver(),
2796 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002797 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002798 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002799 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002800 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002801 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002802 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002803 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002804 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002805 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002806 }
Steve Antondcc3c022017-12-22 16:02:54 -08002807 }
2808
Henrik Boströmfdb92012017-11-09 19:55:44 +01002809 const cricket::ContentInfo* audio_content =
2810 GetFirstAudioContent(remote_description()->description());
2811 const cricket::ContentInfo* video_content =
2812 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002813 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002814 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002815 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002816 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002817 const cricket::RtpDataContentDescription* rtp_data_desc =
2818 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002819
2820 // Check if the descriptions include streams, just in case the peer supports
2821 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002822 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002823 (audio_desc && !audio_desc->streams().empty()) ||
2824 (video_desc && !video_desc->streams().empty())) {
2825 remote_peer_supports_msid_ = true;
2826 }
deadbeefab9b2d12015-10-14 11:33:11 -07002827
2828 // We wait to signal new streams until we finish processing the description,
2829 // since only at that point will new streams have all their tracks.
2830 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2831
Steve Antondcc3c022017-12-22 16:02:54 -08002832 if (!IsUnifiedPlan()) {
2833 // TODO(steveanton): When removing RTP senders/receivers in response to a
2834 // rejected media section, there is some cleanup logic that expects the
2835 // voice/ video channel to still be set. But in this method the voice/video
2836 // channel would have been destroyed by the SetRemoteDescription caller
2837 // above so the cleanup that relies on them fails to run. The RemoveSenders
2838 // calls should be moved to right before the DestroyChannel calls to fix
2839 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002840
Steve Antondcc3c022017-12-22 16:02:54 -08002841 // Find all audio rtp streams and create corresponding remote AudioTracks
2842 // and MediaStreams.
2843 if (audio_content) {
2844 if (audio_content->rejected) {
2845 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2846 } else {
2847 bool default_audio_track_needed =
2848 !remote_peer_supports_msid_ &&
2849 RtpTransceiverDirectionHasSend(audio_desc->direction());
2850 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2851 default_audio_track_needed, audio_desc->type(),
2852 new_streams);
2853 }
deadbeeffaac4972015-11-12 15:33:07 -08002854 }
deadbeefab9b2d12015-10-14 11:33:11 -07002855
Steve Antondcc3c022017-12-22 16:02:54 -08002856 // Find all video rtp streams and create corresponding remote VideoTracks
2857 // and MediaStreams.
2858 if (video_content) {
2859 if (video_content->rejected) {
2860 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2861 } else {
2862 bool default_video_track_needed =
2863 !remote_peer_supports_msid_ &&
2864 RtpTransceiverDirectionHasSend(video_desc->direction());
2865 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2866 default_video_track_needed, video_desc->type(),
2867 new_streams);
2868 }
deadbeeffaac4972015-11-12 15:33:07 -08002869 }
deadbeefab9b2d12015-10-14 11:33:11 -07002870
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002871 // If this is an RTP data transport, update the DataChannels with the
2872 // information from the remote peer.
2873 if (rtp_data_desc) {
2874 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002875 }
deadbeefab9b2d12015-10-14 11:33:11 -07002876
Steve Antondcc3c022017-12-22 16:02:54 -08002877 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002878 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002879 for (size_t i = 0; i < new_streams->count(); ++i) {
2880 MediaStreamInterface* new_stream = new_streams->at(i);
2881 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002882 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002883 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2884 }
deadbeefab9b2d12015-10-14 11:33:11 -07002885
Steve Antondcc3c022017-12-22 16:02:54 -08002886 UpdateEndedRemoteMediaStreams();
2887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888
Steve Anton8a006912017-12-04 15:25:56 -08002889 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002890}
2891
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002892void PeerConnection::SetAssociatedRemoteStreams(
2893 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2894 const std::vector<std::string>& stream_ids,
2895 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2896 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2897 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2898 for (const std::string& stream_id : stream_ids) {
2899 rtc::scoped_refptr<MediaStreamInterface> stream =
2900 remote_streams_->find(stream_id);
2901 if (!stream) {
2902 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2903 MediaStream::Create(stream_id));
2904 remote_streams_->AddStream(stream);
2905 added_streams->push_back(stream);
2906 }
2907 media_streams.push_back(stream);
2908 }
2909 // Special case: "a=msid" missing, use random stream ID.
2910 if (media_streams.empty() &&
2911 !(remote_description()->description()->msid_signaling() &
2912 cricket::kMsidSignalingMediaSection)) {
2913 if (!missing_msid_default_stream_) {
2914 missing_msid_default_stream_ = MediaStreamProxy::Create(
2915 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2916 added_streams->push_back(missing_msid_default_stream_);
2917 }
2918 media_streams.push_back(missing_msid_default_stream_);
2919 }
2920 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2921 receiver->streams();
2922 // SetStreams() will add/remove the receiver's track to/from the streams. This
2923 // differs from the spec - the spec uses an "addList" and "removeList" to
2924 // update the stream-track relationships in a later step. We do this earlier,
2925 // changing the order of things, but the end-result is the same.
2926 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2927 // instead. https://crbug.com/webrtc/9480
2928 receiver->SetStreams(media_streams);
2929 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2930}
2931
Steve Anton0f5400a2018-07-17 14:25:36 -07002932void PeerConnection::ProcessRemovalOfRemoteTrack(
2933 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2934 transceiver,
2935 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2936 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2937 RTC_DCHECK(transceiver->mid());
2938 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2939 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002940 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002941 transceiver->internal()->receiver_internal()->streams();
2942 // This will remove the remote track from the streams.
2943 transceiver->internal()->receiver_internal()->set_stream_ids({});
2944 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002945 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2946}
2947
2948void PeerConnection::RemoveRemoteStreamsIfEmpty(
2949 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2950 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2951 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2952 // streams, see if the stream was removed by checking if this was the last
2953 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002954 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002955 if (remote_stream->GetAudioTracks().empty() &&
2956 remote_stream->GetVideoTracks().empty()) {
2957 remote_streams_->RemoveStream(remote_stream);
2958 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002959 }
2960 }
2961}
2962
Steve Antondcc3c022017-12-22 16:02:54 -08002963RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2964 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002965 const SessionDescriptionInterface& new_session,
2966 const SessionDescriptionInterface* old_local_description,
2967 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002968 RTC_DCHECK(IsUnifiedPlan());
2969
Steve Anton7464fca2018-01-19 11:10:37 -08002970 const cricket::ContentGroup* bundle_group = nullptr;
2971 if (new_session.GetType() == SdpType::kOffer) {
2972 auto bundle_group_or_error =
2973 GetEarlyBundleGroup(*new_session.description());
2974 if (!bundle_group_or_error.ok()) {
2975 return bundle_group_or_error.MoveError();
2976 }
2977 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002978 }
Steve Antondcc3c022017-12-22 16:02:54 -08002979
Steve Antondcc3c022017-12-22 16:02:54 -08002980 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002981 for (size_t i = 0; i < new_contents.size(); ++i) {
2982 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002983 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002984 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002985 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2986 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002987 const cricket::ContentInfo* old_local_content = nullptr;
2988 if (old_local_description &&
2989 i < old_local_description->description()->contents().size()) {
2990 old_local_content =
2991 &old_local_description->description()->contents()[i];
2992 }
2993 const cricket::ContentInfo* old_remote_content = nullptr;
2994 if (old_remote_description &&
2995 i < old_remote_description->description()->contents().size()) {
2996 old_remote_content =
2997 &old_remote_description->description()->contents()[i];
2998 }
Steve Antondcc3c022017-12-22 16:02:54 -08002999 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003000 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3001 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003002 if (!transceiver_or_error.ok()) {
3003 return transceiver_or_error.MoveError();
3004 }
3005 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003006 RTCError error =
3007 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3008 if (!error.ok()) {
3009 return error;
3010 }
3011 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003012 if (GetDataMid() && new_content.name != *GetDataMid()) {
3013 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003014 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3015 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003016 continue;
3017 }
3018 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3019 if (!error.ok()) {
3020 return error;
3021 }
Steve Antondcc3c022017-12-22 16:02:54 -08003022 } else {
3023 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3024 "Unknown section type.");
3025 }
3026 }
3027
3028 return RTCError::OK();
3029}
3030
3031RTCError PeerConnection::UpdateTransceiverChannel(
3032 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3033 transceiver,
3034 const cricket::ContentInfo& content,
3035 const cricket::ContentGroup* bundle_group) {
3036 RTC_DCHECK(IsUnifiedPlan());
3037 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003038 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003039 if (content.rejected) {
3040 if (channel) {
3041 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003042 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003043 }
3044 } else {
3045 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003046 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003047 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003048 } else {
Steve Anton69470252018-02-09 11:43:08 -08003049 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003050 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003051 }
3052 if (!channel) {
3053 LOG_AND_RETURN_ERROR(
3054 RTCErrorType::INTERNAL_ERROR,
3055 "Failed to create channel for mid=" + content.name);
3056 }
3057 transceiver->internal()->SetChannel(channel);
3058 }
3059 }
3060 return RTCError::OK();
3061}
3062
Steve Antonfa2260d2017-12-28 16:38:23 -08003063RTCError PeerConnection::UpdateDataChannel(
3064 cricket::ContentSource source,
3065 const cricket::ContentInfo& content,
3066 const cricket::ContentGroup* bundle_group) {
3067 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003068 // If data channels are disabled, ignore this media section. CreateAnswer
3069 // will take care of rejecting it.
3070 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003071 }
3072 if (content.rejected) {
3073 DestroyDataChannel();
3074 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003075 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003076 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003077 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3078 "Failed to create data channel.");
3079 }
3080 }
3081 if (source == cricket::CS_REMOTE) {
3082 const MediaContentDescription* data_desc = content.media_description();
3083 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3084 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3085 }
3086 }
3087 }
3088 return RTCError::OK();
3089}
3090
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003091// This method will extract any send encodings that were sent by the remote
3092// connection. This is currently only relevant for Simulcast scenario (where
3093// the number of layers may be communicated by the server).
3094static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3095 const MediaContentDescription& desc) {
3096 if (!desc.HasSimulcast()) {
3097 return {};
3098 }
3099 std::vector<RtpEncodingParameters> result;
3100 const SimulcastDescription& simulcast = desc.simulcast_description();
3101
3102 // This is a remote description, the parameters we are after should appear
3103 // as receive streams.
3104 for (const auto& alternatives : simulcast.receive_layers()) {
3105 RTC_DCHECK(!alternatives.empty());
3106 // There is currently no way to specify or choose from alternatives.
3107 // We will always use the first alternative, which is the most preferred.
3108 const SimulcastLayer& layer = alternatives[0];
3109 RtpEncodingParameters parameters;
3110 parameters.rid = layer.rid;
3111 parameters.active = !layer.is_paused;
3112 result.push_back(parameters);
3113 }
3114
3115 return result;
3116}
3117
3118static RTCError UpdateSimulcastLayerStatusInSender(
3119 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003120 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003121 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003122 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003123 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003124
3125 // The simulcast envelope cannot be changed, only the status of the streams.
3126 // So we will iterate over the send encodings rather than the layers.
3127 for (RtpEncodingParameters& encoding : parameters.encodings) {
3128 auto iter = std::find_if(layers.begin(), layers.end(),
3129 [&encoding](const SimulcastLayer& layer) {
3130 return layer.rid == encoding.rid;
3131 });
3132 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003133 if (iter == layers.end()) {
3134 disabled_layers.push_back(encoding.rid);
3135 continue;
3136 }
3137
3138 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003139 }
3140
Amit Hilbuch619b2942019-02-26 15:55:19 -08003141 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003142 if (result.ok()) {
3143 result = sender->DisableEncodingLayers(disabled_layers);
3144 }
3145
3146 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003147}
3148
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003149static bool SimulcastIsRejected(
3150 const ContentInfo* local_content,
3151 const MediaContentDescription& answer_media_desc) {
3152 bool simulcast_offered = local_content &&
3153 local_content->media_description() &&
3154 local_content->media_description()->HasSimulcast();
3155 bool simulcast_answered = answer_media_desc.HasSimulcast();
3156 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3157 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3158 return simulcast_offered && (!simulcast_answered || !rids_supported);
3159}
3160
Amit Hilbuch2297d332019-02-19 12:49:22 -08003161static RTCError DisableSimulcastInSender(
3162 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003163 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003164 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003165 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003166 return RTCError::OK();
3167 }
3168
Amit Hilbuch2297d332019-02-19 12:49:22 -08003169 std::vector<std::string> disabled_layers;
3170 std::transform(
3171 parameters.encodings.begin() + 1, parameters.encodings.end(),
3172 std::back_inserter(disabled_layers),
3173 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3174 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003175}
3176
Steve Antondcc3c022017-12-22 16:02:54 -08003177RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3178PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003179 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003180 size_t mline_index,
3181 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003182 const ContentInfo* old_local_content,
3183 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003184 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003185 // If this is an offer then the m= section might be recycled. If the m=
3186 // section is being recycled (defined as: rejected in the current local or
3187 // remote description and not rejected in new description), dissociate the
3188 // currently associated RtpTransceiver by setting its mid property to null,
3189 // and discard the mapping between the transceiver and its m= section index.
3190 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3191 old_remote_content)) {
3192 // We want to dissociate the transceiver that has the rejected mid.
3193 const std::string& old_mid =
3194 (old_local_content && old_local_content->rejected)
3195 ? old_local_content->name
3196 : old_remote_content->name;
3197 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003198 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003199 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3200 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003201 old_transceiver->internal()->set_mid(absl::nullopt);
3202 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003203 }
3204 }
3205 const MediaContentDescription* media_desc = content.media_description();
3206 auto transceiver = GetAssociatedTransceiver(content.name);
3207 if (source == cricket::CS_LOCAL) {
3208 // Find the RtpTransceiver that corresponds to this m= section, using the
3209 // mapping between transceivers and m= section indices established when
3210 // creating the offer.
3211 if (!transceiver) {
3212 transceiver = GetTransceiverByMLineIndex(mline_index);
3213 }
3214 if (!transceiver) {
3215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3216 "Unknown transceiver");
3217 }
3218 } else {
3219 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3220 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3221 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003222 // When simulcast is requested, a transceiver cannot be associated because
3223 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003224 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003225 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3226 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003227 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3228 }
3229 // If no RtpTransceiver was found in the previous step, create one with a
3230 // recvonly direction.
3231 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003232 RTC_LOG(LS_INFO) << "Adding "
3233 << cricket::MediaTypeToString(media_desc->type())
3234 << " transceiver for MID=" << content.name
3235 << " at i=" << mline_index
3236 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003237 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003238 std::vector<RtpEncodingParameters> send_encodings =
3239 GetSendEncodingsFromRemoteDescription(*media_desc);
3240 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3241 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003242 std::string receiver_id;
3243 if (!media_desc->streams().empty()) {
3244 receiver_id = media_desc->streams()[0].id;
3245 } else {
3246 receiver_id = rtc::CreateRandomUuid();
3247 }
3248 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003249 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003250 transceiver->internal()->set_direction(
3251 RtpTransceiverDirection::kRecvOnly);
3252 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003253
3254 // Check if the offer indicated simulcast but the answer rejected it.
3255 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003256 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003257 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003258 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003259 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003260 if (!error.ok()) {
3261 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3262 return std::move(error);
3263 }
3264 }
Steve Antondcc3c022017-12-22 16:02:54 -08003265 }
3266 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003267 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003268 LOG_AND_RETURN_ERROR(
3269 RTCErrorType::INVALID_PARAMETER,
3270 "Transceiver type does not match media description type.");
3271 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003272 if (media_desc->HasSimulcast()) {
3273 std::vector<SimulcastLayer> layers =
3274 source == cricket::CS_LOCAL
3275 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3276 : media_desc->simulcast_description()
3277 .receive_layers()
3278 .GetAllLayers();
3279 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003280 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003281 if (!error.ok()) {
3282 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3283 return std::move(error);
3284 }
3285 }
Steve Antondcc3c022017-12-22 16:02:54 -08003286 // Associate the found or created RtpTransceiver with the m= section by
3287 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3288 // section, and establish a mapping between the transceiver and the index of
3289 // the m= section.
3290 transceiver->internal()->set_mid(content.name);
3291 transceiver->internal()->set_mline_index(mline_index);
3292 return std::move(transceiver);
3293}
3294
3295rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3296PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3297 RTC_DCHECK(IsUnifiedPlan());
3298 for (auto transceiver : transceivers_) {
3299 if (transceiver->mid() == mid) {
3300 return transceiver;
3301 }
3302 }
3303 return nullptr;
3304}
3305
3306rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3307PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3308 RTC_DCHECK(IsUnifiedPlan());
3309 for (auto transceiver : transceivers_) {
3310 if (transceiver->internal()->mline_index() == mline_index) {
3311 return transceiver;
3312 }
3313 }
3314 return nullptr;
3315}
3316
3317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3318PeerConnection::FindAvailableTransceiverToReceive(
3319 cricket::MediaType media_type) const {
3320 RTC_DCHECK(IsUnifiedPlan());
3321 // From JSEP section 5.10 (Applying a Remote Description):
3322 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3323 // the same type that were added to the PeerConnection by addTrack and are not
3324 // associated with any m= section and are not stopped, find the first such
3325 // RtpTransceiver.
3326 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003327 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003328 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3329 !transceiver->stopped()) {
3330 return transceiver;
3331 }
3332 }
3333 return nullptr;
3334}
3335
Steve Antoned10bd92017-12-05 10:52:59 -08003336const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3337 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3338 transceiver,
3339 const SessionDescriptionInterface* sdesc) const {
3340 RTC_DCHECK(transceiver);
3341 RTC_DCHECK(sdesc);
3342 if (IsUnifiedPlan()) {
3343 if (!transceiver->internal()->mid()) {
3344 // This transceiver is not associated with a media section yet.
3345 return nullptr;
3346 }
3347 return sdesc->description()->GetContentByName(
3348 *transceiver->internal()->mid());
3349 } else {
3350 // Plan B only allows at most one audio and one video section, so use the
3351 // first media section of that type.
3352 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003353 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003354 }
3355}
3356
deadbeef46c73892016-11-16 19:42:04 -08003357PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003358 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003359 return configuration_;
3360}
3361
deadbeef293e9262017-01-11 12:28:30 -08003362bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3363 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003364 RTC_DCHECK_RUN_ON(signaling_thread());
3365 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003366 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003367 if (IsClosed()) {
3368 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3369 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3370 }
3371
Qingsi Wanga2d60672018-04-11 16:57:45 -07003372 // According to JSEP, after setLocalDescription, changing the candidate pool
3373 // size is not allowed, and changing the set of ICE servers will not result
3374 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003375 if (local_description() && configuration.ice_candidate_pool_size !=
3376 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003377 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3378 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003379 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003380 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003381
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003382 if (local_description() &&
3383 configuration.use_media_transport != configuration_.use_media_transport) {
3384 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3385 "SetLocalDescription.";
3386 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3387 }
3388
3389 if (remote_description() &&
3390 configuration.use_media_transport != configuration_.use_media_transport) {
3391 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3392 "SetRemoteDescription.";
3393 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3394 }
3395
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003396 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003397 configuration.use_media_transport_for_data_channels !=
3398 configuration_.use_media_transport_for_data_channels) {
3399 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3400 "after calling SetLocalDescription.";
3401 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3402 }
3403
3404 if (remote_description() &&
3405 configuration.use_media_transport_for_data_channels !=
3406 configuration_.use_media_transport_for_data_channels) {
3407 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3408 "after calling SetRemoteDescription.";
3409 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3410 }
3411
3412 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003413 configuration.crypto_options != configuration_.crypto_options) {
3414 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3415 "SetLocalDescription.";
3416 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3417 }
3418
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003419 if (local_description() && configuration.use_datagram_transport !=
3420 configuration_.use_datagram_transport) {
3421 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3422 "after calling SetLocalDescription.";
3423 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3424 }
3425
3426 if (remote_description() && configuration.use_datagram_transport !=
3427 configuration_.use_datagram_transport) {
3428 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3429 "after calling SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003433 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003434 configuration.use_media_transport ||
3435 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003436 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3437 << "Media transport requires MaxBundle policy.";
3438 }
3439
deadbeef293e9262017-01-11 12:28:30 -08003440 // The simplest (and most future-compatible) way to tell if the config was
3441 // modified in an invalid way is to copy each property we do support
3442 // modifying, then use operator==. There are far more properties we don't
3443 // support modifying than those we do, and more could be added.
3444 RTCConfiguration modified_config = configuration_;
3445 modified_config.servers = configuration.servers;
3446 modified_config.type = configuration.type;
3447 modified_config.ice_candidate_pool_size =
3448 configuration.ice_candidate_pool_size;
3449 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003450 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003451 modified_config.ice_check_interval_strong_connectivity =
3452 configuration.ice_check_interval_strong_connectivity;
3453 modified_config.ice_check_interval_weak_connectivity =
3454 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003455 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3456 modified_config.ice_unwritable_min_checks =
3457 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003458 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003459 modified_config.stun_candidate_keepalive_interval =
3460 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003461 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003462 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003463 modified_config.active_reset_srtp_params =
3464 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003465 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003466 modified_config.use_media_transport_for_data_channels =
3467 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003468 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003469 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003470 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3471 }
3472
Steve Anton038834f2017-07-14 15:59:59 -07003473 // Validate the modified configuration.
3474 RTCError validate_error = ValidateConfiguration(modified_config);
3475 if (!validate_error.ok()) {
3476 return SafeSetError(std::move(validate_error), error);
3477 }
3478
deadbeef293e9262017-01-11 12:28:30 -08003479 // Note that this isn't possible through chromium, since it's an unsigned
3480 // short in WebIDL.
3481 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003482 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003483 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3484 }
3485
3486 // Parse ICE servers before hopping to network thread.
3487 cricket::ServerAddresses stun_servers;
3488 std::vector<cricket::RelayServerConfig> turn_servers;
3489 RTCErrorType parse_error =
3490 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3491 if (parse_error != RTCErrorType::NONE) {
3492 return SafeSetError(parse_error, error);
3493 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003494 // Note if STUN or TURN servers were supplied.
3495 if (!stun_servers.empty()) {
3496 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3497 }
3498 if (!turn_servers.empty()) {
3499 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3500 }
deadbeef293e9262017-01-11 12:28:30 -08003501
3502 // In theory this shouldn't fail.
3503 if (!network_thread()->Invoke<bool>(
3504 RTC_FROM_HERE,
3505 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3506 stun_servers, turn_servers, modified_config.type,
3507 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003508 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003509 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003510 modified_config.stun_candidate_keepalive_interval,
3511 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003513 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3514 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003515
deadbeefd1a38b52016-12-10 13:15:33 -08003516 // As described in JSEP, calling setConfiguration with new ICE servers or
3517 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3518 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003519 if (modified_config.servers != configuration_.servers ||
3520 modified_config.type != configuration_.type ||
3521 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003522 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003523 }
skvladd1f5fda2017-02-03 16:54:05 -08003524
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003525 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003526 transport_controller_->SetMediaTransportSettings(
3527 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003528 modified_config.use_media_transport_for_data_channels,
3529 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003530
Zhi Huangb57e1692018-06-12 11:41:11 -07003531 if (configuration_.active_reset_srtp_params !=
3532 modified_config.active_reset_srtp_params) {
3533 transport_controller_->SetActiveResetSrtpParams(
3534 modified_config.active_reset_srtp_params);
3535 }
3536
deadbeef293e9262017-01-11 12:28:30 -08003537 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003538 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003539 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003540}
3541
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003542bool PeerConnection::AddIceCandidate(
3543 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003544 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003545 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003546 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003547 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003548 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003549 return false;
3550 }
Steve Antond25da372017-11-06 14:50:29 -08003551
3552 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003553 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003554 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003555 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003556 return false;
3557 }
3558
3559 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003560 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003561 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003562 return false;
3563 }
3564
3565 bool valid = false;
3566 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3567 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003568 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003569 return false;
3570 }
3571
3572 // Add this candidate to the remote session description.
3573 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003574 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003575 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003576 return false;
3577 }
3578
3579 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003580 bool result = UseCandidate(ice_candidate);
3581 if (result) {
3582 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003583 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3584 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3585 }
3586 if (ice_candidate->candidate().address().IsPrivateIP()) {
3587 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3588 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003589 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3590 } else {
3591 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3592 }
3593 return result;
Steve Antond25da372017-11-06 14:50:29 -08003594 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003595 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003596 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003597 return true;
3598 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003599}
3600
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003601bool PeerConnection::RemoveIceCandidates(
3602 const std::vector<cricket::Candidate>& candidates) {
3603 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003604 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003605 if (IsClosed()) {
3606 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3607 return false;
3608 }
3609
Steve Antond25da372017-11-06 14:50:29 -08003610 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003611 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3612 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003613 return false;
3614 }
3615
3616 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003617 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003618 return false;
3619 }
3620
3621 size_t number_removed =
3622 mutable_remote_description()->RemoveCandidates(candidates);
3623 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003624 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003625 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003626 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003627 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003628 }
3629
3630 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003631 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3632 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003633 RTC_LOG(LS_ERROR)
3634 << "RemoveIceCandidates: Error when removing remote candidates: "
3635 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003636 }
3637 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003638}
3639
Niels Möller0c4f7be2018-05-07 14:01:37 +02003640RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003641 if (!worker_thread()->IsCurrent()) {
3642 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003643 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003644 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003645 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003646
Niels Möller0c4f7be2018-05-07 14:01:37 +02003647 const bool has_min = bitrate.min_bitrate_bps.has_value();
3648 const bool has_start = bitrate.start_bitrate_bps.has_value();
3649 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003650 if (has_min && *bitrate.min_bitrate_bps < 0) {
3651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3652 "min_bitrate_bps <= 0");
3653 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003654 if (has_start) {
3655 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003657 "start_bitrate_bps < min_bitrate_bps");
3658 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003659 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3660 "curent_bitrate_bps < 0");
3661 }
3662 }
3663 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003664 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003666 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003667 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3668 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3669 "max_bitrate_bps < min_bitrate_bps");
3670 } else if (*bitrate.max_bitrate_bps < 0) {
3671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3672 "max_bitrate_bps < 0");
3673 }
3674 }
3675
zstein4b979802017-06-02 14:37:37 -07003676 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003677 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003678
3679 return RTCError::OK();
3680}
3681
Alex Narest78609d52017-10-20 10:37:47 +02003682void PeerConnection::SetBitrateAllocationStrategy(
3683 std::unique_ptr<rtc::BitrateAllocationStrategy>
3684 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003685 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003686 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3687 // move-capture values in lambdas.
3688 struct Task {
3689 PeerConnection* const pc;
3690 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3691 void operator()() {
3692 RTC_DCHECK_RUN_ON(pc->worker_thread());
3693 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3694 }
3695 };
3696 worker_thread()->Invoke<void>(
3697 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003698 return;
3699 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003700 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003701 RTC_DCHECK(call_.get());
3702 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3703}
3704
henrika5f6bf242017-11-01 11:06:56 +01003705void PeerConnection::SetAudioPlayout(bool playout) {
3706 if (!worker_thread()->IsCurrent()) {
3707 worker_thread()->Invoke<void>(
3708 RTC_FROM_HERE,
3709 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
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->SetPlayout(playout);
3715}
3716
3717void PeerConnection::SetAudioRecording(bool recording) {
3718 if (!worker_thread()->IsCurrent()) {
3719 worker_thread()->Invoke<void>(
3720 RTC_FROM_HERE,
3721 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3722 return;
3723 }
3724 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003725 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003726 audio_state->SetRecording(recording);
3727}
3728
Steve Anton8c0f7a72017-10-03 10:03:10 -07003729std::unique_ptr<rtc::SSLCertificate>
3730PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003731 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3732 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003733 return nullptr;
3734 }
Steve Antonf25303e2018-10-16 15:23:31 -07003735 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003736}
3737
Zhi Huang70b820f2018-01-27 14:16:15 -08003738std::unique_ptr<rtc::SSLCertChain>
3739PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003741 auto audio_transceiver = GetFirstAudioTransceiver();
3742 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003743 return nullptr;
3744 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003745 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003746 audio_transceiver->internal()->channel()->transport_name());
3747}
3748
3749rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3750PeerConnection::GetFirstAudioTransceiver() const {
3751 for (auto transceiver : transceivers_) {
3752 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3753 return transceiver;
3754 }
3755 }
3756 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003757}
3758
ivoc14d5dbe2016-07-04 07:06:55 -07003759bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3760 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003761 // TODO(eladalon): It would be better to not allow negative values into PC.
3762 const size_t max_size = (max_size_bytes < 0)
3763 ? RtcEventLog::kUnlimitedOutput
3764 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003765 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3766 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3767 output_period_ms = 5000;
3768 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003769 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003770 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003771 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003772}
3773
Bjorn Tereliusde939432017-11-20 17:38:14 +01003774bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3775 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003776 // TODO(eladalon): In C++14, this can be done with a lambda.
3777 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003778 bool operator()() {
3779 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3780 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003781 PeerConnection* const pc;
3782 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003783 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003784 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003785 return worker_thread()->Invoke<bool>(
3786 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003787}
3788
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003789bool PeerConnection::StartRtcEventLog(
3790 std::unique_ptr<RtcEventLogOutput> output) {
3791 return StartRtcEventLog(std::move(output),
3792 webrtc::RtcEventLog::kImmediateOutput);
3793}
3794
ivoc14d5dbe2016-07-04 07:06:55 -07003795void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003796 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003797 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3798}
3799
Harald Alvestrandad88c882018-11-28 16:47:46 +01003800rtc::scoped_refptr<DtlsTransportInterface>
3801PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003802 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003803 return transport_controller_->LookupDtlsTransportByMid(mid);
3804}
3805
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003806rtc::scoped_refptr<DtlsTransport>
3807PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003808 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003809 return transport_controller_->LookupDtlsTransportByMid(mid);
3810}
3811
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003812rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3813 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003814 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003815 return sctp_transport_;
3816}
3817
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003819 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003820 return pending_local_description_ ? pending_local_description_.get()
3821 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003822}
3823
3824const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003825 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003826 return pending_remote_description_ ? pending_remote_description_.get()
3827 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003828}
3829
deadbeeffe4a8a42016-12-20 17:56:17 -08003830const SessionDescriptionInterface* PeerConnection::current_local_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 current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003834}
3835
3836const SessionDescriptionInterface* PeerConnection::current_remote_description()
3837 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003838 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003839 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003840}
3841
3842const SessionDescriptionInterface* PeerConnection::pending_local_description()
3843 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003844 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003845 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003846}
3847
3848const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3849 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003850 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003851 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003852}
3853
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003854void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003855 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003856 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003857 // Update stats here so that we have the most recent stats for tracks and
3858 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003859 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003860
Steve Anton75737c02017-11-06 10:37:17 -08003861 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003862 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003863
Mirko Bonadei739baf02019-01-27 17:29:42 +01003864 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003865 transceiver->Stop();
3866 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003867
3868 // Ensure that all asynchronous stats requests are completed before destroying
3869 // the transport controller below.
3870 if (stats_collector_) {
3871 stats_collector_->WaitForPendingRequest();
3872 }
3873
3874 // Don't destroy BaseChannels until after stats has been cleaned up so that
3875 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003876 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003877
Qingsi Wang93a84392018-01-30 17:13:09 -08003878 // The event log is used in the transport controller, which must be outlived
3879 // by the former. CreateOffer by the peer connection is implemented
3880 // asynchronously and if the peer connection is closed without resetting the
3881 // WebRTC session description factory, the session description factory would
3882 // call the transport controller.
3883 webrtc_session_desc_factory_.reset();
3884 transport_controller_.reset();
3885
deadbeef42a42632017-03-10 15:18:00 -08003886 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003887 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3888 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003889
Steve Anton978b8762017-09-29 12:15:02 -07003890 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003891 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003892 call_.reset();
3893 // The event log must outlive call (and any other object that uses it).
3894 event_log_.reset();
3895 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003896 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003897 // The .h file says that observer can be discarded after close() returns.
3898 // Make sure this is true.
3899 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003900}
3901
Steve Antonad182762018-09-05 20:22:40 +00003902void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003903 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003904 switch (msg->message_id) {
3905 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3906 SetSessionDescriptionMsg* param =
3907 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3908 param->observer->OnSuccess();
3909 delete param;
3910 break;
3911 }
3912 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3913 SetSessionDescriptionMsg* param =
3914 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3915 param->observer->OnFailure(std::move(param->error));
3916 delete param;
3917 break;
3918 }
3919 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3920 CreateSessionDescriptionMsg* param =
3921 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3922 param->observer->OnFailure(std::move(param->error));
3923 delete param;
3924 break;
3925 }
3926 case MSG_GETSTATS: {
3927 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3928 StatsReports reports;
3929 stats_->GetStats(param->track, &reports);
3930 param->observer->OnComplete(reports);
3931 delete param;
3932 break;
3933 }
3934 case MSG_FREE_DATACHANNELS: {
3935 sctp_data_channels_to_free_.clear();
3936 break;
3937 }
3938 case MSG_REPORT_USAGE_PATTERN: {
3939 ReportUsagePattern();
3940 break;
3941 }
3942 default:
3943 RTC_NOTREACHED() << "Not implemented";
3944 break;
3945 }
3946}
3947
Steve Antonafb0bb72018-02-20 11:35:37 -08003948cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3949 RTC_DCHECK(!IsUnifiedPlan());
3950 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3951 GetAudioTransceiver()->internal()->channel());
3952 if (voice_channel) {
3953 return voice_channel->media_channel();
3954 } else {
3955 return nullptr;
3956 }
3957}
3958
3959cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3960 RTC_DCHECK(!IsUnifiedPlan());
3961 auto* video_channel = static_cast<cricket::VideoChannel*>(
3962 GetVideoTransceiver()->internal()->channel());
3963 if (video_channel) {
3964 return video_channel->media_channel();
3965 } else {
3966 return nullptr;
3967 }
3968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970void PeerConnection::CreateAudioReceiver(
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* audio_receiver = new AudioRtpReceiver(
3978 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003979 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003980 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3981 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3982 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003983 GetAudioTransceiver()->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::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003986}
3987
Steve Anton4171afb2017-11-20 10:20:22 -08003988void PeerConnection::CreateVideoReceiver(
3989 MediaStreamInterface* stream,
3990 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003991 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3992 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003993 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3994 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003995 auto* video_receiver = new VideoRtpReceiver(
3996 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003997 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003998 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3999 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4000 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004001 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004002 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004003 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004004}
4005
deadbeef70ab1a12015-09-28 16:53:55 -07004006// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4007// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004008rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004009 const RtpSenderInfo& remote_sender_info) {
4010 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4011 if (!receiver) {
4012 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4013 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004014 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004015 }
Steve Anton4171afb2017-11-20 10:20:22 -08004016 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4017 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4018 } else {
4019 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4020 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004021 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004022}
4023
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004024void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4025 MediaStreamInterface* stream) {
4026 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004027 RTC_DCHECK(track);
4028 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004030 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004031 // We already have a sender for this track, so just change the stream_id
4032 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004033 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 return;
4035 }
4036
4037 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004038 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004039 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004040 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004041 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004042 // If the sender has already been configured in SDP, we call SetSsrc,
4043 // which will connect the sender to the underlying transport. This can
4044 // occur if a local session description that contains the ID of the sender
4045 // is set before AddStream is called. It can also occur if the local
4046 // session description is not changed and RemoveStream is called, and
4047 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004048 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004049 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004050 if (sender_info) {
4051 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004052 }
4053}
4054
4055// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4056// indefinitely, when we have unified plan SDP.
4057void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4058 MediaStreamInterface* stream) {
4059 RTC_DCHECK(!IsClosed());
4060 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004061 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004062 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4063 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004064 return;
4065 }
Steve Anton4171afb2017-11-20 10:20:22 -08004066 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004067}
4068
4069void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4070 MediaStreamInterface* stream) {
4071 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004072 RTC_DCHECK(track);
4073 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004075 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004076 // We already have a sender for this track, so just change the stream_id
4077 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004078 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004079 return;
4080 }
4081
4082 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004083 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004084 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004085 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004086 GetVideoTransceiver()->internal()->AddSender(new_sender);
4087 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004088 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004089 if (sender_info) {
4090 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004091 }
4092}
4093
4094void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4095 MediaStreamInterface* stream) {
4096 RTC_DCHECK(!IsClosed());
4097 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004098 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004099 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4100 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004101 return;
4102 }
Steve Anton4171afb2017-11-20 10:20:22 -08004103 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004104}
4105
Steve Antonba818672017-11-06 10:21:57 -08004106void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004107 if (ice_connection_state_ == new_state) {
4108 return;
4109 }
4110
deadbeefcbecd352015-09-23 11:50:27 -07004111 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004112 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004113 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004114 return;
4115 }
Steve Antonba818672017-11-06 10:21:57 -08004116
Mirko Bonadei675513b2017-11-09 11:09:25 +01004117 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4118 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004119 RTC_DCHECK(ice_connection_state_ !=
4120 PeerConnectionInterface::kIceConnectionClosed);
4121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004122 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004123 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004124}
4125
Alex Loiko9289eda2018-11-23 16:18:59 +00004126void PeerConnection::SetStandardizedIceConnectionState(
4127 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004128 if (standardized_ice_connection_state_ == new_state)
4129 return;
4130 if (IsClosed())
4131 return;
4132 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004133 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004134}
4135
Jonas Olsson635474e2018-10-18 15:58:17 +02004136void PeerConnection::SetConnectionState(
4137 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004138 if (connection_state_ == new_state)
4139 return;
4140 if (IsClosed())
4141 return;
4142 connection_state_ = new_state;
4143 Observer()->OnConnectionChange(new_state);
4144}
4145
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004146void PeerConnection::OnIceGatheringChange(
4147 PeerConnectionInterface::IceGatheringState new_state) {
4148 if (IsClosed()) {
4149 return;
4150 }
4151 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004152 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004153}
4154
jbauch81bf7b02017-03-25 08:31:12 -07004155void PeerConnection::OnIceCandidate(
4156 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004157 if (IsClosed()) {
4158 return;
4159 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004160 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004161 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4162 candidate->candidate().address().IsPrivateIP()) {
4163 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4164 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004165 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4166 candidate->candidate().address().IsUnresolvedIP()) {
4167 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4168 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004169 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004170}
4171
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004172void PeerConnection::OnIceCandidatesRemoved(
4173 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004174 if (IsClosed()) {
4175 return;
4176 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004177 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004178}
4179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004180void PeerConnection::ChangeSignalingState(
4181 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004182 if (signaling_state_ == signaling_state) {
4183 return;
4184 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004185 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4186 << GetSignalingStateString(signaling_state_)
4187 << " New state: "
4188 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004189 signaling_state_ = signaling_state;
4190 if (signaling_state == kClosed) {
4191 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004192 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004193 standardized_ice_connection_state_ =
4194 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004195 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4196 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004197 if (ice_gathering_state_ != kIceGatheringComplete) {
4198 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004199 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004200 }
4201 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004202 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004203}
4204
deadbeefeb459812015-12-15 19:24:43 -08004205void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4206 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004207 if (IsClosed()) {
4208 return;
4209 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004210 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004211 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004212}
4213
deadbeefeb459812015-12-15 19:24:43 -08004214void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4215 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004216 if (IsClosed()) {
4217 return;
4218 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004219 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004220 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004221}
4222
4223void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4224 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004225 if (IsClosed()) {
4226 return;
4227 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004228 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004229 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004230}
4231
4232void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4233 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004234 if (IsClosed()) {
4235 return;
4236 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004237 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004238 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004239}
4240
Henrik Boström31638672017-11-23 17:48:32 +01004241void PeerConnection::PostSetSessionDescriptionSuccess(
4242 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004243 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4244 signaling_thread()->Post(RTC_FROM_HERE, this,
4245 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004246}
4247
deadbeefab9b2d12015-10-14 11:33:11 -07004248void PeerConnection::PostSetSessionDescriptionFailure(
4249 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004250 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004251 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004252 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4253 msg->error = std::move(error);
4254 signaling_thread()->Post(RTC_FROM_HERE, this,
4255 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004256}
4257
4258void PeerConnection::PostCreateSessionDescriptionFailure(
4259 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004260 RTCError error) {
4261 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004262 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4263 msg->error = std::move(error);
4264 signaling_thread()->Post(RTC_FROM_HERE, this,
4265 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004266}
4267
zhihuang1c378ed2017-08-17 14:10:50 -07004268void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004269 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004270 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004271 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004272
Steve Antondcc3c022017-12-22 16:02:54 -08004273 if (IsUnifiedPlan()) {
4274 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4275 } else {
4276 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4277 }
4278
Steve Antonfa2260d2017-12-28 16:38:23 -08004279 // Intentionally unset the data channel type for RTP data channel with the
4280 // second condition. Otherwise the RTP data channels would be successfully
4281 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4282 // when building with chromium. We want to leave RTP data channels broken, so
4283 // people won't try to use them.
4284 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4285 session_options->data_channel_type = data_channel_type();
4286 }
4287
Steve Antondcc3c022017-12-22 16:02:54 -08004288 // Apply ICE restart flag and renomination flag.
4289 for (auto& options : session_options->media_description_options) {
4290 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4291 options.transport_options.enable_ice_renomination =
4292 configuration_.enable_ice_renomination;
4293 }
4294
4295 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004296 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004297 session_options->pooled_ice_credentials =
4298 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4299 RTC_FROM_HERE,
4300 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4301 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004302 session_options->offer_extmap_allow_mixed =
4303 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004304
4305 if (configuration_.enable_dtls_srtp &&
4306 !configuration_.enable_dtls_srtp.value()) {
4307 session_options->media_transport_settings =
4308 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4309 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004310 // Allow fallback for using obsolete SCTP syntax.
4311 // Note that the default in |session_options| is true, while
4312 // the default in |options| is false.
4313 session_options->use_obsolete_sctp_sdp =
4314 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004315}
4316
4317void PeerConnection::GetOptionsForPlanBOffer(
4318 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4319 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004320 // Figure out transceiver directional preferences.
4321 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4322 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4323
4324 // By default, generate sendrecv/recvonly m= sections.
4325 bool recv_audio = true;
4326 bool recv_video = true;
4327
4328 // By default, only offer a new m= section if we have media to send with it.
4329 bool offer_new_audio_description = send_audio;
4330 bool offer_new_video_description = send_video;
4331 bool offer_new_data_description = HasDataChannels();
4332
4333 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004334 if (offer_answer_options.offer_to_receive_audio !=
4335 RTCOfferAnswerOptions::kUndefined) {
4336 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004337 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004338 offer_new_audio_description ||
4339 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004340 }
Steve Antondcc3c022017-12-22 16:02:54 -08004341 if (offer_answer_options.offer_to_receive_video !=
4342 RTCOfferAnswerOptions::kUndefined) {
4343 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004344 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004345 offer_new_video_description ||
4346 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004347 }
4348
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004349 absl::optional<size_t> audio_index;
4350 absl::optional<size_t> video_index;
4351 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004352 // If a current description exists, generate m= sections in the same order,
4353 // using the first audio/video/data section that appears and rejecting
4354 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004355 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004356 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004357 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004358 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4359 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4360 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004361 }
4362
zhihuang1c378ed2017-08-17 14:10:50 -07004363 // Add audio/video/data m= sections to the end if needed.
4364 if (!audio_index && offer_new_audio_description) {
4365 session_options->media_description_options.push_back(
4366 cricket::MediaDescriptionOptions(
4367 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004368 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4369 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004370 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004371 }
zhihuang1c378ed2017-08-17 14:10:50 -07004372 if (!video_index && offer_new_video_description) {
4373 session_options->media_description_options.push_back(
4374 cricket::MediaDescriptionOptions(
4375 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004376 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4377 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004378 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004379 }
zhihuang1c378ed2017-08-17 14:10:50 -07004380 if (!data_index && offer_new_data_description) {
4381 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004382 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004383 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004384 }
4385
4386 cricket::MediaDescriptionOptions* audio_media_description_options =
4387 !audio_index ? nullptr
4388 : &session_options->media_description_options[*audio_index];
4389 cricket::MediaDescriptionOptions* video_media_description_options =
4390 !video_index ? nullptr
4391 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004392
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004393 AddPlanBRtpSenderOptions(GetSendersInternal(),
4394 audio_media_description_options,
4395 video_media_description_options,
4396 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004397}
4398
Steve Antondcc3c022017-12-22 16:02:54 -08004399static cricket::MediaDescriptionOptions
4400GetMediaDescriptionOptionsForTransceiver(
4401 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4402 transceiver,
4403 const std::string& mid) {
4404 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004405 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004406 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004407 media_description_options.codec_preferences =
4408 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004409 // This behavior is specified in JSEP. The gist is that:
4410 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4411 // sendrecv.
4412 // 2. If the MSID is included, then it must be included in any subsequent
4413 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004414 if (transceiver->stopped() ||
4415 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4416 !transceiver->internal()->has_ever_been_used_to_send())) {
4417 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004418 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004419
4420 cricket::SenderOptions sender_options;
4421 sender_options.track_id = transceiver->sender()->id();
4422 sender_options.stream_ids = transceiver->sender()->stream_ids();
4423
4424 // The following sets up RIDs and Simulcast.
4425 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004426 RtpParameters send_parameters =
4427 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004428 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4429 send_parameters.encodings.end(),
4430 [](const RtpEncodingParameters& encoding) {
4431 return !encoding.rid.empty();
4432 });
4433
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004434 std::vector<RidDescription> send_rids;
4435 SimulcastLayerList send_layers;
4436 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4437 if (encoding.rid.empty()) {
4438 continue;
4439 }
4440 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4441 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4442 }
4443
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004444 if (has_rids) {
4445 sender_options.rids = send_rids;
4446 }
4447
4448 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004449 // When RIDs are configured, we must set num_sim_layers to 0 to.
4450 // Otherwise, num_sim_layers must be 1 because either there is no
4451 // simulcast, or simulcast is acheived by munging the SDP.
4452 sender_options.num_sim_layers = has_rids ? 0 : 1;
4453 media_description_options.sender_options.push_back(sender_options);
4454
Steve Antondcc3c022017-12-22 16:02:54 -08004455 return media_description_options;
4456}
4457
Steve Anton5c72e712018-12-10 14:25:30 -08004458// Returns the ContentInfo at mline index |i|, or null if none exists.
4459static const ContentInfo* GetContentByIndex(
4460 const SessionDescriptionInterface* sdesc,
4461 size_t i) {
4462 if (!sdesc) {
4463 return nullptr;
4464 }
4465 const ContentInfos& contents = sdesc->description()->contents();
4466 return (i < contents.size() ? &contents[i] : nullptr);
4467}
4468
Steve Antondcc3c022017-12-22 16:02:54 -08004469void PeerConnection::GetOptionsForUnifiedPlanOffer(
4470 const RTCOfferAnswerOptions& offer_answer_options,
4471 cricket::MediaSessionOptions* session_options) {
4472 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4473 // Offers) and 5.2.2 (Subsequent Offers).
4474 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4475 const ContentInfos& local_contents =
4476 (local_description() ? local_description()->description()->contents()
4477 : ContentInfos());
4478 const ContentInfos& remote_contents =
4479 (remote_description() ? remote_description()->description()->contents()
4480 : ContentInfos());
4481 // The mline indices that can be recycled. New transceivers should reuse these
4482 // slots first.
4483 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004484 // First, go through each media section that exists in either the local or
4485 // remote description and generate a media section in this offer for the
4486 // associated transceiver. If a media section can be recycled, generate a
4487 // default, rejected media section here that can be later overwritten.
4488 for (size_t i = 0;
4489 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4490 // Either |local_content| or |remote_content| is non-null.
4491 const ContentInfo* local_content =
4492 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004493 const ContentInfo* current_local_content =
4494 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004495 const ContentInfo* remote_content =
4496 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004497 const ContentInfo* current_remote_content =
4498 GetContentByIndex(current_remote_description(), i);
4499 bool had_been_rejected =
4500 (current_local_content && current_local_content->rejected) ||
4501 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004502 const std::string& mid =
4503 (local_content ? local_content->name : remote_content->name);
4504 cricket::MediaType media_type =
4505 (local_content ? local_content->media_description()->type()
4506 : remote_content->media_description()->type());
4507 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4508 media_type == cricket::MEDIA_TYPE_VIDEO) {
4509 auto transceiver = GetAssociatedTransceiver(mid);
4510 RTC_CHECK(transceiver);
4511 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004512 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004513 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004514 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004515 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4516 RtpTransceiverDirection::kInactive,
4517 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004518 recycleable_mline_indices.push(i);
4519 } else {
4520 session_options->media_description_options.push_back(
4521 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4522 // CreateOffer shouldn't really cause any state changes in
4523 // PeerConnection, but we need a way to match new transceivers to new
4524 // media sections in SetLocalDescription and JSEP specifies this is done
4525 // by recording the index of the media section generated for the
4526 // transceiver in the offer.
4527 transceiver->internal()->set_mline_index(i);
4528 }
4529 } else {
4530 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004531 RTC_CHECK(GetDataMid());
4532 if (had_been_rejected || mid != *GetDataMid()) {
4533 session_options->media_description_options.push_back(
4534 GetMediaDescriptionOptionsForRejectedData(mid));
4535 } else {
4536 session_options->media_description_options.push_back(
4537 GetMediaDescriptionOptionsForActiveData(mid));
4538 }
Steve Antondcc3c022017-12-22 16:02:54 -08004539 }
4540 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004541
Steve Antondcc3c022017-12-22 16:02:54 -08004542 // Next, look for transceivers that are newly added (that is, are not stopped
4543 // and not associated). Reuse media sections marked as recyclable first,
4544 // otherwise append to the end of the offer. New media sections should be
4545 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004546 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004547 if (transceiver->mid() || transceiver->stopped()) {
4548 continue;
4549 }
4550 size_t mline_index;
4551 if (!recycleable_mline_indices.empty()) {
4552 mline_index = recycleable_mline_indices.front();
4553 recycleable_mline_indices.pop();
4554 session_options->media_description_options[mline_index] =
4555 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004556 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004557 } else {
4558 mline_index = session_options->media_description_options.size();
4559 session_options->media_description_options.push_back(
4560 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004561 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004562 }
4563 // See comment above for why CreateOffer changes the transceiver's state.
4564 transceiver->internal()->set_mline_index(mline_index);
4565 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004566 // Lastly, add a m-section if we have local data channels and an m section
4567 // does not already exist.
4568 if (!GetDataMid() && HasDataChannels()) {
4569 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004570 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004571 }
Steve Antondcc3c022017-12-22 16:02:54 -08004572}
4573
4574void PeerConnection::GetOptionsForAnswer(
4575 const RTCOfferAnswerOptions& offer_answer_options,
4576 cricket::MediaSessionOptions* session_options) {
4577 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4578
4579 if (IsUnifiedPlan()) {
4580 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4581 } else {
4582 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4583 }
4584
Steve Antonfa2260d2017-12-28 16:38:23 -08004585 // Intentionally unset the data channel type for RTP data channel. Otherwise
4586 // the RTP data channels would be successfully negotiated by default and the
4587 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4588 // We want to leave RTP data channels broken, so people won't try to use them.
4589 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4590 session_options->data_channel_type = data_channel_type();
4591 }
4592
Steve Antondcc3c022017-12-22 16:02:54 -08004593 // Apply ICE renomination flag.
4594 for (auto& options : session_options->media_description_options) {
4595 options.transport_options.enable_ice_renomination =
4596 configuration_.enable_ice_renomination;
4597 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004598
4599 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004600 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004601 session_options->pooled_ice_credentials =
4602 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4603 RTC_FROM_HERE,
4604 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4605 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004606}
4607
Steve Antondcc3c022017-12-22 16:02:54 -08004608void PeerConnection::GetOptionsForPlanBAnswer(
4609 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004610 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004611 // Figure out transceiver directional preferences.
4612 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4613 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4614
4615 // By default, generate sendrecv/recvonly m= sections. The direction is also
4616 // restricted by the direction in the offer.
4617 bool recv_audio = true;
4618 bool recv_video = true;
4619
4620 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004621 if (offer_answer_options.offer_to_receive_audio !=
4622 RTCOfferAnswerOptions::kUndefined) {
4623 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004624 }
Steve Antondcc3c022017-12-22 16:02:54 -08004625 if (offer_answer_options.offer_to_receive_video !=
4626 RTCOfferAnswerOptions::kUndefined) {
4627 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004628 }
4629
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004630 absl::optional<size_t> audio_index;
4631 absl::optional<size_t> video_index;
4632 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004633
4634 // Generate m= sections that match those in the offer.
4635 // Note that mediasession.cc will handle intersection our preferred
4636 // direction with the offered direction.
4637 GenerateMediaDescriptionOptions(
4638 remote_description(),
4639 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4640 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4641 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004642
4643 cricket::MediaDescriptionOptions* audio_media_description_options =
4644 !audio_index ? nullptr
4645 : &session_options->media_description_options[*audio_index];
4646 cricket::MediaDescriptionOptions* video_media_description_options =
4647 !video_index ? nullptr
4648 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004649
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004650 AddPlanBRtpSenderOptions(GetSendersInternal(),
4651 audio_media_description_options,
4652 video_media_description_options,
4653 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004654}
zhihuangaf388472016-11-02 16:49:48 -07004655
Steve Antondcc3c022017-12-22 16:02:54 -08004656void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4657 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4658 cricket::MediaSessionOptions* session_options) {
4659 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4660 // Answers) and 5.3.2 (Subsequent Answers).
4661 RTC_DCHECK(remote_description());
4662 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4663 for (const ContentInfo& content :
4664 remote_description()->description()->contents()) {
4665 cricket::MediaType media_type = content.media_description()->type();
4666 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4667 media_type == cricket::MEDIA_TYPE_VIDEO) {
4668 auto transceiver = GetAssociatedTransceiver(content.name);
4669 RTC_CHECK(transceiver);
4670 session_options->media_description_options.push_back(
4671 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4672 } else {
4673 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004674 // Reject all data sections if data channels are disabled.
4675 // Reject a data section if it has already been rejected.
4676 // Reject all data sections except for the first one.
4677 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4678 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004679 session_options->media_description_options.push_back(
4680 GetMediaDescriptionOptionsForRejectedData(content.name));
4681 } else {
4682 session_options->media_description_options.push_back(
4683 GetMediaDescriptionOptionsForActiveData(content.name));
4684 }
Steve Antondcc3c022017-12-22 16:02:54 -08004685 }
4686 }
htaa2a49d92016-03-04 02:51:39 -08004687}
4688
zhihuang1c378ed2017-08-17 14:10:50 -07004689void PeerConnection::GenerateMediaDescriptionOptions(
4690 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004691 RtpTransceiverDirection audio_direction,
4692 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004693 absl::optional<size_t>* audio_index,
4694 absl::optional<size_t>* video_index,
4695 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004696 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004697 for (const cricket::ContentInfo& content :
4698 session_desc->description()->contents()) {
4699 if (IsAudioContent(&content)) {
4700 // If we already have an audio m= section, reject this extra one.
4701 if (*audio_index) {
4702 session_options->media_description_options.push_back(
4703 cricket::MediaDescriptionOptions(
4704 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004705 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004706 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004707 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004708 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004709 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4710 content.name, audio_direction,
4711 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004712 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004713 }
4714 } else if (IsVideoContent(&content)) {
4715 // If we already have an video m= section, reject this extra one.
4716 if (*video_index) {
4717 session_options->media_description_options.push_back(
4718 cricket::MediaDescriptionOptions(
4719 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004720 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004721 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004722 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004723 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004724 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4725 content.name, video_direction,
4726 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004727 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004728 }
4729 } else {
4730 RTC_DCHECK(IsDataContent(&content));
4731 // If we already have an data m= section, reject this extra one.
4732 if (*data_index) {
4733 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004734 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004735 } else {
4736 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004737 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004738 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004739 }
4740 }
htaa2a49d92016-03-04 02:51:39 -08004741 }
deadbeefab9b2d12015-10-14 11:33:11 -07004742}
4743
Steve Antonfa2260d2017-12-28 16:38:23 -08004744cricket::MediaDescriptionOptions
4745PeerConnection::GetMediaDescriptionOptionsForActiveData(
4746 const std::string& mid) const {
4747 // Direction for data sections is meaningless, but legacy endpoints might
4748 // expect sendrecv.
4749 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4750 RtpTransceiverDirection::kSendRecv,
4751 /*stopped=*/false);
4752 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4753 return options;
4754}
4755
4756cricket::MediaDescriptionOptions
4757PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4758 const std::string& mid) const {
4759 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4760 RtpTransceiverDirection::kInactive,
4761 /*stopped=*/true);
4762 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4763 return options;
4764}
4765
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004766absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004767 switch (data_channel_type_) {
4768 case cricket::DCT_RTP:
4769 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004770 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004771 }
4772 return rtp_data_channel_->content_name();
4773 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004774 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004775 case cricket::DCT_MEDIA_TRANSPORT:
4776 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004777 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004778 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004779 }
4780}
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4783 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4784 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004785 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004786}
4787
Steve Anton4171afb2017-11-20 10:20:22 -08004788void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004789 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004790 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004791 cricket::MediaType media_type,
4792 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004793 RTC_DCHECK(!IsUnifiedPlan());
4794
Steve Anton4171afb2017-11-20 10:20:22 -08004795 std::vector<RtpSenderInfo>* current_senders =
4796 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004797
Steve Anton4171afb2017-11-20 10:20:22 -08004798 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004799 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004800 for (auto sender_it = current_senders->begin();
4801 sender_it != current_senders->end();
4802 /* incremented manually */) {
4803 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004804 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004805 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004806 std::string params_stream_id;
4807 if (params) {
4808 params_stream_id =
4809 (!params->first_stream_id().empty() ? params->first_stream_id()
4810 : kDefaultStreamId);
4811 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004812 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004813 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004814 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004815 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004816 sender_exists) {
4817 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004818 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004819 OnRemoteSenderRemoved(info, media_type);
4820 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004821 }
4822 }
4823
Steve Anton4171afb2017-11-20 10:20:22 -08004824 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004825 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004826 if (!params.has_ssrcs()) {
4827 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4828 // sender, this means it is coming from a Unified Plan endpoint,so we just
4829 // create a default.
4830 default_sender_needed = true;
4831 break;
4832 }
4833
Seth Hampson845e8782018-03-02 11:34:10 -08004834 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004835 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004836 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4837 // not supported in Plan B, we just take the first here and create the
4838 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004839 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004840 (!params.first_stream_id().empty() ? params.first_stream_id()
4841 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004842 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004843 uint32_t ssrc = params.first_ssrc();
4844
4845 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004846 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004847 if (!stream) {
4848 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004849 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004850 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004851 remote_streams_->AddStream(stream);
4852 new_streams->AddStream(stream);
4853 }
4854
Steve Anton4171afb2017-11-20 10:20:22 -08004855 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004856 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004857 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004858 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004859 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004860 }
4861 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004862
Steve Anton4171afb2017-11-20 10:20:22 -08004863 // Add default sender if necessary.
4864 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004865 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004866 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004867 if (!default_stream) {
4868 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004869 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004870 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004871 remote_streams_->AddStream(default_stream);
4872 new_streams->AddStream(default_stream);
4873 }
Steve Anton4171afb2017-11-20 10:20:22 -08004874 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4875 ? kDefaultAudioSenderId
4876 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004877 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004878 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004879 if (!default_sender_info) {
4880 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004881 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004882 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004883 }
4884 }
deadbeefab9b2d12015-10-14 11:33:11 -07004885}
4886
Steve Anton4171afb2017-11-20 10:20:22 -08004887void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4888 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004889 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4890 << " receiver for track_id=" << sender_info.sender_id
4891 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004892
Steve Anton3d954a62018-04-02 11:27:23 -07004893 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004894 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004895 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004896 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004897 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004898 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004899 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004900 }
4901}
4902
Steve Anton4171afb2017-11-20 10:20:22 -08004903void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4904 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004905 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4906 << " receiver for track_id=" << sender_info.sender_id
4907 << " and stream_id=" << sender_info.stream_id;
4908
Seth Hampson845e8782018-03-02 11:34:10 -08004909 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004910
Henrik Boström933d8b02017-10-10 10:05:16 -07004911 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004912 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004913 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4914 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004915 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004916 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004917 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004918 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004919 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004920 }
4921 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004922 // Stopping or destroying a VideoRtpReceiver will end the
4923 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004924 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004925 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004926 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004927 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004928 // There's no guarantee the track is still available, e.g. the track may
4929 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004930 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004931 }
4932 } else {
nisseede5da42017-01-12 05:15:36 -08004933 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004934 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004935 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004936 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004937 }
deadbeefab9b2d12015-10-14 11:33:11 -07004938}
4939
4940void PeerConnection::UpdateEndedRemoteMediaStreams() {
4941 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4942 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4943 MediaStreamInterface* stream = remote_streams_->at(i);
4944 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4945 streams_to_remove.push_back(stream);
4946 }
4947 }
4948
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004949 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004950 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004951 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004952 }
4953}
4954
Steve Anton4171afb2017-11-20 10:20:22 -08004955void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004956 const std::vector<cricket::StreamParams>& streams,
4957 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004958 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004959
Seth Hampson845e8782018-03-02 11:34:10 -08004960 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004961 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004962 for (auto sender_it = current_senders->begin();
4963 sender_it != current_senders->end();
4964 /* incremented manually */) {
4965 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004966 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004967 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4968 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004969 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004970 OnLocalSenderRemoved(info, media_type);
4971 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004972 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004973 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004974 }
4975 }
4976
Steve Anton4171afb2017-11-20 10:20:22 -08004977 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004978 for (const cricket::StreamParams& params : streams) {
4979 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004980 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004981 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004982 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004983 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004984 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004985 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004986 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004987 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004988 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004989 }
4990 }
4991}
4992
Steve Anton4171afb2017-11-20 10:20:22 -08004993void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4994 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004995 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004996 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004997 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004998 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4999 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005000 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005001 return;
5002 }
5003
deadbeeffac06552015-11-25 11:26:01 -08005004 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005005 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005006 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005007 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005008 }
deadbeeffac06552015-11-25 11:26:01 -08005009
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005010 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005011 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005012}
5013
Steve Anton4171afb2017-11-20 10:20:22 -08005014void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5015 cricket::MediaType media_type) {
5016 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005017 if (!sender) {
5018 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005019 // SessionDescriptions has been renegotiated.
5020 return;
5021 }
deadbeeffac06552015-11-25 11:26:01 -08005022
5023 // A sender has been removed from the SessionDescription but it's still
5024 // associated with the PeerConnection. This only occurs if the SDP doesn't
5025 // match with the calls to CreateSender, AddStream and RemoveStream.
5026 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005027 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005028 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005029 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005030 }
deadbeeffac06552015-11-25 11:26:01 -08005031
Steve Anton4171afb2017-11-20 10:20:22 -08005032 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005033}
5034
5035void PeerConnection::UpdateLocalRtpDataChannels(
5036 const cricket::StreamParamsVec& streams) {
5037 std::vector<std::string> existing_channels;
5038
5039 // Find new and active data channels.
5040 for (const cricket::StreamParams& params : streams) {
5041 // |it->sync_label| is actually the data channel label. The reason is that
5042 // we use the same naming of data channels as we do for
5043 // MediaStreams and Tracks.
5044 // For MediaStreams, the sync_label is the MediaStream label and the
5045 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005046 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005047 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005048 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005049 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005050 continue;
5051 }
5052 // Set the SSRC the data channel should use for sending.
5053 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5054 existing_channels.push_back(data_channel_it->first);
5055 }
5056
5057 UpdateClosingRtpDataChannels(existing_channels, true);
5058}
5059
5060void PeerConnection::UpdateRemoteRtpDataChannels(
5061 const cricket::StreamParamsVec& streams) {
5062 std::vector<std::string> existing_channels;
5063
5064 // Find new and active data channels.
5065 for (const cricket::StreamParams& params : streams) {
5066 // The data channel label is either the mslabel or the SSRC if the mslabel
5067 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005068 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005069 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005070 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005071 auto data_channel_it = rtp_data_channels_.find(label);
5072 if (data_channel_it == rtp_data_channels_.end()) {
5073 // This is a new data channel.
5074 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5075 } else {
5076 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5077 }
5078 existing_channels.push_back(label);
5079 }
5080
5081 UpdateClosingRtpDataChannels(existing_channels, false);
5082}
5083
5084void PeerConnection::UpdateClosingRtpDataChannels(
5085 const std::vector<std::string>& active_channels,
5086 bool is_local_update) {
5087 auto it = rtp_data_channels_.begin();
5088 while (it != rtp_data_channels_.end()) {
5089 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005090 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005091 ++it;
5092 continue;
5093 }
5094
5095 if (is_local_update) {
5096 data_channel->SetSendSsrc(0);
5097 } else {
5098 data_channel->RemotePeerRequestClose();
5099 }
5100
5101 if (data_channel->state() == DataChannel::kClosed) {
5102 rtp_data_channels_.erase(it);
5103 it = rtp_data_channels_.begin();
5104 } else {
5105 ++it;
5106 }
5107 }
5108}
5109
5110void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5111 uint32_t remote_ssrc) {
5112 rtc::scoped_refptr<DataChannel> channel(
5113 InternalCreateDataChannel(label, nullptr));
5114 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005116 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005117 return;
5118 }
5119 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005120 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5121 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005122 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005123}
5124
5125rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5126 const std::string& label,
5127 const InternalDataChannelInit* config) {
5128 if (IsClosed()) {
5129 return nullptr;
5130 }
Steve Anton75737c02017-11-06 10:37:17 -08005131 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005132 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005133 << "InternalCreateDataChannel: Data is not supported in this call.";
5134 return nullptr;
5135 }
5136 InternalDataChannelInit new_config =
5137 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005138 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005139 if (new_config.id < 0) {
5140 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005141 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005142 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005143 RTC_LOG(LS_ERROR)
5144 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005145 return nullptr;
5146 }
5147 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005148 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005149 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005150 return nullptr;
5151 }
5152 }
5153
Steve Anton75737c02017-11-06 10:37:17 -08005154 rtc::scoped_refptr<DataChannel> channel(
5155 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005156 if (!channel) {
5157 sid_allocator_.ReleaseSid(new_config.id);
5158 return nullptr;
5159 }
5160
5161 if (channel->data_channel_type() == cricket::DCT_RTP) {
5162 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005163 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5164 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005165 return nullptr;
5166 }
5167 rtp_data_channels_[channel->label()] = channel;
5168 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005169 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005170 sctp_data_channels_.push_back(channel);
5171 channel->SignalClosed.connect(this,
5172 &PeerConnection::OnSctpDataChannelClosed);
5173 }
5174
Steve Anton2d8609c2018-01-23 16:38:46 -08005175 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005176 return channel;
5177}
5178
5179bool PeerConnection::HasDataChannels() const {
5180 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5181}
5182
5183void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005184 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005185 for (const auto& channel : sctp_data_channels_) {
5186 if (channel->id() < 0) {
5187 int sid;
5188 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005189 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5190 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005191 continue;
5192 }
5193 channel->SetSctpSid(sid);
5194 }
5195 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005196 // Since closing modifies the list of channels, we have to do the actual
5197 // closing outside the loop.
5198 for (const auto& channel : channels_to_close) {
5199 channel->CloseAbruptly();
5200 }
deadbeefab9b2d12015-10-14 11:33:11 -07005201}
5202
5203void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005204 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005205 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5206 ++it) {
5207 if (it->get() == channel) {
5208 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005209 // After the closing procedure is done, it's safe to use this ID for
5210 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005211 sid_allocator_.ReleaseSid(channel->id());
5212 }
deadbeefbd292462015-12-14 18:15:29 -08005213 // Since this method is triggered by a signal from the DataChannel,
5214 // we can't free it directly here; we need to free it asynchronously.
5215 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005216 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005217 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5218 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005219 return;
5220 }
5221 }
5222}
5223
deadbeefab9b2d12015-10-14 11:33:11 -07005224void PeerConnection::OnDataChannelDestroyed() {
5225 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5226 // DataChannel may callback to us and try to modify the list.
5227 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5228 temp_rtp_dcs.swap(rtp_data_channels_);
5229 for (const auto& kv : temp_rtp_dcs) {
5230 kv.second->OnTransportChannelDestroyed();
5231 }
5232
5233 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5234 temp_sctp_dcs.swap(sctp_data_channels_);
5235 for (const auto& channel : temp_sctp_dcs) {
5236 channel->OnTransportChannelDestroyed();
5237 }
5238}
5239
5240void PeerConnection::OnDataChannelOpenMessage(
5241 const std::string& label,
5242 const InternalDataChannelInit& config) {
5243 rtc::scoped_refptr<DataChannel> channel(
5244 InternalCreateDataChannel(label, &config));
5245 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005246 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005247 return;
5248 }
5249
deadbeefa601f5c2016-06-06 14:27:39 -07005250 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5251 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005252 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005253 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005254}
5255
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005256bool PeerConnection::HandleOpenMessage_s(
5257 const cricket::ReceiveDataParams& params,
5258 const rtc::CopyOnWriteBuffer& buffer) {
5259 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5260 // Received OPEN message; parse and signal that a new data channel should
5261 // be created.
5262 std::string label;
5263 InternalDataChannelInit config;
5264 config.id = params.ssrc;
5265 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5266 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5267 << params.ssrc;
5268 return true;
5269 }
5270 config.open_handshake_role = InternalDataChannelInit::kAcker;
5271 OnDataChannelOpenMessage(label, config);
5272 return true;
5273 }
5274 return false;
5275}
5276
Steve Anton4171afb2017-11-20 10:20:22 -08005277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5278PeerConnection::GetAudioTransceiver() const {
5279 // This method only works with Plan B SDP, where there is a single
5280 // audio/video transceiver.
5281 RTC_DCHECK(!IsUnifiedPlan());
5282 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005283 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005284 return transceiver;
5285 }
5286 }
5287 RTC_NOTREACHED();
5288 return nullptr;
5289}
5290
5291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5292PeerConnection::GetVideoTransceiver() const {
5293 // This method only works with Plan B SDP, where there is a single
5294 // audio/video transceiver.
5295 RTC_DCHECK(!IsUnifiedPlan());
5296 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005297 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005298 return transceiver;
5299 }
5300 }
5301 RTC_NOTREACHED();
5302 return nullptr;
5303}
5304
5305// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5306// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005307bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005308 switch (type) {
5309 case cricket::MEDIA_TYPE_AUDIO:
5310 return !GetAudioTransceiver()->internal()->senders().empty();
5311 case cricket::MEDIA_TYPE_VIDEO:
5312 return !GetVideoTransceiver()->internal()->senders().empty();
5313 case cricket::MEDIA_TYPE_DATA:
5314 return false;
5315 }
5316 RTC_NOTREACHED();
5317 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005318}
5319
Steve Anton4171afb2017-11-20 10:20:22 -08005320rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5321PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005322 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005323 for (auto sender : transceiver->internal()->senders()) {
5324 if (sender->track() == track) {
5325 return sender;
5326 }
5327 }
5328 }
5329 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005330}
5331
Steve Anton4171afb2017-11-20 10:20:22 -08005332rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5333PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005334 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005335 for (auto sender : transceiver->internal()->senders()) {
5336 if (sender->id() == sender_id) {
5337 return sender;
5338 }
5339 }
5340 }
5341 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005342}
5343
Steve Anton4171afb2017-11-20 10:20:22 -08005344rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5345PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005346 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005347 for (auto receiver : transceiver->internal()->receivers()) {
5348 if (receiver->id() == receiver_id) {
5349 return receiver;
5350 }
5351 }
5352 }
5353 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005354}
5355
Steve Anton4171afb2017-11-20 10:20:22 -08005356std::vector<PeerConnection::RtpSenderInfo>*
5357PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5358 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5359 media_type == cricket::MEDIA_TYPE_VIDEO);
5360 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5361 ? &remote_audio_sender_infos_
5362 : &remote_video_sender_infos_;
5363}
5364
5365std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005366 cricket::MediaType media_type) {
5367 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5368 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005369 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5370 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005371}
5372
Steve Anton4171afb2017-11-20 10:20:22 -08005373const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5374 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005375 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005376 const std::string sender_id) const {
5377 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005378 if (sender_info.stream_id == stream_id &&
5379 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005380 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005381 }
5382 }
5383 return nullptr;
5384}
5385
5386DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5387 for (const auto& channel : sctp_data_channels_) {
5388 if (channel->id() == sid) {
5389 return channel;
5390 }
5391 }
5392 return nullptr;
5393}
5394
Karl Wibergfb3be392019-03-22 14:13:22 +01005395PeerConnection::InitializePortAllocatorResult
5396PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005397 const cricket::ServerAddresses& stun_servers,
5398 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005399 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005400 RTC_DCHECK_RUN_ON(network_thread());
5401
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005402 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403 // To handle both internal and externally created port allocator, we will
5404 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005405 int port_allocator_flags = port_allocator_->flags();
5406 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5407 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5408 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005409 // If the disable-IPv6 flag was specified, we'll not override it
5410 // by experiment.
5411 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005412 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005413 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5414 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005415 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005416 }
5417
zhihuangb09b3f92017-03-07 14:40:51 -08005418 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005419 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005420 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005421 }
5422
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005424 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005425 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005426 }
5427
honghaiz60347052016-05-31 18:29:12 -07005428 if (configuration.candidate_network_policy ==
5429 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005430 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005431 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005432 }
5433
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005434 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005435 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005436 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5437 }
5438
Karl Wibergfb3be392019-03-22 14:13:22 +01005439 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005440 // No step delay is used while allocating ports.
5441 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005442 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005443 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005444 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005445
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005446 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005447 for (auto& turn_server : turn_servers_copy) {
5448 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005449 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005450 // Call this last since it may create pooled allocator sessions using the
5451 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005452 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005453 stun_servers, std::move(turn_servers_copy),
5454 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5455 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005456 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005457
5458 InitializePortAllocatorResult res;
5459 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5460 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005461}
5462
deadbeef91dd5672016-05-18 16:55:30 -07005463bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005464 const cricket::ServerAddresses& stun_servers,
5465 const std::vector<cricket::RelayServerConfig>& turn_servers,
5466 IceTransportsType type,
5467 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005468 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005469 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005470 absl::optional<int> stun_candidate_keepalive_interval,
5471 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005472 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005473 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005474 // According to JSEP, after setLocalDescription, changing the candidate pool
5475 // size is not allowed, and changing the set of ICE servers will not result
5476 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005477 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005478 port_allocator_->FreezeCandidatePool();
5479 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005480 // Add the custom tls turn servers if they exist.
5481 auto turn_servers_copy = turn_servers;
5482 for (auto& turn_server : turn_servers_copy) {
5483 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5484 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005485 // Call this last since it may create pooled allocator sessions using the
5486 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005487 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005488 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5489 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005490}
5491
Steve Antonba818672017-11-06 10:21:57 -08005492cricket::ChannelManager* PeerConnection::channel_manager() const {
5493 return factory_->channel_manager();
5494}
5495
Elad Alon99c3fe52017-10-13 16:29:40 +02005496bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005497 std::unique_ptr<RtcEventLogOutput> output,
5498 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005499 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005500 if (!event_log_) {
5501 return false;
5502 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005503 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005504}
5505
5506void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005507 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005508 if (event_log_) {
5509 event_log_->StopLogging();
5510 }
ivoc14d5dbe2016-07-04 07:06:55 -07005511}
nisseeaabdf62017-05-05 02:23:02 -07005512
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005513cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005514 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005515 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005516 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005517 if (channel && channel->content_name() == content_name) {
5518 return channel;
5519 }
Steve Anton75737c02017-11-06 10:37:17 -08005520 }
5521 if (rtp_data_channel() &&
5522 rtp_data_channel()->content_name() == content_name) {
5523 return rtp_data_channel();
5524 }
5525 return nullptr;
5526}
5527
5528bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005529 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005530 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005531 RTC_LOG(LS_INFO)
5532 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005533 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005534 return false;
5535 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005536 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005537 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005538 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005539 return false;
5540 }
5541
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005542 absl::optional<rtc::SSLRole> dtls_role;
5543 if (sctp_mid_) {
5544 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5545 } else if (is_caller_) {
5546 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5547 }
Zhi Huange830e682018-03-30 10:48:35 -07005548 if (dtls_role) {
5549 *role = *dtls_role;
5550 return true;
5551 }
5552 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005553}
5554
5555bool PeerConnection::GetSslRole(const std::string& content_name,
5556 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005557 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005558 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005559 RTC_LOG(LS_INFO)
5560 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005561 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005562 return false;
5563 }
5564
Zhi Huange830e682018-03-30 10:48:35 -07005565 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5566 if (dtls_role) {
5567 *role = *dtls_role;
5568 return true;
5569 }
5570 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005571}
5572
Steve Antonf8470812017-12-04 10:46:21 -08005573void PeerConnection::SetSessionError(SessionError error,
5574 const std::string& error_desc) {
5575 RTC_DCHECK_RUN_ON(signaling_thread());
5576 if (error != session_error_) {
5577 session_error_ = error;
5578 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005579 }
5580}
5581
Zhi Huange830e682018-03-30 10:48:35 -07005582RTCError PeerConnection::UpdateSessionState(
5583 SdpType type,
5584 cricket::ContentSource source,
5585 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005586 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005587
5588 // If there's already a pending error then no state transition should happen.
5589 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005590 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005591
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005592 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005593 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005594 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005595 }
5596
5597 // Update the signaling state according to the specified state machine (see
5598 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005599 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005600 ChangeSignalingState(source == cricket::CS_LOCAL
5601 ? PeerConnectionInterface::kHaveLocalOffer
5602 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005603 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005604 ChangeSignalingState(source == cricket::CS_LOCAL
5605 ? PeerConnectionInterface::kHaveLocalPrAnswer
5606 : PeerConnectionInterface::kHaveRemotePrAnswer);
5607 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005608 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005609 ChangeSignalingState(PeerConnectionInterface::kStable);
5610 }
5611
5612 // Update internal objects according to the session description's media
5613 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005614 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005615 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005616 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005617 }
5618
Steve Anton8a006912017-12-04 15:25:56 -08005619 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005620}
5621
Steve Anton8a006912017-12-04 15:25:56 -08005622RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005623 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005624 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005625 const SessionDescriptionInterface* sdesc =
5626 (source == cricket::CS_LOCAL ? local_description()
5627 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005628 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005629
5630 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005631 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005632 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005633 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005634 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005635 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005636 continue;
5637 }
5638 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005639 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005640 if (!content_desc) {
5641 continue;
5642 }
5643 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005644 bool success = (source == cricket::CS_LOCAL)
5645 ? channel->SetLocalContent(content_desc, type, &error)
5646 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005647 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005649 }
5650 }
5651
5652 // If using the RtpDataChannel, push down the new SDP section for it too.
5653 if (rtp_data_channel_) {
5654 const ContentInfo* data_content =
5655 cricket::GetFirstDataContent(sdesc->description());
5656 if (data_content && !data_content->rejected) {
5657 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005658 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005659 if (data_desc) {
5660 std::string error;
5661 bool success =
5662 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005663 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005664 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005665 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005667 }
Steve Anton75737c02017-11-06 10:37:17 -08005668 }
5669 }
5670 }
Steve Antoned10bd92017-12-05 10:52:59 -08005671
Steve Anton75737c02017-11-06 10:37:17 -08005672 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5673 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005674 if (sctp_transport_ && local_description() && remote_description()) {
5675 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5676 local_description()->description());
5677 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5678 remote_description()->description());
5679 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005680 int max_message_size;
5681 // A remote max message size of zero means "any size supported".
5682 // We configure the connection with our own max message size.
5683 if (remote_sctp_description->max_message_size() == 0) {
5684 max_message_size = local_sctp_description->max_message_size();
5685 } else {
5686 max_message_size =
5687 std::min(local_sctp_description->max_message_size(),
5688 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005689 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005690 sctp_transport_->Start(local_sctp_description->port(),
5691 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005692 }
Steve Anton75737c02017-11-06 10:37:17 -08005693 }
Steve Antoned10bd92017-12-05 10:52:59 -08005694
Steve Anton8a006912017-12-04 15:25:56 -08005695 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005696}
5697
Steve Anton8a006912017-12-04 15:25:56 -08005698RTCError PeerConnection::PushdownTransportDescription(
5699 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005700 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005701 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005702
Zhi Huange830e682018-03-30 10:48:35 -07005703 if (source == cricket::CS_LOCAL) {
5704 const SessionDescriptionInterface* sdesc = local_description();
5705 RTC_DCHECK(sdesc);
5706 return transport_controller_->SetLocalDescription(type,
5707 sdesc->description());
5708 } else {
5709 const SessionDescriptionInterface* sdesc = remote_description();
5710 RTC_DCHECK(sdesc);
5711 return transport_controller_->SetRemoteDescription(type,
5712 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
Steve Anton75737c02017-11-06 10:37:17 -08005714}
5715
5716bool PeerConnection::GetTransportDescription(
5717 const SessionDescription* description,
5718 const std::string& content_name,
5719 cricket::TransportDescription* tdesc) {
5720 if (!description || !tdesc) {
5721 return false;
5722 }
5723 const TransportInfo* transport_info =
5724 description->GetTransportInfoByName(content_name);
5725 if (!transport_info) {
5726 return false;
5727 }
5728 *tdesc = transport_info->description;
5729 return true;
5730}
5731
Steve Anton75737c02017-11-06 10:37:17 -08005732cricket::IceConfig PeerConnection::ParseIceConfig(
5733 const PeerConnectionInterface::RTCConfiguration& config) const {
5734 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005735 switch (config.continual_gathering_policy) {
5736 case PeerConnectionInterface::GATHER_ONCE:
5737 gathering_policy = cricket::GATHER_ONCE;
5738 break;
5739 case PeerConnectionInterface::GATHER_CONTINUALLY:
5740 gathering_policy = cricket::GATHER_CONTINUALLY;
5741 break;
5742 default:
5743 RTC_NOTREACHED();
5744 gathering_policy = cricket::GATHER_ONCE;
5745 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005746
Steve Anton75737c02017-11-06 10:37:17 -08005747 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005748 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5749 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005750 ice_config.prioritize_most_likely_candidate_pairs =
5751 config.prioritize_most_likely_ice_candidate_pairs;
5752 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005753 RTCConfigurationToIceConfigOptionalInt(
5754 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005755 ice_config.continual_gathering_policy = gathering_policy;
5756 ice_config.presume_writable_when_fully_relayed =
5757 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005758 ice_config.ice_check_interval_strong_connectivity =
5759 config.ice_check_interval_strong_connectivity;
5760 ice_config.ice_check_interval_weak_connectivity =
5761 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005762 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005763 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5764 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005765 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005766 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005767 ice_config.regather_all_networks_interval_range =
5768 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005769 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005770 return ice_config;
5771}
5772
Steve Anton75737c02017-11-06 10:37:17 -08005773bool PeerConnection::SendData(const cricket::SendDataParams& params,
5774 const rtc::CopyOnWriteBuffer& payload,
5775 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005776 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005777 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5778 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5779 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005780 return false;
5781 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005782 if (media_transport_) {
5783 SendDataParams send_params;
5784 send_params.type = ToWebrtcDataMessageType(params.type);
5785 send_params.ordered = params.ordered;
5786 if (params.max_rtx_count >= 0) {
5787 send_params.max_rtx_count = params.max_rtx_count;
5788 } else if (params.max_rtx_ms >= 0) {
5789 send_params.max_rtx_ms = params.max_rtx_ms;
5790 }
5791 return media_transport_->SendData(params.sid, send_params, payload).ok();
5792 }
Steve Anton75737c02017-11-06 10:37:17 -08005793 return rtp_data_channel_
5794 ? rtp_data_channel_->SendData(params, payload, result)
5795 : network_thread()->Invoke<bool>(
5796 RTC_FROM_HERE,
5797 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005798 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005799}
5800
5801bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005802 RTC_DCHECK_RUN_ON(signaling_thread());
5803 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005804 // Don't log an error here, because DataChannels are expected to call
5805 // ConnectDataChannel in this state. It's the only way to initially tell
5806 // whether or not the underlying transport is ready.
5807 return false;
5808 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005809 if (media_transport_) {
5810 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5811 &DataChannel::OnChannelReady);
5812 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5813 &DataChannel::OnDataReceived);
5814 SignalMediaTransportChannelClosing_s.connect(
5815 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5816 SignalMediaTransportChannelClosed_s.connect(
5817 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5818 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005819 rtp_data_channel_->SignalReadyToSendData.connect(
5820 webrtc_data_channel, &DataChannel::OnChannelReady);
5821 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5822 &DataChannel::OnDataReceived);
5823 } else {
5824 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5825 &DataChannel::OnChannelReady);
5826 SignalSctpDataReceived.connect(webrtc_data_channel,
5827 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005828 SignalSctpClosingProcedureStartedRemotely.connect(
5829 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5830 SignalSctpClosingProcedureComplete.connect(
5831 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005832 }
5833 return true;
5834}
5835
5836void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005837 RTC_DCHECK_RUN_ON(signaling_thread());
5838 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005839 RTC_LOG(LS_ERROR)
5840 << "DisconnectDataChannel called when rtp_data_channel_ and "
5841 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005842 return;
5843 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005844 if (media_transport_) {
5845 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5846 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5847 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5848 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5849 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005850 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5851 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5852 } else {
5853 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5854 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005855 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5856 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005857 }
5858}
5859
5860void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005861 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005862 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005863 return;
5864 }
Steve Anton75737c02017-11-06 10:37:17 -08005865 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005866 RTC_LOG(LS_ERROR)
5867 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005868 return;
5869 }
5870 network_thread()->Invoke<void>(
5871 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005872 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005873}
5874
5875void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005876 if (media_transport_) {
5877 media_transport_->CloseChannel(sid);
5878 return;
5879 }
Steve Anton75737c02017-11-06 10:37:17 -08005880 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005881 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005882 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005883 return;
5884 }
5885 network_thread()->Invoke<void>(
5886 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005887 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005888}
5889
5890bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005891 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005892 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005893 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005894 sctp_ready_to_send_data_;
5895}
5896
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005897void PeerConnection::OnDataReceived(int channel_id,
5898 DataMessageType type,
5899 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005900 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005901 cricket::ReceiveDataParams params;
5902 params.sid = channel_id;
5903 params.type = ToCricketDataMessageType(type);
5904 media_transport_invoker_->AsyncInvoke<void>(
5905 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5906 RTC_DCHECK_RUN_ON(signaling_thread());
5907 if (!HandleOpenMessage_s(params, buffer)) {
5908 SignalMediaTransportReceivedData_s(params, buffer);
5909 }
5910 });
5911}
5912
5913void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005914 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005915 media_transport_invoker_->AsyncInvoke<void>(
5916 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5917 RTC_DCHECK_RUN_ON(signaling_thread());
5918 SignalMediaTransportChannelClosing_s(channel_id);
5919 });
5920}
5921
5922void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005923 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005924 media_transport_invoker_->AsyncInvoke<void>(
5925 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5926 RTC_DCHECK_RUN_ON(signaling_thread());
5927 SignalMediaTransportChannelClosed_s(channel_id);
5928 });
5929}
5930
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005931absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005932 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005933 if (sctp_mid_ && transport_controller_) {
5934 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5935 if (dtls_transport) {
5936 return dtls_transport->transport_name();
5937 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005938 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005939 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005940 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005941}
5942
Qingsi Wang72a43a12018-02-20 16:03:18 -08005943cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5944 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005945 network_thread()->Invoke<void>(
5946 RTC_FROM_HERE,
5947 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5948 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005949 return candidate_states_list;
5950}
5951
Steve Anton5dfde182018-02-06 10:34:40 -08005952std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5953 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005954 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005955 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005956 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005957 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005958 if (channel) {
5959 transport_names_by_mid[channel->content_name()] =
5960 channel->transport_name();
5961 }
Steve Anton75737c02017-11-06 10:37:17 -08005962 }
Steve Anton5dfde182018-02-06 10:34:40 -08005963 if (rtp_data_channel_) {
5964 transport_names_by_mid[rtp_data_channel_->content_name()] =
5965 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005966 }
5967 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005968 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005969 RTC_DCHECK(transport_name);
5970 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005971 }
Steve Anton5dfde182018-02-06 10:34:40 -08005972 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005973}
5974
Steve Anton5dfde182018-02-06 10:34:40 -08005975std::map<std::string, cricket::TransportStats>
5976PeerConnection::GetTransportStatsByNames(
5977 const std::set<std::string>& transport_names) {
5978 if (!network_thread()->IsCurrent()) {
5979 return network_thread()
5980 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5981 RTC_FROM_HERE,
5982 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005983 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005984 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005985 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5986 for (const std::string& transport_name : transport_names) {
5987 cricket::TransportStats transport_stats;
5988 bool success =
5989 transport_controller_->GetStats(transport_name, &transport_stats);
5990 if (success) {
5991 transport_stats_by_name[transport_name] = std::move(transport_stats);
5992 } else {
5993 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5994 << transport_name;
5995 }
5996 }
5997 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005998}
5999
6000bool PeerConnection::GetLocalCertificate(
6001 const std::string& transport_name,
6002 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006003 if (!certificate) {
6004 return false;
6005 }
6006 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6007 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006008}
6009
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006010std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006011 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006012 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006013}
6014
6015cricket::DataChannelType PeerConnection::data_channel_type() const {
6016 return data_channel_type_;
6017}
6018
6019bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006020 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006021 return pending_ice_restarts_.find(content_name) !=
6022 pending_ice_restarts_.end();
6023}
6024
Steve Anton75737c02017-11-06 10:37:17 -08006025bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6026 return transport_controller_->NeedsIceRestart(content_name);
6027}
6028
6029void PeerConnection::OnCertificateReady(
6030 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6031 transport_controller_->SetLocalCertificate(certificate);
6032}
6033
6034void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006035 SetSessionError(SessionError::kTransport,
6036 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006037}
6038
Alex Loiko9289eda2018-11-23 16:18:59 +00006039void PeerConnection::OnTransportControllerConnectionState(
6040 cricket::IceConnectionState state) {
6041 switch (state) {
6042 case cricket::kIceConnectionConnecting:
6043 // If the current state is Connected or Completed, then there were
6044 // writable channels but now there are not, so the next state must
6045 // be Disconnected.
6046 // kIceConnectionConnecting is currently used as the default,
6047 // un-connected state by the TransportController, so its only use is
6048 // detecting disconnections.
6049 if (ice_connection_state_ ==
6050 PeerConnectionInterface::kIceConnectionConnected ||
6051 ice_connection_state_ ==
6052 PeerConnectionInterface::kIceConnectionCompleted) {
6053 SetIceConnectionState(
6054 PeerConnectionInterface::kIceConnectionDisconnected);
6055 }
6056 break;
6057 case cricket::kIceConnectionFailed:
6058 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6059 break;
6060 case cricket::kIceConnectionConnected:
6061 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6062 "all transports are writable.";
6063 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6064 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6065 break;
6066 case cricket::kIceConnectionCompleted:
6067 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6068 "all transports are complete.";
6069 if (ice_connection_state_ !=
6070 PeerConnectionInterface::kIceConnectionConnected) {
6071 // If jumping directly from "checking" to "connected",
6072 // signal "connected" first.
6073 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6074 }
6075 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6076 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6077 ReportTransportStats();
6078 break;
6079 default:
6080 RTC_NOTREACHED();
6081 }
6082}
6083
Steve Anton75737c02017-11-06 10:37:17 -08006084void PeerConnection::OnTransportControllerCandidatesGathered(
6085 const std::string& transport_name,
6086 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006087 int sdp_mline_index;
6088 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006089 RTC_LOG(LS_ERROR)
6090 << "OnTransportControllerCandidatesGathered: content name "
6091 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006092 return;
6093 }
6094
6095 for (cricket::Candidates::const_iterator citer = candidates.begin();
6096 citer != candidates.end(); ++citer) {
6097 // Use transport_name as the candidate media id.
6098 std::unique_ptr<JsepIceCandidate> candidate(
6099 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6100 if (local_description()) {
6101 mutable_local_description()->AddCandidate(candidate.get());
6102 }
6103 OnIceCandidate(std::move(candidate));
6104 }
6105}
6106
6107void PeerConnection::OnTransportControllerCandidatesRemoved(
6108 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006109 // Sanity check.
6110 for (const cricket::Candidate& candidate : candidates) {
6111 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006112 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006113 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006114 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006115 return;
6116 }
6117 }
6118
6119 if (local_description()) {
6120 mutable_local_description()->RemoveCandidates(candidates);
6121 }
6122 OnIceCandidatesRemoved(candidates);
6123}
6124
6125void PeerConnection::OnTransportControllerDtlsHandshakeError(
6126 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006127 RTC_HISTOGRAM_ENUMERATION(
6128 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6129 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006130}
6131
Steve Antoned10bd92017-12-05 10:52:59 -08006132void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006133 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006134 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006135 if (channel && !channel->enabled()) {
6136 channel->Enable(true);
6137 }
Steve Anton75737c02017-11-06 10:37:17 -08006138 }
6139
Steve Anton4171afb2017-11-20 10:20:22 -08006140 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006141 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006142 }
Steve Anton75737c02017-11-06 10:37:17 -08006143}
6144
6145// Returns the media index for a local ice candidate given the content name.
6146bool PeerConnection::GetLocalCandidateMediaIndex(
6147 const std::string& content_name,
6148 int* sdp_mline_index) {
6149 if (!local_description() || !sdp_mline_index) {
6150 return false;
6151 }
6152
6153 bool content_found = false;
6154 const ContentInfos& contents = local_description()->description()->contents();
6155 for (size_t index = 0; index < contents.size(); ++index) {
6156 if (contents[index].name == content_name) {
6157 *sdp_mline_index = static_cast<int>(index);
6158 content_found = true;
6159 break;
6160 }
6161 }
6162 return content_found;
6163}
6164
6165bool PeerConnection::UseCandidatesInSessionDescription(
6166 const SessionDescriptionInterface* remote_desc) {
6167 if (!remote_desc) {
6168 return true;
6169 }
6170 bool ret = true;
6171
6172 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6173 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6174 for (size_t n = 0; n < candidates->count(); ++n) {
6175 const IceCandidateInterface* candidate = candidates->at(n);
6176 bool valid = false;
6177 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6178 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006179 RTC_LOG(LS_INFO)
6180 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006181 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006182 }
6183 continue;
6184 }
6185 ret = UseCandidate(candidate);
6186 if (!ret) {
6187 break;
6188 }
6189 }
6190 }
6191 return ret;
6192}
6193
6194bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006195 RTCErrorOr<const cricket::ContentInfo*> result =
6196 FindContentInfo(remote_description(), candidate);
6197 if (!result.ok()) {
6198 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6199 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006200 return false;
6201 }
Steve Anton75737c02017-11-06 10:37:17 -08006202 std::vector<cricket::Candidate> candidates;
6203 candidates.push_back(candidate->candidate());
6204 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006205 RTCError error = transport_controller_->AddRemoteCandidates(
6206 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006207 if (error.ok()) {
6208 // Candidates successfully submitted for checking.
6209 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6210 ice_connection_state_ ==
6211 PeerConnectionInterface::kIceConnectionDisconnected) {
6212 // If state is New, then the session has just gotten its first remote ICE
6213 // candidates, so go to Checking.
6214 // If state is Disconnected, the session is re-using old candidates or
6215 // receiving additional ones, so go to Checking.
6216 // If state is Connected, stay Connected.
6217 // TODO(bemasc): If state is Connected, and the new candidates are for a
6218 // newly added transport, then the state actually _should_ move to
6219 // checking. Add a way to distinguish that case.
6220 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6221 }
6222 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006223 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006224 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006225 }
6226 return true;
6227}
6228
Guido Urdaneta41633172019-05-23 20:12:29 +02006229RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6230 const SessionDescriptionInterface* description,
6231 const IceCandidateInterface* candidate) {
6232 if (candidate->sdp_mline_index() >= 0) {
6233 size_t mediacontent_index =
6234 static_cast<size_t>(candidate->sdp_mline_index());
6235 size_t content_size = description->description()->contents().size();
6236 if (mediacontent_index < content_size) {
6237 return &description->description()->contents()[mediacontent_index];
6238 } else {
6239 return RTCError(RTCErrorType::INVALID_RANGE,
6240 "Media line index (" +
6241 rtc::ToString(candidate->sdp_mline_index()) +
6242 ") out of range (number of mlines: " +
6243 rtc::ToString(content_size) + ").");
6244 }
6245 } else if (!candidate->sdp_mid().empty()) {
6246 auto& contents = description->description()->contents();
6247 auto it = absl::c_find_if(
6248 contents, [candidate](const cricket::ContentInfo& content_info) {
6249 return content_info.mid() == candidate->sdp_mid();
6250 });
6251 if (it == contents.end()) {
6252 return RTCError(
6253 RTCErrorType::INVALID_PARAMETER,
6254 "Mid " + candidate->sdp_mid() +
6255 " specified but no media section with that mid found.");
6256 } else {
6257 return &*it;
6258 }
6259 }
6260
6261 return RTCError(RTCErrorType::INVALID_PARAMETER,
6262 "Neither sdp_mline_index nor sdp_mid specified.");
6263}
6264
Steve Anton75737c02017-11-06 10:37:17 -08006265void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006266 // Destroy video channel first since it may have a pointer to the
6267 // voice channel.
6268 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006269 if (!video_info || video_info->rejected) {
6270 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006271 }
6272
Steve Anton6fec8802017-12-04 10:37:29 -08006273 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6274 if (!audio_info || audio_info->rejected) {
6275 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006276 }
6277
6278 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6279 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006280 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006281 }
6282}
6283
Steve Antondcc3c022017-12-22 16:02:54 -08006284RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6285 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006286 const cricket::ContentGroup* bundle_group = nullptr;
6287 if (configuration_.bundle_policy ==
6288 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006289 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006290 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6292 "max-bundle configured but session description "
6293 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006294 }
6295 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006296 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006297}
6298
6299RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006300 // Creating the media channels. Transports should already have been created
6301 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006302 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006303 if (voice && !voice->rejected &&
6304 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006305 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006306 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006307 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6308 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006309 }
6310 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6311 }
6312
Steve Antondcc3c022017-12-22 16:02:54 -08006313 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006314 if (video && !video->rejected &&
6315 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006316 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006317 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006318 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6319 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006320 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006321 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006322 }
6323
Steve Antondcc3c022017-12-22 16:02:54 -08006324 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006325 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006326 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006327 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006328 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6329 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006330 }
6331 }
6332
Steve Anton8a006912017-12-04 15:25:56 -08006333 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006334}
6335
Steve Anton4171afb2017-11-20 10:20:22 -08006336// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006337cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006338 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006339 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006340 MediaTransportConfig media_transport_config =
6341 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006342
Steve Anton75737c02017-11-06 10:37:17 -08006343 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006344 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006345 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6346 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006347 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006348 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006349 }
Steve Anton75737c02017-11-06 10:37:17 -08006350 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6351 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006352 voice_channel->SignalSentPacket.connect(this,
6353 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006354 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006355
Steve Antoneda6ccd2017-12-04 10:21:55 -08006356 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006357}
6358
Steve Anton4171afb2017-11-20 10:20:22 -08006359// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006360cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006361 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006362 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006363 MediaTransportConfig media_transport_config =
6364 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006365
Steve Anton75737c02017-11-06 10:37:17 -08006366 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006367 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006368 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6369 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006370 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006371 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006372 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006373 }
Steve Anton75737c02017-11-06 10:37:17 -08006374 video_channel->SignalDtlsSrtpSetupFailure.connect(
6375 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006376 video_channel->SignalSentPacket.connect(this,
6377 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006378 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006379
Steve Antoneda6ccd2017-12-04 10:21:55 -08006380 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006381}
6382
Zhi Huange830e682018-03-30 10:48:35 -07006383bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006384 switch (data_channel_type_) {
6385 case cricket::DCT_MEDIA_TRANSPORT:
6386 if (network_thread()->Invoke<bool>(
6387 RTC_FROM_HERE,
6388 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6389 this, mid))) {
6390 for (const auto& channel : sctp_data_channels_) {
6391 channel->OnTransportChannelCreated();
6392 }
6393 return true;
6394 }
Steve Anton75737c02017-11-06 10:37:17 -08006395 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006396 case cricket::DCT_SCTP:
6397 if (!sctp_factory_) {
6398 RTC_LOG(LS_ERROR)
6399 << "Trying to create SCTP transport, but didn't compile with "
6400 "SCTP support (HAVE_SCTP)";
6401 return false;
6402 }
6403 if (!network_thread()->Invoke<bool>(
6404 RTC_FROM_HERE,
6405 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6406 return false;
6407 }
6408 for (const auto& channel : sctp_data_channels_) {
6409 channel->OnTransportChannelCreated();
6410 }
6411 return true;
6412 case cricket::DCT_RTP:
6413 default:
6414 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6415 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6416 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006417 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006418 if (!rtp_data_channel_) {
6419 return false;
6420 }
6421 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6422 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6423 rtp_data_channel_->SignalSentPacket.connect(
6424 this, &PeerConnection::OnSentPacket_w);
6425 rtp_data_channel_->SetRtpTransport(rtp_transport);
6426 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006427 }
6428
Steve Anton75737c02017-11-06 10:37:17 -08006429 return true;
6430}
6431
6432Call::Stats PeerConnection::GetCallStats() {
6433 if (!worker_thread()->IsCurrent()) {
6434 return worker_thread()->Invoke<Call::Stats>(
6435 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6436 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006437 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006438 if (call_) {
6439 return call_->GetStats();
6440 } else {
6441 return Call::Stats();
6442 }
6443}
6444
Zhi Huange830e682018-03-30 10:48:35 -07006445bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006446 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006447 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006448 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6449 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006450 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006451 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006452 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006453 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6454 sctp_factory_->CreateSctpTransport(dtls_transport);
6455 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006456 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006457 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006458 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006459 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006460 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006461 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6462 // another thread. Would be nice if there was a helper class similar to
6463 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6464 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006465 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006466 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006467 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006468 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006469 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006470 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6471 std::move(cricket_sctp_transport));
6472 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006473 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006474}
6475
6476void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006477 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006478 sctp_transport_->Clear();
6479 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006480 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006481 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006482}
6483
6484void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006485 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006486 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006487 // Note: Cannot use rtc::Bind here because it will grab a reference to
6488 // PeerConnection and potentially cause PeerConnection to live longer than
6489 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6490 // be destroyed before PeerConnection is destroyed, and at that point all
6491 // pending tasks will be cleared.
6492 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6493 OnSctpTransportReadyToSendData_s(true);
6494 });
6495}
6496
6497void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006498 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006499 sctp_ready_to_send_data_ = ready;
6500 SignalSctpReadyToSendData(ready);
6501}
6502
6503void PeerConnection::OnSctpTransportDataReceived_n(
6504 const cricket::ReceiveDataParams& params,
6505 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006506 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006507 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006508 // Note: Cannot use rtc::Bind here because it will grab a reference to
6509 // PeerConnection and potentially cause PeerConnection to live longer than
6510 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6511 // be destroyed before PeerConnection is destroyed, and at that point all
6512 // pending tasks will be cleared.
6513 sctp_invoker_->AsyncInvoke<void>(
6514 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6515 OnSctpTransportDataReceived_s(params, payload);
6516 });
6517}
6518
6519void PeerConnection::OnSctpTransportDataReceived_s(
6520 const cricket::ReceiveDataParams& params,
6521 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006522 RTC_DCHECK_RUN_ON(signaling_thread());
6523 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006524 SignalSctpDataReceived(params, payload);
6525 }
6526}
6527
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006528void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006529 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006530 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006531 sctp_invoker_->AsyncInvoke<void>(
6532 RTC_FROM_HERE, signaling_thread(),
6533 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006534 &SignalSctpClosingProcedureStartedRemotely, sid));
6535}
6536
6537void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006538 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006539 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006540 sctp_invoker_->AsyncInvoke<void>(
6541 RTC_FROM_HERE, signaling_thread(),
6542 rtc::Bind(&sigslot::signal1<int>::operator(),
6543 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006544}
6545
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006546bool PeerConnection::SetupMediaTransportForDataChannels_n(
6547 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006548 media_transport_ =
6549 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006550 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006551 RTC_LOG(LS_ERROR)
6552 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006553 return false;
6554 }
6555
6556 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6557 media_transport_->SetDataSink(this);
6558 media_transport_data_mid_ = mid;
6559 transport_controller_->SignalMediaTransportStateChanged.connect(
6560 this, &PeerConnection::OnMediaTransportStateChanged_n);
6561 // Check the initial state right away, in case transport is already writable.
6562 OnMediaTransportStateChanged_n();
6563 return true;
6564}
6565
6566void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6567 if (!media_transport_) {
6568 return;
6569 }
6570 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6571 media_transport_data_mid_.reset();
6572 media_transport_->SetDataSink(nullptr);
6573 media_transport_invoker_ = nullptr;
6574 media_transport_ = nullptr;
6575}
6576
6577void PeerConnection::OnMediaTransportStateChanged_n() {
6578 if (!media_transport_data_mid_ ||
6579 transport_controller_->GetMediaTransportState(
6580 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6581 return;
6582 }
6583 media_transport_invoker_->AsyncInvoke<void>(
6584 RTC_FROM_HERE, signaling_thread(), [this] {
6585 RTC_DCHECK_RUN_ON(signaling_thread());
6586 media_transport_ready_to_send_data_ = true;
6587 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6588 });
6589}
6590
Steve Anton75737c02017-11-06 10:37:17 -08006591// Returns false if bundle is enabled and rtcp_mux is disabled.
6592bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6593 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6594 if (!bundle_enabled)
6595 return true;
6596
6597 const cricket::ContentGroup* bundle_group =
6598 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6599 RTC_DCHECK(bundle_group != NULL);
6600
6601 const cricket::ContentInfos& contents = desc->contents();
6602 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6603 citer != contents.end(); ++citer) {
6604 const cricket::ContentInfo* content = (&*citer);
6605 RTC_DCHECK(content != NULL);
6606 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006607 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006608 if (!HasRtcpMuxEnabled(content))
6609 return false;
6610 }
6611 }
6612 // RTCP-MUX is enabled in all the contents.
6613 return true;
6614}
6615
6616bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006617 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006618}
6619
Steve Anton06817cd2018-12-18 15:55:30 -08006620static RTCError ValidateMids(const cricket::SessionDescription& description) {
6621 std::set<std::string> mids;
6622 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006623 if (content.name.empty()) {
6624 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6625 "A media section is missing a MID attribute.");
6626 }
Steve Anton06817cd2018-12-18 15:55:30 -08006627 if (!mids.insert(content.name).second) {
6628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6629 "Duplicate a=mid value '" + content.name + "'.");
6630 }
6631 }
6632 return RTCError::OK();
6633}
6634
Steve Anton8a006912017-12-04 15:25:56 -08006635RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006636 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006637 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006638 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006639 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006640 }
6641
6642 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006644 }
6645
Steve Anton3828c062017-12-06 10:34:51 -08006646 SdpType type = sdesc->GetType();
6647 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6648 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006649 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006650 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006651 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006652 }
6653
Steve Anton06817cd2018-12-18 15:55:30 -08006654 RTCError error = ValidateMids(*sdesc->description());
6655 if (!error.ok()) {
6656 return error;
6657 }
6658
Steve Anton75737c02017-11-06 10:37:17 -08006659 // Verify crypto settings.
6660 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006661 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6662 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006663 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006664 if (!crypto_error.ok()) {
6665 return crypto_error;
6666 }
Steve Anton75737c02017-11-06 10:37:17 -08006667 }
6668
6669 // Verify ice-ufrag and ice-pwd.
6670 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6672 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006673 }
6674
6675 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006676 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6677 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006678 }
6679
6680 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6681 // m-lines that do not rtcp-mux enabled.
6682
6683 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006684 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006685 // With an answer we want to compare the new answer session description with
6686 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006687 const cricket::SessionDescription* offer_desc =
6688 (source == cricket::CS_LOCAL) ? remote_description()->description()
6689 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006690 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6691 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6692 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006693 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6694 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006695 }
6696 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006697 // The re-offers should respect the order of m= sections in current
6698 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006699 // With a re-offer, either the current local or current remote descriptions
6700 // could be the most up to date, so we would like to check against both of
6701 // them if they exist. It could be the case that one of them has a 0 port
6702 // for a media section, but the other does not. This is important to check
6703 // against in the case that we are recycling an m= section.
6704 const cricket::SessionDescription* current_desc = nullptr;
6705 const cricket::SessionDescription* secondary_current_desc = nullptr;
6706 if (local_description()) {
6707 current_desc = local_description()->description();
6708 if (remote_description()) {
6709 secondary_current_desc = remote_description()->description();
6710 }
6711 } else if (remote_description()) {
6712 current_desc = remote_description()->description();
6713 }
Steve Anton75737c02017-11-06 10:37:17 -08006714 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006715 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6716 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006717 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6718 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006719 }
6720 }
6721
Steve Antonba42e992018-04-09 14:10:01 -07006722 if (IsUnifiedPlan()) {
6723 // Ensure that each audio and video media section has at most one
6724 // "StreamParams". This will return an error if receiving a session
6725 // description from a "Plan B" endpoint which adds multiple tracks of the
6726 // same type. With Unified Plan, there can only be at most one track per
6727 // media section.
6728 for (const ContentInfo& content : sdesc->description()->contents()) {
6729 const MediaContentDescription& desc = *content.description;
6730 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6731 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6732 desc.streams().size() > 1u) {
6733 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6734 "Media section has more than one track specified "
6735 "with a=ssrc lines which is not supported with "
6736 "Unified Plan.");
6737 }
6738 }
6739 }
6740
Steve Anton8a006912017-12-04 15:25:56 -08006741 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006742}
6743
Steve Anton3828c062017-12-06 10:34:51 -08006744bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006745 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006746 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006747 return (state == PeerConnectionInterface::kStable) ||
6748 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006749 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006750 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006751 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6752 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6753 }
6754}
6755
Steve Anton3828c062017-12-06 10:34:51 -08006756bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006757 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006758 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006759 return (state == PeerConnectionInterface::kStable) ||
6760 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006761 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006762 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006763 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6764 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6765 }
6766}
6767
Steve Antonf8470812017-12-04 10:46:21 -08006768const char* PeerConnection::SessionErrorToString(SessionError error) const {
6769 switch (error) {
6770 case SessionError::kNone:
6771 return "ERROR_NONE";
6772 case SessionError::kContent:
6773 return "ERROR_CONTENT";
6774 case SessionError::kTransport:
6775 return "ERROR_TRANSPORT";
6776 }
6777 RTC_NOTREACHED();
6778 return "";
6779}
6780
Steve Anton75737c02017-11-06 10:37:17 -08006781std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006782 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006783 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6784 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006785 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006786}
6787
Steve Anton8e20f172018-03-06 10:55:04 -08006788void PeerConnection::ReportSdpFormatReceived(
6789 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006790 int num_audio_mlines = 0;
6791 int num_video_mlines = 0;
6792 int num_audio_tracks = 0;
6793 int num_video_tracks = 0;
6794 for (const ContentInfo& content : remote_offer.description()->contents()) {
6795 cricket::MediaType media_type = content.media_description()->type();
6796 int num_tracks = std::max(
6797 1, static_cast<int>(content.media_description()->streams().size()));
6798 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6799 num_audio_mlines += 1;
6800 num_audio_tracks += num_tracks;
6801 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6802 num_video_mlines += 1;
6803 num_video_tracks += num_tracks;
6804 }
6805 }
6806 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6807 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6808 format = kSdpFormatReceivedComplexUnifiedPlan;
6809 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6810 format = kSdpFormatReceivedComplexPlanB;
6811 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6812 format = kSdpFormatReceivedSimple;
6813 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006814 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6815 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006816}
6817
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006818void PeerConnection::NoteUsageEvent(UsageEvent event) {
6819 RTC_DCHECK_RUN_ON(signaling_thread());
6820 usage_event_accumulator_ |= static_cast<int>(event);
6821}
6822
6823void PeerConnection::ReportUsagePattern() const {
6824 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006825 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6826 usage_event_accumulator_,
6827 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006828 const int bad_bits =
6829 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6830 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6831 const int good_bits =
6832 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6833 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6834 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6835 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6836 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006837 // If called after close(), we can't report, because observer may have
6838 // been deallocated, and therefore pointer is null. Write to log instead.
6839 if (observer_) {
6840 Observer()->OnInterestingUsage(usage_event_accumulator_);
6841 } else {
6842 RTC_LOG(LS_INFO) << "Interesting usage signature "
6843 << usage_event_accumulator_
6844 << " observed after observer shutdown";
6845 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006846 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006847}
6848
Steve Anton0ffaaa22018-02-23 10:31:30 -08006849void PeerConnection::ReportNegotiatedSdpSemantics(
6850 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006851 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006852 switch (answer.description()->msid_signaling()) {
6853 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006854 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006855 break;
6856 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006857 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006858 break;
6859 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006860 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006861 break;
6862 case cricket::kMsidSignalingMediaSection |
6863 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006864 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006865 break;
6866 default:
6867 RTC_NOTREACHED();
6868 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006869 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6870 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006871}
6872
Steve Anton75737c02017-11-06 10:37:17 -08006873// We need to check the local/remote description for the Transport instead of
6874// the session, because a new Transport added during renegotiation may have
6875// them unset while the session has them set from the previous negotiation.
6876// Not doing so may trigger the auto generation of transport description and
6877// mess up DTLS identity information, ICE credential, etc.
6878bool PeerConnection::ReadyToUseRemoteCandidate(
6879 const IceCandidateInterface* candidate,
6880 const SessionDescriptionInterface* remote_desc,
6881 bool* valid) {
6882 *valid = true;
6883
6884 const SessionDescriptionInterface* current_remote_desc =
6885 remote_desc ? remote_desc : remote_description();
6886
6887 if (!current_remote_desc) {
6888 return false;
6889 }
6890
Guido Urdaneta41633172019-05-23 20:12:29 +02006891 RTCErrorOr<const cricket::ContentInfo*> result =
6892 FindContentInfo(current_remote_desc, candidate);
6893 if (!result.ok()) {
6894 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6895 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006896
6897 *valid = false;
6898 return false;
6899 }
6900
Guido Urdaneta41633172019-05-23 20:12:29 +02006901 std::string transport_name = GetTransportName(result.value()->name);
6902 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006903}
6904
6905bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006906 return !configuration_.use_datagram_transport &&
6907 (dtls_enabled_ ||
6908 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006909}
6910
6911void PeerConnection::OnTransportControllerGatheringState(
6912 cricket::IceGatheringState state) {
6913 RTC_DCHECK(signaling_thread()->IsCurrent());
6914 if (state == cricket::kIceGatheringGathering) {
6915 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6916 } else if (state == cricket::kIceGatheringComplete) {
6917 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6918 }
6919}
6920
6921void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006922 std::map<std::string, std::set<cricket::MediaType>>
6923 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006924 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006925 if (transceiver->internal()->channel()) {
6926 const std::string& transport_name =
6927 transceiver->internal()->channel()->transport_name();
6928 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006929 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006930 }
Steve Anton75737c02017-11-06 10:37:17 -08006931 }
6932 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006933 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6934 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006935 }
Zhi Huange830e682018-03-30 10:48:35 -07006936
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006937 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006938 if (transport_name) {
6939 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006940 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006941 }
Zhi Huange830e682018-03-30 10:48:35 -07006942
Steve Antonc7b964c2018-02-01 14:39:45 -08006943 for (const auto& entry : media_types_by_transport_name) {
6944 const std::string& transport_name = entry.first;
6945 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006946 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006947 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006948 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006949 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006950 }
6951 }
6952}
6953// Walk through the ConnectionInfos to gather best connection usage
6954// for IPv4 and IPv6.
6955void PeerConnection::ReportBestConnectionState(
6956 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006957 for (const cricket::TransportChannelStats& channel_stats :
6958 stats.channel_stats) {
6959 for (const cricket::ConnectionInfo& connection_info :
6960 channel_stats.connection_infos) {
6961 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006962 continue;
6963 }
6964
Steve Antonc7b964c2018-02-01 14:39:45 -08006965 const cricket::Candidate& local = connection_info.local_candidate;
6966 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006967
6968 // Increment the counter for IceCandidatePairType.
6969 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6970 (local.type() == RELAY_PORT_TYPE &&
6971 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006972 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6973 GetIceCandidatePairCounter(local, remote),
6974 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006975 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006976 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6977 GetIceCandidatePairCounter(local, remote),
6978 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006979 } else {
6980 RTC_CHECK(0);
6981 }
Steve Anton75737c02017-11-06 10:37:17 -08006982
6983 // Increment the counter for IP type.
6984 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006985 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6986 kBestConnections_IPv4,
6987 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006988 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006989 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6990 kBestConnections_IPv6,
6991 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006992 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006993 RTC_CHECK(!local.address().hostname().empty() &&
6994 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006995 }
6996
6997 return;
6998 }
6999 }
7000}
7001
7002void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007003 const cricket::TransportStats& stats,
7004 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007005 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7006 return;
7007 }
7008
7009 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7010 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7011 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7012 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7013 return;
7014 }
7015
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007016 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7017 for (cricket::MediaType media_type : media_types) {
7018 switch (media_type) {
7019 case cricket::MEDIA_TYPE_AUDIO:
7020 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7021 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7022 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7023 break;
7024 case cricket::MEDIA_TYPE_VIDEO:
7025 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7026 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7027 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7028 break;
7029 case cricket::MEDIA_TYPE_DATA:
7030 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7031 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7032 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7033 break;
7034 default:
7035 RTC_NOTREACHED();
7036 continue;
7037 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007038 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007039 }
7040
7041 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7042 for (cricket::MediaType media_type : media_types) {
7043 switch (media_type) {
7044 case cricket::MEDIA_TYPE_AUDIO:
7045 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7046 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7047 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7048 break;
7049 case cricket::MEDIA_TYPE_VIDEO:
7050 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7051 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7052 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7053 break;
7054 case cricket::MEDIA_TYPE_DATA:
7055 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7056 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7057 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7058 break;
7059 default:
7060 RTC_NOTREACHED();
7061 continue;
7062 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007063 }
Steve Anton75737c02017-11-06 10:37:17 -08007064 }
7065}
7066
7067void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007068 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007069 RTC_DCHECK(call_);
7070 call_->OnSentPacket(sent_packet);
7071}
7072
7073const std::string PeerConnection::GetTransportName(
7074 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007075 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007076 if (channel) {
7077 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007078 }
Steve Anton6fec8802017-12-04 10:37:29 -08007079 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007080 RTC_DCHECK(sctp_mid_);
7081 if (content_name == *sctp_mid_) {
7082 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007083 }
7084 }
7085 // Return an empty string if failed to retrieve the transport name.
7086 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007087}
7088
Steve Anton6fec8802017-12-04 10:37:29 -08007089void PeerConnection::DestroyTransceiverChannel(
7090 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7091 transceiver) {
7092 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007093
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007094 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007095 if (channel) {
7096 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007097 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007098 }
7099}
7100
7101void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007102 if (rtp_data_channel_) {
7103 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007104 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007105 rtp_data_channel_ = nullptr;
7106 }
7107
7108 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7109 // grab a reference to this PeerConnection. If this is called from the
7110 // PeerConnection destructor, the RefCountedObject vtable will have already
7111 // been destroyed (since it is a subclass of PeerConnection) and using
7112 // rtc::Bind will cause "Pure virtual function called" error to appear.
7113
7114 if (sctp_transport_) {
7115 OnDataChannelDestroyed();
7116 network_thread()->Invoke<void>(RTC_FROM_HERE,
7117 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007118 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007119 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007120
7121 if (media_transport_) {
7122 OnDataChannelDestroyed();
7123 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7124 RTC_DCHECK_RUN_ON(network_thread());
7125 TeardownMediaTransportForDataChannels_n();
7126 });
7127 }
Steve Anton6fec8802017-12-04 10:37:29 -08007128}
7129
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007130void PeerConnection::DestroyChannelInterface(
7131 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007132 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007133 switch (channel->media_type()) {
7134 case cricket::MEDIA_TYPE_AUDIO:
7135 channel_manager()->DestroyVoiceChannel(
7136 static_cast<cricket::VoiceChannel*>(channel));
7137 break;
7138 case cricket::MEDIA_TYPE_VIDEO:
7139 channel_manager()->DestroyVideoChannel(
7140 static_cast<cricket::VideoChannel*>(channel));
7141 break;
7142 case cricket::MEDIA_TYPE_DATA:
7143 channel_manager()->DestroyRtpDataChannel(
7144 static_cast<cricket::RtpDataChannel*>(channel));
7145 break;
7146 default:
7147 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7148 break;
7149 }
Zhi Huange830e682018-03-30 10:48:35 -07007150}
Steve Anton6fec8802017-12-04 10:37:29 -08007151
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007152bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007153 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007154 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007155 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007156 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007157 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007158 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007159 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007160 auto base_channel = GetChannel(mid);
7161 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007162 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007163 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007164 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007165 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007166 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007167
Karl Wiberg5966c502019-02-21 23:55:09 +01007168 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007169 // Only pass media transport to call object if media transport is used
7170 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007171 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007172 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007173
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007174 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007175}
7176
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007177void PeerConnection::OnSetStreams() {
7178 RTC_DCHECK_RUN_ON(signaling_thread());
7179 if (IsUnifiedPlan())
7180 UpdateNegotiationNeeded();
7181}
7182
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007183PeerConnectionObserver* PeerConnection::Observer() const {
7184 // In earlier production code, the pointer was not cleared on close,
7185 // which might have led to undefined behavior if the observer was not
7186 // deallocated, or strange crashes if it was.
7187 // We use CHECK in order to catch such behavior if it exists.
7188 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7189 RTC_CHECK(observer_);
7190 return observer_;
7191}
7192
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007193CryptoOptions PeerConnection::GetCryptoOptions() {
7194 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7195 // after it has been removed.
7196 return configuration_.crypto_options.has_value()
7197 ? *configuration_.crypto_options
7198 : factory_->options().crypto_options;
7199}
7200
Harald Alvestrand89061872018-01-02 14:08:34 +01007201void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007202 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007203 if (stats_collector_) {
7204 stats_collector_->ClearCachedStatsReport();
7205 }
7206}
7207
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007208void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007209 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7210 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007211}
7212
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007213void PeerConnection::UpdateNegotiationNeeded() {
7214 RTC_DCHECK_RUN_ON(signaling_thread());
7215 if (!IsUnifiedPlan()) {
7216 Observer()->OnRenegotiationNeeded();
7217 return;
7218 }
7219
7220 // If connection's [[IsClosed]] slot is true, abort these steps.
7221 if (IsClosed())
7222 return;
7223
7224 // If connection's signaling state is not "stable", abort these steps.
7225 if (signaling_state() != kStable)
7226 return;
7227
7228 // NOTE
7229 // The negotiation-needed flag will be updated once the state transitions to
7230 // "stable", as part of the steps for setting an RTCSessionDescription.
7231
7232 // If the result of checking if negotiation is needed is false, clear the
7233 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7234 // to false, and abort these steps.
7235 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7236 if (!is_negotiation_needed) {
7237 is_negotiation_needed_ = false;
7238 return;
7239 }
7240
7241 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7242 // steps.
7243 if (is_negotiation_needed_)
7244 return;
7245
7246 // Set connection's [[NegotiationNeeded]] slot to true.
7247 is_negotiation_needed_ = true;
7248
7249 // Queue a task that runs the following steps:
7250 // If connection's [[IsClosed]] slot is true, abort these steps.
7251 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7252 // Fire an event named negotiationneeded at connection.
7253 Observer()->OnRenegotiationNeeded();
7254}
7255
7256bool PeerConnection::CheckIfNegotiationIsNeeded() {
7257 RTC_DCHECK_RUN_ON(signaling_thread());
7258 // 1. If any implementation-specific negotiation is required, as described at
7259 // the start of this section, return true.
7260
7261 // 2. Let description be connection.[[CurrentLocalDescription]].
7262 const SessionDescriptionInterface* description = current_local_description();
7263 if (!description)
7264 return true;
7265
7266 // 3. If connection has created any RTCDataChannels, and no m= section in
7267 // description has been negotiated yet for data, return true.
7268 if (!sctp_data_channels_.empty()) {
7269 if (!cricket::GetFirstDataContent(description->description()->contents()))
7270 return true;
7271 }
7272
7273 // 4. For each transceiver in connection's set of transceivers, perform the
7274 // following checks:
7275 for (const auto& transceiver : transceivers_) {
7276 const ContentInfo* current_local_msection =
7277 FindTransceiverMSection(transceiver.get(), description);
7278
7279 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7280 transceiver.get(), current_remote_description());
7281
7282 // 4.3 If transceiver is stopped and is associated with an m= section,
7283 // but the associated m= section is not yet rejected in
7284 // connection.[[CurrentLocalDescription]] or
7285 // connection.[[CurrentRemoteDescription]], return true.
7286 if (transceiver->stopped()) {
7287 if (current_local_msection && !current_local_msection->rejected &&
7288 ((current_remote_msection && !current_remote_msection->rejected) ||
7289 !current_remote_msection)) {
7290 return true;
7291 }
7292 continue;
7293 }
7294
7295 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7296 // section in description, return true.
7297 if (!current_local_msection)
7298 return true;
7299
7300 const MediaContentDescription* current_local_media_description =
7301 current_local_msection->media_description();
7302 // 4.2 If transceiver isn't stopped and is associated with an m= section
7303 // in description then perform the following checks:
7304
7305 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7306 // associated m= section in description either doesn't contain a single
7307 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7308 // m= section, or the MSID values themselves, differ from what is in
7309 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7310 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7311 if (current_local_media_description->streams().size() == 0)
7312 return true;
7313
7314 std::vector<std::string> msection_msids;
7315 for (const auto& stream : current_local_media_description->streams()) {
7316 for (const std::string& msid : stream.stream_ids())
7317 msection_msids.push_back(msid);
7318 }
7319
7320 std::vector<std::string> transceiver_msids =
7321 transceiver->sender()->stream_ids();
7322 if (msection_msids.size() != transceiver_msids.size())
7323 return true;
7324
7325 absl::c_sort(transceiver_msids);
7326 absl::c_sort(msection_msids);
7327 if (transceiver_msids != msection_msids)
7328 return true;
7329 }
7330
7331 // 4.2.2 If description is of type "offer", and the direction of the
7332 // associated m= section in neither connection.[[CurrentLocalDescription]]
7333 // nor connection.[[CurrentRemoteDescription]] matches
7334 // transceiver.[[Direction]], return true.
7335 if (description->GetType() == SdpType::kOffer) {
7336 if (!current_remote_description())
7337 return true;
7338
7339 if (!current_remote_msection)
7340 return true;
7341
7342 RtpTransceiverDirection current_local_direction =
7343 current_local_media_description->direction();
7344 RtpTransceiverDirection current_remote_direction =
7345 current_remote_msection->media_description()->direction();
7346 if (transceiver->direction() != current_local_direction &&
7347 transceiver->direction() !=
7348 RtpTransceiverDirectionReversed(current_remote_direction)) {
7349 return true;
7350 }
7351 }
7352
7353 // 4.2.3 If description is of type "answer", and the direction of the
7354 // associated m= section in the description does not match
7355 // transceiver.[[Direction]] intersected with the offered direction (as
7356 // described in [JSEP] (section 5.3.1.)), return true.
7357 if (description->GetType() == SdpType::kAnswer) {
7358 if (!remote_description())
7359 return true;
7360
7361 const ContentInfo* offered_remote_msection =
7362 FindTransceiverMSection(transceiver.get(), remote_description());
7363
7364 RtpTransceiverDirection offered_direction =
7365 offered_remote_msection
7366 ? offered_remote_msection->media_description()->direction()
7367 : RtpTransceiverDirection::kInactive;
7368
7369 if (current_local_media_description->direction() !=
7370 (RtpTransceiverDirectionIntersection(
7371 transceiver->direction(),
7372 RtpTransceiverDirectionReversed(offered_direction)))) {
7373 return true;
7374 }
7375 }
7376 }
7377
7378 // If all the preceding checks were performed and true was not returned,
7379 // nothing remains to be negotiated; return false.
7380 return false;
7381}
7382
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007383} // namespace webrtc