blob: deaff5d613662681eaffc9691b89e52a8d8eebd3 [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;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700767 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100768 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800769 };
770 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
771 "Did you add something to RTCConfiguration and forget to "
772 "update operator==?");
773 return type == o.type && servers == o.servers &&
774 bundle_policy == o.bundle_policy &&
775 rtcp_mux_policy == o.rtcp_mux_policy &&
776 tcp_candidate_policy == o.tcp_candidate_policy &&
777 candidate_network_policy == o.candidate_network_policy &&
778 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
779 audio_jitter_buffer_fast_accelerate ==
780 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100781 audio_jitter_buffer_min_delay_ms ==
782 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100783 audio_jitter_buffer_enable_rtx_handling ==
784 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800785 ice_connection_receiving_timeout ==
786 o.ice_connection_receiving_timeout &&
787 ice_backup_candidate_pair_ping_interval ==
788 o.ice_backup_candidate_pair_ping_interval &&
789 continual_gathering_policy == o.continual_gathering_policy &&
790 certificates == o.certificates &&
791 prioritize_most_likely_ice_candidate_pairs ==
792 o.prioritize_most_likely_ice_candidate_pairs &&
793 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800794 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700795 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100796 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800797 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800798 screencast_min_bitrate == o.screencast_min_bitrate &&
799 combined_audio_video_bwe == o.combined_audio_video_bwe &&
800 enable_dtls_srtp == o.enable_dtls_srtp &&
801 ice_candidate_pool_size == o.ice_candidate_pool_size &&
802 prune_turn_ports == o.prune_turn_ports &&
803 presume_writable_when_fully_relayed ==
804 o.presume_writable_when_fully_relayed &&
805 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800806 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800807 ice_check_interval_strong_connectivity ==
808 o.ice_check_interval_strong_connectivity &&
809 ice_check_interval_weak_connectivity ==
810 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700811 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700812 ice_unwritable_timeout == o.ice_unwritable_timeout &&
813 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800814 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800815 stun_candidate_keepalive_interval ==
816 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200817 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800818 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800819 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700820 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700821 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700822 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700823 use_media_transport_for_data_channels ==
824 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100825 crypto_options == o.crypto_options &&
826 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800827}
828
829bool PeerConnectionInterface::RTCConfiguration::operator!=(
830 const PeerConnectionInterface::RTCConfiguration& o) const {
831 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800832}
833
zhihuang8f65cdf2016-05-06 18:40:30 -0700834// Generate a RTCP CNAME when a PeerConnection is created.
835std::string GenerateRtcpCname() {
836 std::string cname;
837 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100838 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800839 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700840 }
841 return cname;
842}
843
zhihuang1c378ed2017-08-17 14:10:50 -0700844bool ValidateOfferAnswerOptions(
845 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
846 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
847 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700848}
849
zhihuang1c378ed2017-08-17 14:10:50 -0700850// From |rtc_options|, fill parts of |session_options| shared by all generated
851// m= sections (in other words, nothing that involves a map/array).
852void ExtractSharedMediaSessionOptions(
853 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
854 cricket::MediaSessionOptions* session_options) {
855 session_options->vad_enabled = rtc_options.voice_activity_detection;
856 session_options->bundle_enabled = rtc_options.use_rtp_mux;
857}
zhihuanga77e6bb2017-08-14 18:17:48 -0700858
zhihuang38ede132017-06-15 12:52:32 -0700859PeerConnection::PeerConnection(PeerConnectionFactory* factory,
860 std::unique_ptr<RtcEventLog> event_log,
861 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700863 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100864 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700865 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700866 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700867 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100868 call_(std::move(call)),
869 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870
871PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100872 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800873 RTC_DCHECK_RUN_ON(signaling_thread());
874
Steve Anton8af21862017-12-15 11:20:13 -0800875 // Need to stop transceivers before destroying the stats collector because
876 // AudioRtpSender has a reference to the StatsCollector it will update when
877 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100878 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800879 transceiver->Stop();
880 }
Steve Anton4171afb2017-11-20 10:20:22 -0800881
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700882 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800883 if (stats_collector_) {
884 stats_collector_->WaitForPendingRequest();
885 stats_collector_ = nullptr;
886 }
Steve Anton75737c02017-11-06 10:37:17 -0800887
Steve Anton8af21862017-12-15 11:20:13 -0800888 // Don't destroy BaseChannels until after stats has been cleaned up so that
889 // the last stats request can still read from the channels.
890 DestroyAllChannels();
891
Mirko Bonadei675513b2017-11-09 11:09:25 +0100892 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800893
894 webrtc_session_desc_factory_.reset();
895 sctp_invoker_.reset();
896 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800897 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800898 transport_controller_.reset();
899
deadbeef91dd5672016-05-18 16:55:30 -0700900 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100901 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
902 RTC_DCHECK_RUN_ON(network_thread());
903 port_allocator_.reset();
904 });
eladalon248fd4f2017-09-06 05:18:15 -0700905 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700906 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100907 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700908 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800909 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700910 event_log_.reset();
911 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912}
913
Steve Anton8af21862017-12-15 11:20:13 -0800914void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800915 // Destroy video channels first since they may have a pointer to a voice
916 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100917 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800918 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800919 DestroyTransceiverChannel(transceiver);
920 }
921 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100922 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800923 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800924 DestroyTransceiverChannel(transceiver);
925 }
926 }
927 DestroyDataChannel();
928}
929
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000931 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700932 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100933 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100934 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100935 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700936
937 RTCError config_error = ValidateConfiguration(configuration);
938 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100939 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700940 return false;
941 }
942
Benjamin Wrightcab58882018-05-02 15:12:47 -0700943 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100944 RTC_LOG(LS_ERROR)
945 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100946 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800947 return false;
948 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200949
Benjamin Wrightcab58882018-05-02 15:12:47 -0700950 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800951 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100952 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100953 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800954 return false;
955 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700956
Benjamin Wrightcab58882018-05-02 15:12:47 -0700957 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700958 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700959 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700960 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800961
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200962 cricket::ServerAddresses stun_servers;
963 std::vector<cricket::RelayServerConfig> turn_servers;
964
965 RTCErrorType parse_error =
966 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
967 if (parse_error != RTCErrorType::NONE) {
968 return false;
969 }
970
deadbeef91dd5672016-05-18 16:55:30 -0700971 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700972 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100973 const auto pa_result =
974 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200975 RTC_FROM_HERE,
976 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100977 stun_servers, turn_servers, configuration));
978
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200979 // If initialization was successful, note if STUN or TURN servers
980 // were supplied.
981 if (!stun_servers.empty()) {
982 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
983 }
984 if (!turn_servers.empty()) {
985 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
986 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700988 // Send information about IPv4/IPv6 status.
989 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100990 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700991 address_family = kPeerConnection_IPv6;
992 } else {
993 address_family = kPeerConnection_IPv4;
994 }
995 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
996 kPeerConnectionAddressFamilyCounter_Max);
997
Zhi Huange830e682018-03-30 10:48:35 -0700998 const PeerConnectionFactoryInterface::Options& options = factory_->options();
999
Steve Anton75737c02017-11-06 10:37:17 -08001000 // RFC 3264: The numeric value of the session id and version in the
1001 // o line MUST be representable with a "64 bit signed integer".
1002 // Due to this constraint session id |session_id_| is max limited to
1003 // LLONG_MAX.
1004 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001005 JsepTransportController::Config config;
1006 config.redetermine_role_on_ice_restart =
1007 configuration.redetermine_role_on_ice_restart;
1008 config.ssl_max_version = factory_->options().ssl_max_version;
1009 config.disable_encryption = options.disable_encryption;
1010 config.bundle_policy = configuration.bundle_policy;
1011 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001012 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1013 // stub.
1014 config.crypto_options = configuration.crypto_options.has_value()
1015 ? *configuration.crypto_options
1016 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001017 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001018 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001019#if defined(ENABLE_EXTERNAL_AUTH)
1020 config.enable_external_auth = true;
1021#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001022 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001023
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001024 if (configuration.use_media_transport ||
1025 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001026 if (!factory_->media_transport_factory()) {
1027 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001028 << "PeerConnecton is initialized with use_media_transport = true or "
1029 << "use_media_transport_for_data_channels = true "
1030 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001031 return false;
1032 }
1033
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001034 if (configuration.use_media_transport ||
1035 configuration.use_media_transport_for_data_channels) {
1036 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1037 // RTP media transport is introduced. But until then, we require SDES to
1038 // be enabled.
1039 if (configuration.enable_dtls_srtp.has_value() &&
1040 configuration.enable_dtls_srtp.value()) {
1041 RTC_LOG(LS_WARNING)
1042 << "When media transport is used, SDES must be enabled. Set "
1043 "configuration.enable_dtls_srtp to false. use_media_transport="
1044 << configuration.use_media_transport
1045 << ", use_media_transport_for_data_channels="
1046 << configuration.use_media_transport_for_data_channels;
1047 return false;
1048 }
1049 }
1050
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001051 config.use_media_transport_for_media = configuration.use_media_transport;
1052 config.use_media_transport_for_data_channels =
1053 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001054 config.media_transport_factory = factory_->media_transport_factory();
1055 }
1056
Zhi Huange830e682018-03-30 10:48:35 -07001057 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001058 signaling_thread(), network_thread(), port_allocator_.get(),
1059 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001060 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001061 this, &PeerConnection::OnTransportControllerConnectionState);
1062 transport_controller_->SignalStandardizedIceConnectionState.connect(
1063 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001064 transport_controller_->SignalConnectionState.connect(
1065 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001066 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001067 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001068 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001069 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001070 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001071 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1072 transport_controller_->SignalDtlsHandshakeError.connect(
1073 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1074
1075 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001076
deadbeefab9b2d12015-10-14 11:33:11 -07001077 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001078 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001079
Steve Antonba818672017-11-06 10:21:57 -08001080 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001081 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001082
Steve Anton75737c02017-11-06 10:37:17 -08001083 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1084 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1085 if (!configuration.certificates.empty()) {
1086 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1087 // just picking the first one. The decision should be made based on the DTLS
1088 // handshake. The DTLS negotiations need to know about all certificates.
1089 certificate = configuration.certificates[0];
1090 }
1091
Steve Antond25da372017-11-06 14:50:29 -08001092 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001093
1094 if (options.disable_encryption) {
1095 dtls_enabled_ = false;
1096 } else {
1097 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001098 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001099 // |configuration| can override the default |dtls_enabled_| value.
1100 if (configuration.enable_dtls_srtp) {
1101 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1102 }
1103 }
1104
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001105 if (configuration.use_media_transport_for_data_channels) {
1106 if (configuration.enable_rtp_data_channel) {
1107 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1108 "use_media_transport_for_data_channels are "
1109 "incompatible and cannot both be set to true";
1110 return false;
1111 }
1112 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1113 } else if (configuration.enable_rtp_data_channel) {
1114 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1115 // set. It takes precendence over the disable_sctp_data_channels
1116 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001117 data_channel_type_ = cricket::DCT_RTP;
1118 } else {
1119 // DTLS has to be enabled to use SCTP.
1120 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1121 data_channel_type_ = cricket::DCT_SCTP;
1122 }
1123 }
1124
1125 video_options_.screencast_min_bitrate_kbps =
1126 configuration.screencast_min_bitrate;
1127 audio_options_.combined_audio_video_bwe =
1128 configuration.combined_audio_video_bwe;
1129
1130 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001131 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001132
1133 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001134 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001135
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001136 audio_options_.audio_jitter_buffer_min_delay_ms =
1137 configuration.audio_jitter_buffer_min_delay_ms;
1138
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001139 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1140 configuration.audio_jitter_buffer_enable_rtx_handling;
1141
Steve Anton75737c02017-11-06 10:37:17 -08001142 // Whether the certificate generator/certificate is null or not determines
1143 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1144 // the right instructions by clearing the variables if needed.
1145 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001146 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001147 certificate = nullptr;
1148 } else if (certificate) {
1149 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001150 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001151 }
1152
1153 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1154 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001155 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001156 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1157 this, &PeerConnection::OnCertificateReady);
1158
1159 if (options.disable_encryption) {
1160 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1161 }
1162
1163 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001164 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001165 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166
Steve Anton4171afb2017-11-20 10:20:22 -08001167 // Add default audio/video transceivers for Plan B SDP.
1168 if (!IsUnifiedPlan()) {
1169 transceivers_.push_back(
1170 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1171 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1172 transceivers_.push_back(
1173 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1174 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1175 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001176 int delay_ms =
1177 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001178 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1179 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001180
1181 if (dependencies.video_bitrate_allocator_factory) {
1182 video_bitrate_allocator_factory_ =
1183 std::move(dependencies.video_bitrate_allocator_factory);
1184 } else {
1185 video_bitrate_allocator_factory_ =
1186 CreateBuiltinVideoBitrateAllocatorFactory();
1187 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 return true;
1189}
1190
Steve Anton038834f2017-07-14 15:59:59 -07001191RTCError PeerConnection::ValidateConfiguration(
1192 const RTCConfiguration& config) const {
1193 if (config.ice_regather_interval_range &&
1194 config.continual_gathering_policy == GATHER_ONCE) {
1195 return RTCError(RTCErrorType::INVALID_PARAMETER,
1196 "ice_regather_interval_range specified but continual "
1197 "gathering policy is GATHER_ONCE");
1198 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001199 auto result =
1200 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1201 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001202}
1203
Yves Gerey665174f2018-06-19 15:03:05 +02001204rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001205 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001206 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1207 "Plan SdpSemantics. Please use GetSenders "
1208 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001209 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001210}
1211
Yves Gerey665174f2018-06-19 15:03:05 +02001212rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001213 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001214 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1215 "Plan SdpSemantics. Please use GetReceivers "
1216 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001217 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218}
1219
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001220bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001221 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001222 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1223 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001224 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 if (IsClosed()) {
1226 return false;
1227 }
deadbeefab9b2d12015-10-14 11:33:11 -07001228 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229 return false;
1230 }
deadbeefab9b2d12015-10-14 11:33:11 -07001231
1232 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001233 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1234 observer->SignalAudioTrackAdded.connect(this,
1235 &PeerConnection::OnAudioTrackAdded);
1236 observer->SignalAudioTrackRemoved.connect(
1237 this, &PeerConnection::OnAudioTrackRemoved);
1238 observer->SignalVideoTrackAdded.connect(this,
1239 &PeerConnection::OnVideoTrackAdded);
1240 observer->SignalVideoTrackRemoved.connect(
1241 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001242 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001243
deadbeefab9b2d12015-10-14 11:33:11 -07001244 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001245 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001246 }
1247 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001248 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001249 }
1250
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001251 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001252 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 return true;
1254}
1255
1256void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001257 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001258 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1259 "Plan SdpSemantics. Please use RemoveTrack "
1260 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001261 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001262 if (!IsClosed()) {
1263 for (const auto& track : local_stream->GetAudioTracks()) {
1264 RemoveAudioTrack(track.get(), local_stream);
1265 }
1266 for (const auto& track : local_stream->GetVideoTracks()) {
1267 RemoveVideoTrack(track.get(), local_stream);
1268 }
deadbeefab9b2d12015-10-14 11:33:11 -07001269 }
deadbeefab9b2d12015-10-14 11:33:11 -07001270 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001271 stream_observers_.erase(
1272 std::remove_if(
1273 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001274 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001275 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001276 }),
1277 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001278
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 if (IsClosed()) {
1280 return;
1281 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001282 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283}
1284
Steve Anton2d6c76a2018-01-05 17:10:52 -08001285RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001286 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001287 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001288 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001289 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001290 if (!track) {
1291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1292 }
1293 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1294 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1296 "Track has invalid kind: " + track->kind());
1297 }
Steve Antonf9381f02017-12-14 10:23:57 -08001298 if (IsClosed()) {
1299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1300 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001301 }
Steve Anton4171afb2017-11-20 10:20:22 -08001302 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001303 LOG_AND_RETURN_ERROR(
1304 RTCErrorType::INVALID_PARAMETER,
1305 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001306 }
Steve Antonf9381f02017-12-14 10:23:57 -08001307 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001308 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1309 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001310 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001311 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001312 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 }
1314 return sender_or_error;
1315}
deadbeefe1f9d832016-01-14 15:35:42 -08001316
Steve Antonf9381f02017-12-14 10:23:57 -08001317RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1318PeerConnection::AddTrackPlanB(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001320 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001321 if (stream_ids.size() > 1u) {
1322 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1323 "AddTrack with more than one stream is not "
1324 "supported with Plan B semantics.");
1325 }
1326 std::vector<std::string> adjusted_stream_ids = stream_ids;
1327 if (adjusted_stream_ids.empty()) {
1328 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1329 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001330 cricket::MediaType media_type =
1331 (track->kind() == MediaStreamTrackInterface::kAudioKind
1332 ? cricket::MEDIA_TYPE_AUDIO
1333 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001334 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001335 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001336 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001337 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001338 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001339 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001340 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001341 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001342 if (sender_info) {
1343 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001344 }
Steve Antonf9381f02017-12-14 10:23:57 -08001345 } else {
1346 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001347 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001348 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001349 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001350 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001351 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 if (sender_info) {
1353 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
deadbeefe1f9d832016-01-14 15:35:42 -08001355 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001356 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001357}
deadbeefe1f9d832016-01-14 15:35:42 -08001358
Steve Antonf9381f02017-12-14 10:23:57 -08001359RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1360PeerConnection::AddTrackUnifiedPlan(
1361 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001362 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001363 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1364 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001365 RTC_LOG(LS_INFO) << "Reusing an existing "
1366 << cricket::MediaTypeToString(transceiver->media_type())
1367 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001368 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001369 transceiver->internal()->set_direction(
1370 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001371 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001372 transceiver->internal()->set_direction(
1373 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001374 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001375 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001376 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001377 } else {
1378 cricket::MediaType media_type =
1379 (track->kind() == MediaStreamTrackInterface::kAudioKind
1380 ? cricket::MEDIA_TYPE_AUDIO
1381 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001382 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1383 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001384 std::string sender_id = track->id();
1385 // Avoid creating a sender with an existing ID by generating a random ID.
1386 // This can happen if this is the second time AddTrack has created a sender
1387 // for this track.
1388 if (FindSenderById(sender_id)) {
1389 sender_id = rtc::CreateRandomUuid();
1390 }
Florent Castelli892acf02018-10-01 22:47:20 +02001391 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001392 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1393 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001394 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001395 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001396 }
Steve Antonf9381f02017-12-14 10:23:57 -08001397 return transceiver->sender();
1398}
1399
1400rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1401PeerConnection::FindFirstTransceiverForAddedTrack(
1402 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1403 RTC_DCHECK(track);
1404 for (auto transceiver : transceivers_) {
1405 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001406 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001407 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001408 !transceiver->internal()->has_ever_been_used_to_send() &&
1409 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001410 return transceiver;
1411 }
1412 }
1413 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001414}
1415
1416bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1417 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001418 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001419}
1420
Steve Anton24db5732018-07-23 10:27:33 -07001421RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001422 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001423 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001424 if (!sender) {
1425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1426 }
deadbeefe1f9d832016-01-14 15:35:42 -08001427 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1429 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001430 }
Steve Antonf9381f02017-12-14 10:23:57 -08001431 if (IsUnifiedPlan()) {
1432 auto transceiver = FindTransceiverBySender(sender);
1433 if (!transceiver || !sender->track()) {
1434 return RTCError::OK();
1435 }
1436 sender->SetTrack(nullptr);
1437 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001438 transceiver->internal()->set_direction(
1439 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001440 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001441 transceiver->internal()->set_direction(
1442 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001443 }
Steve Anton4171afb2017-11-20 10:20:22 -08001444 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001445 bool removed;
1446 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1447 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1448 } else {
1449 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1450 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1451 }
1452 if (!removed) {
1453 LOG_AND_RETURN_ERROR(
1454 RTCErrorType::INVALID_PARAMETER,
1455 "Couldn't find sender " + sender->id() + " to remove.");
1456 }
Steve Anton4171afb2017-11-20 10:20:22 -08001457 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001458 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001459 return RTCError::OK();
1460}
1461
1462rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1463PeerConnection::FindTransceiverBySender(
1464 rtc::scoped_refptr<RtpSenderInterface> sender) {
1465 for (auto transceiver : transceivers_) {
1466 if (transceiver->sender() == sender) {
1467 return transceiver;
1468 }
1469 }
1470 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001471}
1472
Steve Anton9158ef62017-11-27 13:01:52 -08001473RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1474PeerConnection::AddTransceiver(
1475 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1476 return AddTransceiver(track, RtpTransceiverInit());
1477}
1478
1479RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1480PeerConnection::AddTransceiver(
1481 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1482 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001483 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001484 RTC_CHECK(IsUnifiedPlan())
1485 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001486 if (!track) {
1487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1488 }
1489 cricket::MediaType media_type;
1490 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1491 media_type = cricket::MEDIA_TYPE_AUDIO;
1492 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1493 media_type = cricket::MEDIA_TYPE_VIDEO;
1494 } else {
1495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1496 "Track kind is not audio or video");
1497 }
1498 return AddTransceiver(media_type, track, init);
1499}
1500
1501RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1502PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1503 return AddTransceiver(media_type, RtpTransceiverInit());
1504}
1505
1506RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1507PeerConnection::AddTransceiver(cricket::MediaType media_type,
1508 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001509 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001510 RTC_CHECK(IsUnifiedPlan())
1511 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001512 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1513 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1514 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1515 "media type is not audio or video");
1516 }
1517 return AddTransceiver(media_type, nullptr, init);
1518}
1519
1520RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1521PeerConnection::AddTransceiver(
1522 cricket::MediaType media_type,
1523 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001524 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001525 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001526 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1527 media_type == cricket::MEDIA_TYPE_VIDEO));
1528 if (track) {
1529 RTC_DCHECK_EQ(media_type,
1530 (track->kind() == MediaStreamTrackInterface::kAudioKind
1531 ? cricket::MEDIA_TYPE_AUDIO
1532 : cricket::MEDIA_TYPE_VIDEO));
1533 }
1534
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001535 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1536 init.send_encodings.size(), 0, 7, 8);
1537
Amit Hilbuchaa584152019-02-06 17:09:52 -08001538 size_t num_rids = absl::c_count_if(init.send_encodings,
1539 [](const RtpEncodingParameters& encoding) {
1540 return !encoding.rid.empty();
1541 });
1542 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001543 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001544 RTCErrorType::INVALID_PARAMETER,
1545 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001546 }
1547
Amit Hilbuchf4770402019-04-08 14:11:57 -07001548 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1549 [](const RtpEncodingParameters& encoding) {
1550 return !IsLegalRsidName(encoding.rid);
1551 })) {
1552 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1553 "Invalid RID value provided.");
1554 }
1555
Amit Hilbuchaa584152019-02-06 17:09:52 -08001556 if (absl::c_any_of(init.send_encodings,
1557 [](const RtpEncodingParameters& encoding) {
1558 return encoding.ssrc.has_value();
1559 })) {
1560 LOG_AND_RETURN_ERROR(
1561 RTCErrorType::UNSUPPORTED_PARAMETER,
1562 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001563 }
1564
1565 RtpParameters parameters;
1566 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001567
1568 // Encodings are dropped from the tail if too many are provided.
1569 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1570 parameters.encodings.erase(
1571 parameters.encodings.begin() + kMaxSimulcastStreams,
1572 parameters.encodings.end());
1573 }
1574
1575 // Single RID should be removed.
1576 if (parameters.encodings.size() == 1 &&
1577 !parameters.encodings[0].rid.empty()) {
1578 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1579 parameters.encodings[0].rid.clear();
1580 }
1581
1582 // If RIDs were not provided, they are generated for simulcast scenario.
1583 if (parameters.encodings.size() > 1 && num_rids == 0) {
1584 rtc::UniqueStringGenerator rid_generator;
1585 for (RtpEncodingParameters& encoding : parameters.encodings) {
1586 encoding.rid = rid_generator();
1587 }
1588 }
1589
Florent Castelli892acf02018-10-01 22:47:20 +02001590 if (UnimplementedRtpParameterHasValue(parameters)) {
1591 LOG_AND_RETURN_ERROR(
1592 RTCErrorType::UNSUPPORTED_PARAMETER,
1593 "Attempted to set an unimplemented parameter of RtpParameters.");
1594 }
Steve Anton9158ef62017-11-27 13:01:52 -08001595
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001596 auto result = cricket::CheckRtpParametersValues(parameters);
1597 if (!result.ok()) {
1598 LOG_AND_RETURN_ERROR(result.type(), result.message());
1599 }
1600
Steve Anton3d954a62018-04-02 11:27:23 -07001601 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1602 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001603 // Set the sender ID equal to the track ID if the track is specified unless
1604 // that sender ID is already in use.
1605 std::string sender_id =
1606 (track && !FindSenderById(track->id()) ? track->id()
1607 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001608 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001609 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001610 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1611 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1612 transceiver->internal()->set_direction(init.direction);
1613
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001614 if (update_negotiation_needed) {
1615 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001616 }
Steve Antonf9381f02017-12-14 10:23:57 -08001617
1618 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1619}
1620
Steve Anton02ee47c2018-01-10 16:26:06 -08001621rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1622PeerConnection::CreateSender(
1623 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001624 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001625 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001626 const std::vector<std::string>& stream_ids,
1627 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001628 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001629 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001630 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1631 RTC_DCHECK(!track ||
1632 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1633 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1634 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001635 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001636 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001637 } else {
1638 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1639 RTC_DCHECK(!track ||
1640 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1641 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001642 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001643 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001644 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001645 bool set_track_succeeded = sender->SetTrack(track);
1646 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001647 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001648 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001649 return sender;
1650}
1651
1652rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1653PeerConnection::CreateReceiver(cricket::MediaType media_type,
1654 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001655 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1656 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001657 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001658 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001659 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1660 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001661 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001662 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001663 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001664 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001665 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1666 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001667 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001668 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001669 return receiver;
1670}
1671
1672rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1673PeerConnection::CreateAndAddTransceiver(
1674 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1675 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1676 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001677 // Ensure that the new sender does not have an ID that is already in use by
1678 // another sender.
1679 // Allow receiver IDs to conflict since those come from remote SDP (which
1680 // could be invalid, but should not cause a crash).
1681 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001682 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001683 signaling_thread(),
1684 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001685 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001686 transceiver->internal()->SignalNegotiationNeeded.connect(
1687 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001688 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001689}
1690
Steve Anton52d86772018-02-20 15:48:12 -08001691void PeerConnection::OnNegotiationNeeded() {
1692 RTC_DCHECK_RUN_ON(signaling_thread());
1693 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001694 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001695}
1696
deadbeeffac06552015-11-25 11:26:01 -08001697rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001698 const std::string& kind,
1699 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001700 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001701 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1702 "Plan SdpSemantics. Please use AddTransceiver "
1703 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001704 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001705 if (IsClosed()) {
1706 return nullptr;
1707 }
Steve Anton4171afb2017-11-20 10:20:22 -08001708
Seth Hampson5b4f0752018-04-02 16:31:36 -07001709 // Internally we need to have one stream with Plan B semantics, so we
1710 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001711 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001712 if (stream_id.empty()) {
1713 stream_ids.push_back(rtc::CreateRandomUuid());
1714 RTC_LOG(LS_INFO)
1715 << "No stream_id specified for sender. Generated stream ID: "
1716 << stream_ids[0];
1717 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001718 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001719 }
1720
Steve Anton4171afb2017-11-20 10:20:22 -08001721 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001722 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001723 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001724 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001725 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001726 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001727 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001728 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001729 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001730 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001731 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001732 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001733 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001734 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001735 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001736 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001737 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001739 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001740 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001741 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001742
deadbeefe1f9d832016-01-14 15:35:42 -08001743 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001744}
1745
deadbeef70ab1a12015-09-28 16:53:55 -07001746std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1747 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001748 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001749 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001750 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001751 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001752 }
1753 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001754}
1755
Steve Anton4171afb2017-11-20 10:20:22 -08001756std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1757PeerConnection::GetSendersInternal() const {
1758 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1759 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001760 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001761 auto senders = transceiver->internal()->senders();
1762 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1763 }
1764 return all_senders;
1765}
1766
deadbeef70ab1a12015-09-28 16:53:55 -07001767std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1768PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001769 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001770 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001771 for (const auto& receiver : GetReceiversInternal()) {
1772 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001773 }
1774 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001775}
1776
Steve Anton4171afb2017-11-20 10:20:22 -08001777std::vector<
1778 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1779PeerConnection::GetReceiversInternal() const {
1780 std::vector<
1781 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1782 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001783 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001784 auto receivers = transceiver->internal()->receivers();
1785 all_receivers.insert(all_receivers.end(), receivers.begin(),
1786 receivers.end());
1787 }
1788 return all_receivers;
1789}
1790
Steve Anton9158ef62017-11-27 13:01:52 -08001791std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1792PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001793 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001794 RTC_CHECK(IsUnifiedPlan())
1795 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001796 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001797 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001798 all_transceivers.push_back(transceiver);
1799 }
1800 return all_transceivers;
1801}
1802
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001804 MediaStreamTrackInterface* track,
1805 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001806 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001807 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001808 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001809 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810 return false;
1811 }
1812
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001813 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001814 // The StatsCollector is used to tell if a track is valid because it may
1815 // remember tracks that the PeerConnection previously removed.
1816 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1818 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001819 return false;
1820 }
Steve Antonad182762018-09-05 20:22:40 +00001821 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1822 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 return true;
1824}
1825
hbos74e1a4f2016-09-15 23:33:01 -07001826void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001827 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001828 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001829 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001830 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001831 stats_collector_->GetStatsReport(callback);
1832}
1833
Henrik Boström1df1bf82018-03-20 13:24:20 +01001834void PeerConnection::GetStats(
1835 rtc::scoped_refptr<RtpSenderInterface> selector,
1836 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1837 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001838 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001839 RTC_DCHECK(callback);
1840 RTC_DCHECK(stats_collector_);
1841 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1842 if (selector) {
1843 for (const auto& proxy_transceiver : transceivers_) {
1844 for (const auto& proxy_sender :
1845 proxy_transceiver->internal()->senders()) {
1846 if (proxy_sender == selector) {
1847 internal_sender = proxy_sender->internal();
1848 break;
1849 }
1850 }
1851 if (internal_sender)
1852 break;
1853 }
1854 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001855 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001856 // belong to the PeerConnection (in Plan B, senders can be removed from the
1857 // PeerConnection). This means that "all the stats objects representing the
1858 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1859 // produces an empty stats report.
1860 stats_collector_->GetStatsReport(internal_sender, callback);
1861}
1862
1863void PeerConnection::GetStats(
1864 rtc::scoped_refptr<RtpReceiverInterface> selector,
1865 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1866 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001867 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001868 RTC_DCHECK(callback);
1869 RTC_DCHECK(stats_collector_);
1870 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1871 if (selector) {
1872 for (const auto& proxy_transceiver : transceivers_) {
1873 for (const auto& proxy_receiver :
1874 proxy_transceiver->internal()->receivers()) {
1875 if (proxy_receiver == selector) {
1876 internal_receiver = proxy_receiver->internal();
1877 break;
1878 }
1879 }
1880 if (internal_receiver)
1881 break;
1882 }
1883 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001884 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001885 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1886 // the PeerConnection). This means that "all the stats objects representing
1887 // the selector" is an empty set. Invoking GetStatsReport() with a null
1888 // selector produces an empty stats report.
1889 stats_collector_->GetStatsReport(internal_receiver, callback);
1890}
1891
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001893 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 return signaling_state_;
1895}
1896
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897PeerConnectionInterface::IceConnectionState
1898PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001899 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900 return ice_connection_state_;
1901}
1902
Alex Loiko9289eda2018-11-23 16:18:59 +00001903PeerConnectionInterface::IceConnectionState
1904PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001905 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001906 return standardized_ice_connection_state_;
1907}
1908
Jonas Olsson635474e2018-10-18 15:58:17 +02001909PeerConnectionInterface::PeerConnectionState
1910PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001912 return connection_state_;
1913}
1914
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915PeerConnectionInterface::IceGatheringState
1916PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return ice_gathering_state_;
1919}
1920
Yves Gerey665174f2018-06-19 15:03:05 +02001921rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 const std::string& label,
1923 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001924 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001925 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001926
deadbeefab9b2d12015-10-14 11:33:11 -07001927 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001928
kwibergd1fe2812016-04-27 06:47:29 -07001929 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001930 if (config) {
1931 internal_config.reset(new InternalDataChannelInit(*config));
1932 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001933 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001934 InternalCreateDataChannel(label, internal_config.get()));
1935 if (!channel.get()) {
1936 return nullptr;
1937 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001939 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1940 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001941 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001942 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001943 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001944 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 return DataChannelProxy::Create(signaling_thread(), channel.get());
1946}
1947
1948void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001949 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001950 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001951 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001952
nisse7ce109a2017-01-31 00:57:56 -08001953 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001954 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001955 return;
1956 }
deadbeefab9b2d12015-10-14 11:33:11 -07001957
Steve Anton8d3444d2017-10-20 15:30:51 -07001958 if (IsClosed()) {
1959 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001960 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001961 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001962 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001963 return;
1964 }
1965
zhihuang1c378ed2017-08-17 14:10:50 -07001966 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001967 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001968 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001969 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001970 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001971 return;
1972 }
1973
Steve Anton22da89f2018-01-25 13:58:07 -08001974 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1975 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1976 if (IsUnifiedPlan()) {
1977 RTCError error = HandleLegacyOfferOptions(options);
1978 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001979 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001980 return;
1981 }
1982 }
1983
zhihuang1c378ed2017-08-17 14:10:50 -07001984 cricket::MediaSessionOptions session_options;
1985 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001986 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987}
1988
Steve Anton22da89f2018-01-25 13:58:07 -08001989RTCError PeerConnection::HandleLegacyOfferOptions(
1990 const RTCOfferAnswerOptions& options) {
1991 RTC_DCHECK(IsUnifiedPlan());
1992
1993 if (options.offer_to_receive_audio == 0) {
1994 RemoveRecvDirectionFromReceivingTransceiversOfType(
1995 cricket::MEDIA_TYPE_AUDIO);
1996 } else if (options.offer_to_receive_audio == 1) {
1997 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1998 } else if (options.offer_to_receive_audio > 1) {
1999 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2000 "offer_to_receive_audio > 1 is not supported.");
2001 }
2002
2003 if (options.offer_to_receive_video == 0) {
2004 RemoveRecvDirectionFromReceivingTransceiversOfType(
2005 cricket::MEDIA_TYPE_VIDEO);
2006 } else if (options.offer_to_receive_video == 1) {
2007 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2008 } else if (options.offer_to_receive_video > 1) {
2009 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2010 "offer_to_receive_video > 1 is not supported.");
2011 }
2012
2013 return RTCError::OK();
2014}
2015
2016void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2017 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002018 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002019 RtpTransceiverDirection new_direction =
2020 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2021 if (new_direction != transceiver->direction()) {
2022 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2023 << " transceiver (MID="
2024 << transceiver->mid().value_or("<not set>") << ") from "
2025 << RtpTransceiverDirectionToString(
2026 transceiver->direction())
2027 << " to "
2028 << RtpTransceiverDirectionToString(new_direction)
2029 << " since CreateOffer specified offer_to_receive=0";
2030 transceiver->internal()->set_direction(new_direction);
2031 }
Steve Anton22da89f2018-01-25 13:58:07 -08002032 }
2033}
2034
2035void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2036 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002037 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002038 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002039 RTC_LOG(LS_INFO)
2040 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2041 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002042 RtpTransceiverInit init;
2043 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002044 AddTransceiver(media_type, nullptr, init,
2045 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002046 }
2047}
2048
2049std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2050PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2051 std::vector<
2052 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2053 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002054 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002055 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002056 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2057 receiving_transceivers.push_back(transceiver);
2058 }
2059 }
2060 return receiving_transceivers;
2061}
2062
htaa2a49d92016-03-04 02:51:39 -08002063void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2064 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002065 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002066 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002067 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002068 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002069 return;
2070 }
2071
Steve Antondffead82018-02-06 10:31:29 -08002072 if (!(signaling_state_ == kHaveRemoteOffer ||
2073 signaling_state_ == kHaveLocalPrAnswer)) {
2074 std::string error =
2075 "PeerConnection cannot create an answer in a state other than "
2076 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002077 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002078 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002079 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002080 return;
2081 }
2082
Steve Antondffead82018-02-06 10:31:29 -08002083 // The remote description should be set if we're in the right state.
2084 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002085
Steve Anton22da89f2018-01-25 13:58:07 -08002086 if (IsUnifiedPlan()) {
2087 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2088 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2089 "supported with Unified Plan semantics. Use the "
2090 "RtpTransceiver API instead.";
2091 }
2092 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2093 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2094 "supported with Unified Plan semantics. Use the "
2095 "RtpTransceiver API instead.";
2096 }
2097 }
2098
htaa2a49d92016-03-04 02:51:39 -08002099 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002100 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002101
Steve Antond25da372017-11-06 14:50:29 -08002102 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103}
2104
2105void PeerConnection::SetLocalDescription(
2106 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002107 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002108 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002109 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002110
Steve Anton80dd7b52018-02-16 17:08:42 -08002111 // The SetLocalDescription contract is that we take ownership of the session
2112 // description regardless of the outcome, so wrap it in a unique_ptr right
2113 // away. Ideally, SetLocalDescription's signature will be changed to take the
2114 // description as a unique_ptr argument to formalize this agreement.
2115 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2116
nisse7ce109a2017-01-31 00:57:56 -08002117 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002118 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119 return;
2120 }
Steve Anton8a006912017-12-04 15:25:56 -08002121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002123 PostSetSessionDescriptionFailure(
2124 observer,
2125 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 return;
2127 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002128
Steve Anton80dd7b52018-02-16 17:08:42 -08002129 // If a session error has occurred the PeerConnection is in a possibly
2130 // inconsistent state so fail right away.
2131 if (session_error() != SessionError::kNone) {
2132 std::string error_message = GetSessionErrorMsg();
2133 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002134 PostSetSessionDescriptionFailure(
2135 observer,
2136 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002137 return;
2138 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002139
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2141 if (!error.ok()) {
2142 std::string error_message = GetSetDescriptionErrorMessage(
2143 cricket::CS_LOCAL, desc->GetType(), error);
2144 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002145 PostSetSessionDescriptionFailure(
2146 observer,
2147 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002148 return;
2149 }
2150
2151 // Grab the description type before moving ownership to ApplyLocalDescription,
2152 // which may destroy it before returning.
2153 const SdpType type = desc->GetType();
2154
2155 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002156 // |desc| may be destroyed at this point.
2157
2158 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002159 // If ApplyLocalDescription fails, the PeerConnection could be in an
2160 // inconsistent state, so act conservatively here and set the session error
2161 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2162 SetSessionError(SessionError::kContent, error.message());
2163 std::string error_message =
2164 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2165 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002166 PostSetSessionDescriptionFailure(
2167 observer,
2168 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002169 return;
2170 }
Steve Anton8a006912017-12-04 15:25:56 -08002171 RTC_DCHECK(local_description());
2172
2173 PostSetSessionDescriptionSuccess(observer);
2174
Steve Antonad182762018-09-05 20:22:40 +00002175 // MaybeStartGathering needs to be called after posting
2176 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2177 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002178 transport_controller_->MaybeStartGathering();
2179
Steve Antona3a92c22017-12-07 10:27:41 -08002180 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002181 // TODO(deadbeef): We already had to hop to the network thread for
2182 // MaybeStartGathering...
2183 network_thread()->Invoke<void>(
2184 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2185 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002186 // Make UMA notes about what was agreed to.
2187 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002188 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002189
2190 if (IsUnifiedPlan()) {
2191 bool was_negotiation_needed = is_negotiation_needed_;
2192 UpdateNegotiationNeeded();
2193 if (signaling_state() == kStable && was_negotiation_needed &&
2194 is_negotiation_needed_) {
2195 Observer()->OnRenegotiationNeeded();
2196 }
2197 }
2198
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002199 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002200}
2201
2202RTCError PeerConnection::ApplyLocalDescription(
2203 std::unique_ptr<SessionDescriptionInterface> desc) {
2204 RTC_DCHECK_RUN_ON(signaling_thread());
2205 RTC_DCHECK(desc);
2206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 // Update stats here so that we have the most recent stats for tracks and
2208 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002209 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002210
Steve Antondcc3c022017-12-22 16:02:54 -08002211 // Take a reference to the old local description since it's used below to
2212 // compare against the new local description. When setting the new local
2213 // description, grab ownership of the replaced session description in case it
2214 // is the same as |old_local_description|, to keep it alive for the duration
2215 // of the method.
2216 const SessionDescriptionInterface* old_local_description =
2217 local_description();
2218 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002219 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002220 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002221 replaced_local_description = pending_local_description_
2222 ? std::move(pending_local_description_)
2223 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002224 current_local_description_ = std::move(desc);
2225 pending_local_description_ = nullptr;
2226 current_remote_description_ = std::move(pending_remote_description_);
2227 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002228 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002229 pending_local_description_ = std::move(desc);
2230 }
2231 // The session description to apply now must be accessed by
2232 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002233 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002234
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002235 // Report statistics about any use of simulcast.
2236 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2237 *local_description()->description());
2238
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002239 if (!is_caller_) {
2240 if (remote_description()) {
2241 // Remote description was applied first, so this PC is the callee.
2242 is_caller_ = false;
2243 } else {
2244 // Local description is applied first, so this PC is the caller.
2245 is_caller_ = true;
2246 }
2247 }
2248
Zhi Huange830e682018-03-30 10:48:35 -07002249 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2250 if (!error.ok()) {
2251 return error;
2252 }
2253
Steve Antondcc3c022017-12-22 16:02:54 -08002254 if (IsUnifiedPlan()) {
2255 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002256 cricket::CS_LOCAL, *local_description(), old_local_description,
2257 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002258 if (!error.ok()) {
2259 return error;
2260 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002261 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2262 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002263 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002264 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2265 // Note that code paths that don't set MID won't be able to use
2266 // information about DTLS transports.
2267 if (transceiver->mid()) {
2268 auto dtls_transport =
2269 LookupDtlsTransportByMidInternal(*transceiver->mid());
2270 transceiver->internal()->sender_internal()->set_transport(
2271 dtls_transport);
2272 transceiver->internal()->receiver_internal()->set_transport(
2273 dtls_transport);
2274 }
2275
Steve Antondcc3c022017-12-22 16:02:54 -08002276 const ContentInfo* content =
2277 FindMediaSectionForTransceiver(transceiver, local_description());
2278 if (!content) {
2279 continue;
2280 }
2281 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002282 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2283 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002284 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002285 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2286 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2287 // "recvonly", process the removal of a remote track for the media
2288 // description, given transceiver, removeList, and muteTracks.
2289 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2290 (transceiver->internal()->fired_direction() &&
2291 RtpTransceiverDirectionHasRecv(
2292 *transceiver->internal()->fired_direction()))) {
2293 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2294 &removed_streams);
2295 }
2296 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2297 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002298 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002299 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002300 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002301 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002302 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002303 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002304 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002305 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002306 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002307 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002308 }
2309 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002310 // Media channels will be created only when offer is set. These may use new
2311 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002312 if (type == SdpType::kOffer) {
2313 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2314 // description is applied. Restore back to old description.
2315 RTCError error = CreateChannels(*local_description()->description());
2316 if (!error.ok()) {
2317 return error;
2318 }
2319 }
Steve Antondcc3c022017-12-22 16:02:54 -08002320 // Remove unused channels if MediaContentDescription is rejected.
2321 RemoveUnusedChannels(local_description()->description());
2322 }
Steve Anton8a006912017-12-04 15:25:56 -08002323
Zhi Huange830e682018-03-30 10:48:35 -07002324 error = UpdateSessionState(type, cricket::CS_LOCAL,
2325 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002326 if (!error.ok()) {
2327 return error;
2328 }
Steve Antondcc3c022017-12-22 16:02:54 -08002329
Steve Anton8a006912017-12-04 15:25:56 -08002330 if (remote_description()) {
2331 // Now that we have a local description, we can push down remote candidates.
2332 UseCandidatesInSessionDescription(remote_description());
2333 }
2334
2335 pending_ice_restarts_.clear();
2336 if (session_error() != SessionError::kNone) {
2337 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2338 }
2339
deadbeefab9b2d12015-10-14 11:33:11 -07002340 // If setting the description decided our SSL role, allocate any necessary
2341 // SCTP sids.
2342 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002343 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002344 AllocateSctpSids(role);
2345 }
2346
Steve Antond3679212018-01-17 17:41:02 -08002347 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002348 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002349 const ContentInfo* content =
2350 FindMediaSectionForTransceiver(transceiver, local_description());
2351 if (!content) {
2352 continue;
2353 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002354 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2355 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002356 // 0 is a special value meaning "this sender has no associated send
2357 // stream". Need to call this so the sender won't attempt to configure
2358 // a no longer existing stream and run into DCHECKs in the lower
2359 // layers.
2360 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002361 } else {
2362 // Get the StreamParams from the channel which could generate SSRCs.
2363 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002364 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002365 streams[0].stream_ids());
2366 transceiver->internal()->sender_internal()->SetSsrc(
2367 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002368 }
2369 }
2370 } else {
2371 // Plan B semantics.
2372
Steve Antondcc3c022017-12-22 16:02:54 -08002373 // Update state and SSRC of local MediaStreams and DataChannels based on the
2374 // local session description.
2375 const cricket::ContentInfo* audio_content =
2376 GetFirstAudioContent(local_description()->description());
2377 if (audio_content) {
2378 if (audio_content->rejected) {
2379 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2380 } else {
2381 const cricket::AudioContentDescription* audio_desc =
2382 audio_content->media_description()->as_audio();
2383 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2384 }
deadbeeffaac4972015-11-12 15:33:07 -08002385 }
deadbeefab9b2d12015-10-14 11:33:11 -07002386
Steve Antondcc3c022017-12-22 16:02:54 -08002387 const cricket::ContentInfo* video_content =
2388 GetFirstVideoContent(local_description()->description());
2389 if (video_content) {
2390 if (video_content->rejected) {
2391 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2392 } else {
2393 const cricket::VideoContentDescription* video_desc =
2394 video_content->media_description()->as_video();
2395 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2396 }
deadbeeffaac4972015-11-12 15:33:07 -08002397 }
deadbeefab9b2d12015-10-14 11:33:11 -07002398 }
2399
2400 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002401 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002402 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002403 const cricket::RtpDataContentDescription* rtp_data_desc =
2404 data_content->media_description()->as_rtp_data();
2405 // rtp_data_desc will be null if this is an SCTP description.
2406 if (rtp_data_desc) {
2407 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002408 }
2409 }
2410
Steve Anton8a006912017-12-04 15:25:56 -08002411 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412}
2413
Steve Anton06817cd2018-12-18 15:55:30 -08002414// The SDP parser used to populate these values by default for the 'content
2415// name' if an a=mid line was absent.
2416static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2417 switch (media_type) {
2418 case cricket::MEDIA_TYPE_AUDIO:
2419 return cricket::CN_AUDIO;
2420 case cricket::MEDIA_TYPE_VIDEO:
2421 return cricket::CN_VIDEO;
2422 case cricket::MEDIA_TYPE_DATA:
2423 return cricket::CN_DATA;
2424 }
2425 RTC_NOTREACHED();
2426 return "";
2427}
2428
2429void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002430 cricket::SessionDescription* new_remote_description) {
2431 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002432 const cricket::ContentInfos& local_contents =
2433 (local_description() ? local_description()->description()->contents()
2434 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002435 const cricket::ContentInfos& remote_contents =
2436 (remote_description() ? remote_description()->description()->contents()
2437 : cricket::ContentInfos());
2438 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2439 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002440 if (!content.name.empty()) {
2441 continue;
2442 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002443 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002444 absl::string_view source_explanation;
2445 if (IsUnifiedPlan()) {
2446 if (i < local_contents.size()) {
2447 new_mid = local_contents[i].name;
2448 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002449 } else if (i < remote_contents.size()) {
2450 new_mid = remote_contents[i].name;
2451 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002452 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002453 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002454 source_explanation = "generated just now";
2455 }
2456 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002457 new_mid = std::string(
2458 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002459 source_explanation = "to match pre-existing behavior";
2460 }
Steve Antond7180cc2019-02-07 10:44:53 -08002461 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002462 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002463 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002464 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2465 << " is missing an a=mid line. Filling in the value '"
2466 << new_mid << "' " << source_explanation << ".";
2467 }
2468}
2469
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002471 SetSessionDescriptionObserver* observer,
2472 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002473 SetRemoteDescription(
2474 std::unique_ptr<SessionDescriptionInterface>(desc),
2475 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2476 new SetRemoteDescriptionObserverAdapter(this, observer)));
2477}
2478
2479void PeerConnection::SetRemoteDescription(
2480 std::unique_ptr<SessionDescriptionInterface> desc,
2481 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002482 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002483 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002484
nisse7ce109a2017-01-31 00:57:56 -08002485 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002486 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002487 return;
2488 }
Steve Anton8a006912017-12-04 15:25:56 -08002489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002491 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002492 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 return;
2494 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002495
Steve Anton80dd7b52018-02-16 17:08:42 -08002496 // If a session error has occurred the PeerConnection is in a possibly
2497 // inconsistent state so fail right away.
2498 if (session_error() != SessionError::kNone) {
2499 std::string error_message = GetSessionErrorMsg();
2500 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2501 observer->OnSetRemoteDescriptionComplete(
2502 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2503 return;
2504 }
Steve Anton71439a62018-02-15 11:53:06 -08002505
Steve Antonba42e992018-04-09 14:10:01 -07002506 if (desc->GetType() == SdpType::kOffer) {
2507 // Report to UMA the format of the received offer.
2508 ReportSdpFormatReceived(*desc);
2509 }
2510
Steve Anton06817cd2018-12-18 15:55:30 -08002511 // Handle remote descriptions missing a=mid lines for interop with legacy end
2512 // points.
2513 FillInMissingRemoteMids(desc->description());
2514
Steve Anton80dd7b52018-02-16 17:08:42 -08002515 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002516 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002517 std::string error_message = GetSetDescriptionErrorMessage(
2518 cricket::CS_REMOTE, desc->GetType(), error);
2519 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002520 observer->OnSetRemoteDescriptionComplete(
2521 RTCError(error.type(), std::move(error_message)));
2522 return;
2523 }
Steve Anton71439a62018-02-15 11:53:06 -08002524
Steve Anton80dd7b52018-02-16 17:08:42 -08002525 // Grab the description type before moving ownership to
2526 // ApplyRemoteDescription, which may destroy it before returning.
2527 const SdpType type = desc->GetType();
2528
2529 error = ApplyRemoteDescription(std::move(desc));
2530 // |desc| may be destroyed at this point.
2531
2532 if (!error.ok()) {
2533 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2534 // inconsistent state, so act conservatively here and set the session error
2535 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2536 SetSessionError(SessionError::kContent, error.message());
2537 std::string error_message =
2538 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2539 RTC_LOG(LS_ERROR) << error_message;
2540 observer->OnSetRemoteDescriptionComplete(
2541 RTCError(error.type(), std::move(error_message)));
2542 return;
2543 }
2544 RTC_DCHECK(remote_description());
2545
2546 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002547 // TODO(deadbeef): We already had to hop to the network thread for
2548 // MaybeStartGathering...
2549 network_thread()->Invoke<void>(
2550 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2551 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002552 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002553 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002554 }
2555
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002556 if (IsUnifiedPlan()) {
2557 bool was_negotiation_needed = is_negotiation_needed_;
2558 UpdateNegotiationNeeded();
2559 if (signaling_state() == kStable && was_negotiation_needed &&
2560 is_negotiation_needed_) {
2561 Observer()->OnRenegotiationNeeded();
2562 }
2563 }
2564
Steve Anton8a006912017-12-04 15:25:56 -08002565 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002566 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002567}
2568
2569RTCError PeerConnection::ApplyRemoteDescription(
2570 std::unique_ptr<SessionDescriptionInterface> desc) {
2571 RTC_DCHECK_RUN_ON(signaling_thread());
2572 RTC_DCHECK(desc);
2573
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574 // Update stats here so that we have the most recent stats for tracks and
2575 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002576 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002577
Steve Antondcc3c022017-12-22 16:02:54 -08002578 // Take a reference to the old remote description since it's used below to
2579 // compare against the new remote description. When setting the new remote
2580 // description, grab ownership of the replaced session description in case it
2581 // is the same as |old_remote_description|, to keep it alive for the duration
2582 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002583 const SessionDescriptionInterface* old_remote_description =
2584 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002585 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002586 SdpType type = desc->GetType();
2587 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002588 replaced_remote_description = pending_remote_description_
2589 ? std::move(pending_remote_description_)
2590 : std::move(current_remote_description_);
2591 current_remote_description_ = std::move(desc);
2592 pending_remote_description_ = nullptr;
2593 current_local_description_ = std::move(pending_local_description_);
2594 } else {
2595 replaced_remote_description = std::move(pending_remote_description_);
2596 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597 }
Steve Anton8a006912017-12-04 15:25:56 -08002598 // The session description to apply now must be accessed by
2599 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002600 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002602 // Report statistics about any use of simulcast.
2603 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2604 *remote_description()->description());
2605
Zhi Huange830e682018-03-30 10:48:35 -07002606 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2607 if (!error.ok()) {
2608 return error;
2609 }
Steve Anton8a006912017-12-04 15:25:56 -08002610 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002611 if (IsUnifiedPlan()) {
2612 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002613 cricket::CS_REMOTE, *remote_description(), local_description(),
2614 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002615 if (!error.ok()) {
2616 return error;
2617 }
Steve Antondcc3c022017-12-22 16:02:54 -08002618 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002619 // Media channels will be created only when offer is set. These may use new
2620 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002621 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002622 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002623 // description is applied. Restore back to old description.
2624 RTCError error = CreateChannels(*remote_description()->description());
2625 if (!error.ok()) {
2626 return error;
2627 }
2628 }
Steve Antondcc3c022017-12-22 16:02:54 -08002629 // Remove unused channels if MediaContentDescription is rejected.
2630 RemoveUnusedChannels(remote_description()->description());
2631 }
Steve Anton8a006912017-12-04 15:25:56 -08002632
Zhi Huange830e682018-03-30 10:48:35 -07002633 // NOTE: Candidates allocation will be initiated only when
2634 // SetLocalDescription is called.
2635 error = UpdateSessionState(type, cricket::CS_REMOTE,
2636 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002637 if (!error.ok()) {
2638 return error;
2639 }
2640
2641 if (local_description() &&
2642 !UseCandidatesInSessionDescription(remote_description())) {
2643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2644 }
2645
2646 if (old_remote_description) {
2647 for (const cricket::ContentInfo& content :
2648 old_remote_description->description()->contents()) {
2649 // Check if this new SessionDescription contains new ICE ufrag and
2650 // password that indicates the remote peer requests an ICE restart.
2651 // TODO(deadbeef): When we start storing both the current and pending
2652 // remote description, this should reset pending_ice_restarts and compare
2653 // against the current description.
2654 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2655 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002656 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002657 pending_ice_restarts_.insert(content.name);
2658 }
2659 } else {
2660 // We retain all received candidates only if ICE is not restarted.
2661 // When ICE is restarted, all previous candidates belong to an old
2662 // generation and should not be kept.
2663 // TODO(deadbeef): This goes against the W3C spec which says the remote
2664 // description should only contain candidates from the last set remote
2665 // description plus any candidates added since then. We should remove
2666 // this once we're sure it won't break anything.
2667 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2668 old_remote_description, content.name, mutable_remote_description());
2669 }
2670 }
2671 }
2672
2673 if (session_error() != SessionError::kNone) {
2674 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2675 }
2676
2677 // Set the the ICE connection state to connecting since the connection may
2678 // become writable with peer reflexive candidates before any remote candidate
2679 // is signaled.
2680 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2681 // is to have a new signal the indicates a change in checking state from the
2682 // transport and expose a new checking() member from transport that can be
2683 // read to determine the current checking state. The existing SignalConnecting
2684 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002685 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002686 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002687 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2688 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2689 }
2690
deadbeefab9b2d12015-10-14 11:33:11 -07002691 // If setting the description decided our SSL role, allocate any necessary
2692 // SCTP sids.
2693 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002694 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002695 AllocateSctpSids(role);
2696 }
2697
Steve Antondcc3c022017-12-22 16:02:54 -08002698 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002699 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002700 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002701 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002702 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002703 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002704 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002705 const ContentInfo* content =
2706 FindMediaSectionForTransceiver(transceiver, remote_description());
2707 if (!content) {
2708 continue;
2709 }
2710 const MediaContentDescription* media_desc = content->media_description();
2711 RtpTransceiverDirection local_direction =
2712 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002713 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2714 // RTCSessionDescription: Set the associated remote streams given
2715 // transceiver.[[Receiver]], msids, addList, and removeList".
2716 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2717 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2718 std::vector<std::string> stream_ids;
2719 if (!media_desc->streams().empty()) {
2720 // The remote description has signaled the stream IDs.
2721 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002722 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002723 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2724 << " (" << GetStreamIdsString(stream_ids) << ").";
2725 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2726 stream_ids, &added_streams,
2727 &removed_streams);
2728 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2729 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2730 // and transceiver's current direction is neither sendrecv nor recvonly,
2731 // process the addition of a remote track for the media description.
2732 if (!transceiver->fired_direction() ||
2733 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2734 RTC_LOG(LS_INFO)
2735 << "Processing the addition of a remote track for MID="
2736 << content->name << ".";
2737 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002738 }
Steve Antondcc3c022017-12-22 16:02:54 -08002739 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002740 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002741 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2742 // removal of a remote track for the media description, given transceiver,
2743 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002744 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002745 (transceiver->fired_direction() &&
2746 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2747 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2748 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002749 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002750 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002751 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002752 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002754 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002755 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002756 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002757 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002758 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2759 if (transceiver->mid()) {
2760 auto dtls_transport =
2761 LookupDtlsTransportByMidInternal(*transceiver->mid());
2762 transceiver->internal()->sender_internal()->set_transport(
2763 dtls_transport);
2764 transceiver->internal()->receiver_internal()->set_transport(
2765 dtls_transport);
2766 }
Steve Antondcc3c022017-12-22 16:02:54 -08002767 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002768 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002769 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002770 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002771 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2772 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002773 transceiver->Stop();
2774 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002775 if (!content->rejected &&
2776 RtpTransceiverDirectionHasRecv(local_direction)) {
2777 // Set ssrc to 0 in the case of an unsignalled ssrc.
2778 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002779 if (!media_desc->streams().empty() &&
2780 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002781 ssrc = media_desc->streams()[0].first_ssrc();
2782 }
2783 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002784 }
Steve Antondcc3c022017-12-22 16:02:54 -08002785 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002786 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002787 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002788 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002789 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002790 observer->OnTrack(transceiver);
2791 observer->OnAddTrack(transceiver->receiver(),
2792 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002793 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002794 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002795 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002796 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002797 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002798 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002799 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002801 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002802 }
Steve Antondcc3c022017-12-22 16:02:54 -08002803 }
2804
Henrik Boströmfdb92012017-11-09 19:55:44 +01002805 const cricket::ContentInfo* audio_content =
2806 GetFirstAudioContent(remote_description()->description());
2807 const cricket::ContentInfo* video_content =
2808 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002809 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002810 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002811 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002812 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002813 const cricket::RtpDataContentDescription* rtp_data_desc =
2814 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002815
2816 // Check if the descriptions include streams, just in case the peer supports
2817 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002818 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002819 (audio_desc && !audio_desc->streams().empty()) ||
2820 (video_desc && !video_desc->streams().empty())) {
2821 remote_peer_supports_msid_ = true;
2822 }
deadbeefab9b2d12015-10-14 11:33:11 -07002823
2824 // We wait to signal new streams until we finish processing the description,
2825 // since only at that point will new streams have all their tracks.
2826 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2827
Steve Antondcc3c022017-12-22 16:02:54 -08002828 if (!IsUnifiedPlan()) {
2829 // TODO(steveanton): When removing RTP senders/receivers in response to a
2830 // rejected media section, there is some cleanup logic that expects the
2831 // voice/ video channel to still be set. But in this method the voice/video
2832 // channel would have been destroyed by the SetRemoteDescription caller
2833 // above so the cleanup that relies on them fails to run. The RemoveSenders
2834 // calls should be moved to right before the DestroyChannel calls to fix
2835 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002836
Steve Antondcc3c022017-12-22 16:02:54 -08002837 // Find all audio rtp streams and create corresponding remote AudioTracks
2838 // and MediaStreams.
2839 if (audio_content) {
2840 if (audio_content->rejected) {
2841 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2842 } else {
2843 bool default_audio_track_needed =
2844 !remote_peer_supports_msid_ &&
2845 RtpTransceiverDirectionHasSend(audio_desc->direction());
2846 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2847 default_audio_track_needed, audio_desc->type(),
2848 new_streams);
2849 }
deadbeeffaac4972015-11-12 15:33:07 -08002850 }
deadbeefab9b2d12015-10-14 11:33:11 -07002851
Steve Antondcc3c022017-12-22 16:02:54 -08002852 // Find all video rtp streams and create corresponding remote VideoTracks
2853 // and MediaStreams.
2854 if (video_content) {
2855 if (video_content->rejected) {
2856 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2857 } else {
2858 bool default_video_track_needed =
2859 !remote_peer_supports_msid_ &&
2860 RtpTransceiverDirectionHasSend(video_desc->direction());
2861 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2862 default_video_track_needed, video_desc->type(),
2863 new_streams);
2864 }
deadbeeffaac4972015-11-12 15:33:07 -08002865 }
deadbeefab9b2d12015-10-14 11:33:11 -07002866
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002867 // If this is an RTP data transport, update the DataChannels with the
2868 // information from the remote peer.
2869 if (rtp_data_desc) {
2870 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002871 }
deadbeefab9b2d12015-10-14 11:33:11 -07002872
Steve Antondcc3c022017-12-22 16:02:54 -08002873 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002874 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002875 for (size_t i = 0; i < new_streams->count(); ++i) {
2876 MediaStreamInterface* new_stream = new_streams->at(i);
2877 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002878 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002879 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2880 }
deadbeefab9b2d12015-10-14 11:33:11 -07002881
Steve Antondcc3c022017-12-22 16:02:54 -08002882 UpdateEndedRemoteMediaStreams();
2883 }
deadbeefab9b2d12015-10-14 11:33:11 -07002884
Steve Anton8a006912017-12-04 15:25:56 -08002885 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002886}
2887
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002888void PeerConnection::SetAssociatedRemoteStreams(
2889 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2890 const std::vector<std::string>& stream_ids,
2891 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2892 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2893 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2894 for (const std::string& stream_id : stream_ids) {
2895 rtc::scoped_refptr<MediaStreamInterface> stream =
2896 remote_streams_->find(stream_id);
2897 if (!stream) {
2898 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2899 MediaStream::Create(stream_id));
2900 remote_streams_->AddStream(stream);
2901 added_streams->push_back(stream);
2902 }
2903 media_streams.push_back(stream);
2904 }
2905 // Special case: "a=msid" missing, use random stream ID.
2906 if (media_streams.empty() &&
2907 !(remote_description()->description()->msid_signaling() &
2908 cricket::kMsidSignalingMediaSection)) {
2909 if (!missing_msid_default_stream_) {
2910 missing_msid_default_stream_ = MediaStreamProxy::Create(
2911 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2912 added_streams->push_back(missing_msid_default_stream_);
2913 }
2914 media_streams.push_back(missing_msid_default_stream_);
2915 }
2916 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2917 receiver->streams();
2918 // SetStreams() will add/remove the receiver's track to/from the streams. This
2919 // differs from the spec - the spec uses an "addList" and "removeList" to
2920 // update the stream-track relationships in a later step. We do this earlier,
2921 // changing the order of things, but the end-result is the same.
2922 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2923 // instead. https://crbug.com/webrtc/9480
2924 receiver->SetStreams(media_streams);
2925 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2926}
2927
Steve Anton0f5400a2018-07-17 14:25:36 -07002928void PeerConnection::ProcessRemovalOfRemoteTrack(
2929 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2930 transceiver,
2931 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2932 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2933 RTC_DCHECK(transceiver->mid());
2934 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2935 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002936 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002937 transceiver->internal()->receiver_internal()->streams();
2938 // This will remove the remote track from the streams.
2939 transceiver->internal()->receiver_internal()->set_stream_ids({});
2940 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002941 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2942}
2943
2944void PeerConnection::RemoveRemoteStreamsIfEmpty(
2945 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2946 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2947 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2948 // streams, see if the stream was removed by checking if this was the last
2949 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002950 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002951 if (remote_stream->GetAudioTracks().empty() &&
2952 remote_stream->GetVideoTracks().empty()) {
2953 remote_streams_->RemoveStream(remote_stream);
2954 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002955 }
2956 }
2957}
2958
Steve Antondcc3c022017-12-22 16:02:54 -08002959RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2960 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002961 const SessionDescriptionInterface& new_session,
2962 const SessionDescriptionInterface* old_local_description,
2963 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002964 RTC_DCHECK(IsUnifiedPlan());
2965
Steve Anton7464fca2018-01-19 11:10:37 -08002966 const cricket::ContentGroup* bundle_group = nullptr;
2967 if (new_session.GetType() == SdpType::kOffer) {
2968 auto bundle_group_or_error =
2969 GetEarlyBundleGroup(*new_session.description());
2970 if (!bundle_group_or_error.ok()) {
2971 return bundle_group_or_error.MoveError();
2972 }
2973 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002974 }
Steve Antondcc3c022017-12-22 16:02:54 -08002975
Steve Antondcc3c022017-12-22 16:02:54 -08002976 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002977 for (size_t i = 0; i < new_contents.size(); ++i) {
2978 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002979 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002980 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002981 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2982 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002983 const cricket::ContentInfo* old_local_content = nullptr;
2984 if (old_local_description &&
2985 i < old_local_description->description()->contents().size()) {
2986 old_local_content =
2987 &old_local_description->description()->contents()[i];
2988 }
2989 const cricket::ContentInfo* old_remote_content = nullptr;
2990 if (old_remote_description &&
2991 i < old_remote_description->description()->contents().size()) {
2992 old_remote_content =
2993 &old_remote_description->description()->contents()[i];
2994 }
Steve Antondcc3c022017-12-22 16:02:54 -08002995 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002996 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2997 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002998 if (!transceiver_or_error.ok()) {
2999 return transceiver_or_error.MoveError();
3000 }
3001 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003002 RTCError error =
3003 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3004 if (!error.ok()) {
3005 return error;
3006 }
3007 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003008 if (GetDataMid() && new_content.name != *GetDataMid()) {
3009 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003010 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3011 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003012 continue;
3013 }
3014 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3015 if (!error.ok()) {
3016 return error;
3017 }
Steve Antondcc3c022017-12-22 16:02:54 -08003018 } else {
3019 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3020 "Unknown section type.");
3021 }
3022 }
3023
3024 return RTCError::OK();
3025}
3026
3027RTCError PeerConnection::UpdateTransceiverChannel(
3028 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3029 transceiver,
3030 const cricket::ContentInfo& content,
3031 const cricket::ContentGroup* bundle_group) {
3032 RTC_DCHECK(IsUnifiedPlan());
3033 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003034 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003035 if (content.rejected) {
3036 if (channel) {
3037 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003038 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003039 }
3040 } else {
3041 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003042 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003043 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003044 } else {
Steve Anton69470252018-02-09 11:43:08 -08003045 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003046 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003047 }
3048 if (!channel) {
3049 LOG_AND_RETURN_ERROR(
3050 RTCErrorType::INTERNAL_ERROR,
3051 "Failed to create channel for mid=" + content.name);
3052 }
3053 transceiver->internal()->SetChannel(channel);
3054 }
3055 }
3056 return RTCError::OK();
3057}
3058
Steve Antonfa2260d2017-12-28 16:38:23 -08003059RTCError PeerConnection::UpdateDataChannel(
3060 cricket::ContentSource source,
3061 const cricket::ContentInfo& content,
3062 const cricket::ContentGroup* bundle_group) {
3063 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003064 // If data channels are disabled, ignore this media section. CreateAnswer
3065 // will take care of rejecting it.
3066 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003067 }
3068 if (content.rejected) {
3069 DestroyDataChannel();
3070 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003071 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003072 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003073 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3074 "Failed to create data channel.");
3075 }
3076 }
3077 if (source == cricket::CS_REMOTE) {
3078 const MediaContentDescription* data_desc = content.media_description();
3079 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3080 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3081 }
3082 }
3083 }
3084 return RTCError::OK();
3085}
3086
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003087// This method will extract any send encodings that were sent by the remote
3088// connection. This is currently only relevant for Simulcast scenario (where
3089// the number of layers may be communicated by the server).
3090static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3091 const MediaContentDescription& desc) {
3092 if (!desc.HasSimulcast()) {
3093 return {};
3094 }
3095 std::vector<RtpEncodingParameters> result;
3096 const SimulcastDescription& simulcast = desc.simulcast_description();
3097
3098 // This is a remote description, the parameters we are after should appear
3099 // as receive streams.
3100 for (const auto& alternatives : simulcast.receive_layers()) {
3101 RTC_DCHECK(!alternatives.empty());
3102 // There is currently no way to specify or choose from alternatives.
3103 // We will always use the first alternative, which is the most preferred.
3104 const SimulcastLayer& layer = alternatives[0];
3105 RtpEncodingParameters parameters;
3106 parameters.rid = layer.rid;
3107 parameters.active = !layer.is_paused;
3108 result.push_back(parameters);
3109 }
3110
3111 return result;
3112}
3113
3114static RTCError UpdateSimulcastLayerStatusInSender(
3115 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003116 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003117 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003118 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003119 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003120
3121 // The simulcast envelope cannot be changed, only the status of the streams.
3122 // So we will iterate over the send encodings rather than the layers.
3123 for (RtpEncodingParameters& encoding : parameters.encodings) {
3124 auto iter = std::find_if(layers.begin(), layers.end(),
3125 [&encoding](const SimulcastLayer& layer) {
3126 return layer.rid == encoding.rid;
3127 });
3128 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003129 if (iter == layers.end()) {
3130 disabled_layers.push_back(encoding.rid);
3131 continue;
3132 }
3133
3134 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003135 }
3136
Amit Hilbuch619b2942019-02-26 15:55:19 -08003137 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003138 if (result.ok()) {
3139 result = sender->DisableEncodingLayers(disabled_layers);
3140 }
3141
3142 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003143}
3144
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003145static bool SimulcastIsRejected(
3146 const ContentInfo* local_content,
3147 const MediaContentDescription& answer_media_desc) {
3148 bool simulcast_offered = local_content &&
3149 local_content->media_description() &&
3150 local_content->media_description()->HasSimulcast();
3151 bool simulcast_answered = answer_media_desc.HasSimulcast();
3152 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3153 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3154 return simulcast_offered && (!simulcast_answered || !rids_supported);
3155}
3156
Amit Hilbuch2297d332019-02-19 12:49:22 -08003157static RTCError DisableSimulcastInSender(
3158 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003159 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003160 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003161 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003162 return RTCError::OK();
3163 }
3164
Amit Hilbuch2297d332019-02-19 12:49:22 -08003165 std::vector<std::string> disabled_layers;
3166 std::transform(
3167 parameters.encodings.begin() + 1, parameters.encodings.end(),
3168 std::back_inserter(disabled_layers),
3169 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3170 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003171}
3172
Steve Antondcc3c022017-12-22 16:02:54 -08003173RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3174PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003175 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003176 size_t mline_index,
3177 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003178 const ContentInfo* old_local_content,
3179 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003180 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003181 // If this is an offer then the m= section might be recycled. If the m=
3182 // section is being recycled (defined as: rejected in the current local or
3183 // remote description and not rejected in new description), dissociate the
3184 // currently associated RtpTransceiver by setting its mid property to null,
3185 // and discard the mapping between the transceiver and its m= section index.
3186 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3187 old_remote_content)) {
3188 // We want to dissociate the transceiver that has the rejected mid.
3189 const std::string& old_mid =
3190 (old_local_content && old_local_content->rejected)
3191 ? old_local_content->name
3192 : old_remote_content->name;
3193 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003194 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003195 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3196 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003197 old_transceiver->internal()->set_mid(absl::nullopt);
3198 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003199 }
3200 }
3201 const MediaContentDescription* media_desc = content.media_description();
3202 auto transceiver = GetAssociatedTransceiver(content.name);
3203 if (source == cricket::CS_LOCAL) {
3204 // Find the RtpTransceiver that corresponds to this m= section, using the
3205 // mapping between transceivers and m= section indices established when
3206 // creating the offer.
3207 if (!transceiver) {
3208 transceiver = GetTransceiverByMLineIndex(mline_index);
3209 }
3210 if (!transceiver) {
3211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3212 "Unknown transceiver");
3213 }
3214 } else {
3215 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3216 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3217 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003218 // When simulcast is requested, a transceiver cannot be associated because
3219 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003220 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003221 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3222 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003223 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3224 }
3225 // If no RtpTransceiver was found in the previous step, create one with a
3226 // recvonly direction.
3227 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003228 RTC_LOG(LS_INFO) << "Adding "
3229 << cricket::MediaTypeToString(media_desc->type())
3230 << " transceiver for MID=" << content.name
3231 << " at i=" << mline_index
3232 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003233 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003234 std::vector<RtpEncodingParameters> send_encodings =
3235 GetSendEncodingsFromRemoteDescription(*media_desc);
3236 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3237 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003238 std::string receiver_id;
3239 if (!media_desc->streams().empty()) {
3240 receiver_id = media_desc->streams()[0].id;
3241 } else {
3242 receiver_id = rtc::CreateRandomUuid();
3243 }
3244 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003245 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003246 transceiver->internal()->set_direction(
3247 RtpTransceiverDirection::kRecvOnly);
3248 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003249
3250 // Check if the offer indicated simulcast but the answer rejected it.
3251 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003252 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003253 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003254 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003255 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003256 if (!error.ok()) {
3257 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3258 return std::move(error);
3259 }
3260 }
Steve Antondcc3c022017-12-22 16:02:54 -08003261 }
3262 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003263 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003264 LOG_AND_RETURN_ERROR(
3265 RTCErrorType::INVALID_PARAMETER,
3266 "Transceiver type does not match media description type.");
3267 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003268 if (media_desc->HasSimulcast()) {
3269 std::vector<SimulcastLayer> layers =
3270 source == cricket::CS_LOCAL
3271 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3272 : media_desc->simulcast_description()
3273 .receive_layers()
3274 .GetAllLayers();
3275 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003276 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003277 if (!error.ok()) {
3278 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3279 return std::move(error);
3280 }
3281 }
Steve Antondcc3c022017-12-22 16:02:54 -08003282 // Associate the found or created RtpTransceiver with the m= section by
3283 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3284 // section, and establish a mapping between the transceiver and the index of
3285 // the m= section.
3286 transceiver->internal()->set_mid(content.name);
3287 transceiver->internal()->set_mline_index(mline_index);
3288 return std::move(transceiver);
3289}
3290
3291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3292PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3293 RTC_DCHECK(IsUnifiedPlan());
3294 for (auto transceiver : transceivers_) {
3295 if (transceiver->mid() == mid) {
3296 return transceiver;
3297 }
3298 }
3299 return nullptr;
3300}
3301
3302rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3303PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3304 RTC_DCHECK(IsUnifiedPlan());
3305 for (auto transceiver : transceivers_) {
3306 if (transceiver->internal()->mline_index() == mline_index) {
3307 return transceiver;
3308 }
3309 }
3310 return nullptr;
3311}
3312
3313rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3314PeerConnection::FindAvailableTransceiverToReceive(
3315 cricket::MediaType media_type) const {
3316 RTC_DCHECK(IsUnifiedPlan());
3317 // From JSEP section 5.10 (Applying a Remote Description):
3318 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3319 // the same type that were added to the PeerConnection by addTrack and are not
3320 // associated with any m= section and are not stopped, find the first such
3321 // RtpTransceiver.
3322 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003323 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003324 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3325 !transceiver->stopped()) {
3326 return transceiver;
3327 }
3328 }
3329 return nullptr;
3330}
3331
Steve Antoned10bd92017-12-05 10:52:59 -08003332const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3333 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3334 transceiver,
3335 const SessionDescriptionInterface* sdesc) const {
3336 RTC_DCHECK(transceiver);
3337 RTC_DCHECK(sdesc);
3338 if (IsUnifiedPlan()) {
3339 if (!transceiver->internal()->mid()) {
3340 // This transceiver is not associated with a media section yet.
3341 return nullptr;
3342 }
3343 return sdesc->description()->GetContentByName(
3344 *transceiver->internal()->mid());
3345 } else {
3346 // Plan B only allows at most one audio and one video section, so use the
3347 // first media section of that type.
3348 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003349 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003350 }
3351}
3352
deadbeef46c73892016-11-16 19:42:04 -08003353PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003354 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003355 return configuration_;
3356}
3357
deadbeef293e9262017-01-11 12:28:30 -08003358bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3359 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003360 RTC_DCHECK_RUN_ON(signaling_thread());
3361 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003362 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003363 if (IsClosed()) {
3364 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3365 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3366 }
3367
Qingsi Wanga2d60672018-04-11 16:57:45 -07003368 // According to JSEP, after setLocalDescription, changing the candidate pool
3369 // size is not allowed, and changing the set of ICE servers will not result
3370 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003371 if (local_description() && configuration.ice_candidate_pool_size !=
3372 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003373 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3374 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003375 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003376 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003377
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003378 if (local_description() &&
3379 configuration.use_media_transport != configuration_.use_media_transport) {
3380 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3381 "SetLocalDescription.";
3382 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3383 }
3384
3385 if (remote_description() &&
3386 configuration.use_media_transport != configuration_.use_media_transport) {
3387 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3388 "SetRemoteDescription.";
3389 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3390 }
3391
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003392 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003393 configuration.use_media_transport_for_data_channels !=
3394 configuration_.use_media_transport_for_data_channels) {
3395 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3396 "after calling SetLocalDescription.";
3397 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3398 }
3399
3400 if (remote_description() &&
3401 configuration.use_media_transport_for_data_channels !=
3402 configuration_.use_media_transport_for_data_channels) {
3403 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3404 "after calling SetRemoteDescription.";
3405 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3406 }
3407
3408 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003409 configuration.crypto_options != configuration_.crypto_options) {
3410 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3411 "SetLocalDescription.";
3412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3413 }
3414
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003415 if (configuration.use_media_transport_for_data_channels ||
3416 configuration.use_media_transport) {
3417 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3418 << "Media transport requires MaxBundle policy.";
3419 }
3420
deadbeef293e9262017-01-11 12:28:30 -08003421 // The simplest (and most future-compatible) way to tell if the config was
3422 // modified in an invalid way is to copy each property we do support
3423 // modifying, then use operator==. There are far more properties we don't
3424 // support modifying than those we do, and more could be added.
3425 RTCConfiguration modified_config = configuration_;
3426 modified_config.servers = configuration.servers;
3427 modified_config.type = configuration.type;
3428 modified_config.ice_candidate_pool_size =
3429 configuration.ice_candidate_pool_size;
3430 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003431 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003432 modified_config.ice_check_interval_strong_connectivity =
3433 configuration.ice_check_interval_strong_connectivity;
3434 modified_config.ice_check_interval_weak_connectivity =
3435 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003436 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3437 modified_config.ice_unwritable_min_checks =
3438 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003439 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003440 modified_config.stun_candidate_keepalive_interval =
3441 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003442 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003443 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003444 modified_config.active_reset_srtp_params =
3445 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003446 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003447 modified_config.use_media_transport_for_data_channels =
3448 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003449 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003450 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003451 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3452 }
3453
Steve Anton038834f2017-07-14 15:59:59 -07003454 // Validate the modified configuration.
3455 RTCError validate_error = ValidateConfiguration(modified_config);
3456 if (!validate_error.ok()) {
3457 return SafeSetError(std::move(validate_error), error);
3458 }
3459
deadbeef293e9262017-01-11 12:28:30 -08003460 // Note that this isn't possible through chromium, since it's an unsigned
3461 // short in WebIDL.
3462 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003463 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003464 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3465 }
3466
3467 // Parse ICE servers before hopping to network thread.
3468 cricket::ServerAddresses stun_servers;
3469 std::vector<cricket::RelayServerConfig> turn_servers;
3470 RTCErrorType parse_error =
3471 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3472 if (parse_error != RTCErrorType::NONE) {
3473 return SafeSetError(parse_error, error);
3474 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003475 // Note if STUN or TURN servers were supplied.
3476 if (!stun_servers.empty()) {
3477 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3478 }
3479 if (!turn_servers.empty()) {
3480 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3481 }
deadbeef293e9262017-01-11 12:28:30 -08003482
3483 // In theory this shouldn't fail.
3484 if (!network_thread()->Invoke<bool>(
3485 RTC_FROM_HERE,
3486 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3487 stun_servers, turn_servers, modified_config.type,
3488 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003489 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003490 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003491 modified_config.stun_candidate_keepalive_interval,
3492 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003493 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003494 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3495 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003496
deadbeefd1a38b52016-12-10 13:15:33 -08003497 // As described in JSEP, calling setConfiguration with new ICE servers or
3498 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3499 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003500 if (modified_config.servers != configuration_.servers ||
3501 modified_config.type != configuration_.type ||
3502 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003503 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003504 }
skvladd1f5fda2017-02-03 16:54:05 -08003505
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003506 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003507 transport_controller_->SetMediaTransportSettings(
3508 modified_config.use_media_transport,
3509 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003510
Zhi Huangb57e1692018-06-12 11:41:11 -07003511 if (configuration_.active_reset_srtp_params !=
3512 modified_config.active_reset_srtp_params) {
3513 transport_controller_->SetActiveResetSrtpParams(
3514 modified_config.active_reset_srtp_params);
3515 }
3516
deadbeef293e9262017-01-11 12:28:30 -08003517 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003518 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003519 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003520}
3521
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003522bool PeerConnection::AddIceCandidate(
3523 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003524 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003525 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003526 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003527 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003528 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003529 return false;
3530 }
Steve Antond25da372017-11-06 14:50:29 -08003531
3532 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003533 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003534 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003535 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003536 return false;
3537 }
3538
3539 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003540 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003541 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003542 return false;
3543 }
3544
3545 bool valid = false;
3546 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3547 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003548 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003549 return false;
3550 }
3551
3552 // Add this candidate to the remote session description.
3553 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003554 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003555 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003556 return false;
3557 }
3558
3559 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003560 bool result = UseCandidate(ice_candidate);
3561 if (result) {
3562 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003563 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3564 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3565 }
3566 if (ice_candidate->candidate().address().IsPrivateIP()) {
3567 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3568 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003569 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3570 } else {
3571 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3572 }
3573 return result;
Steve Antond25da372017-11-06 14:50:29 -08003574 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003575 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003576 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003577 return true;
3578 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003579}
3580
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003581bool PeerConnection::RemoveIceCandidates(
3582 const std::vector<cricket::Candidate>& candidates) {
3583 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003584 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003585 if (IsClosed()) {
3586 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3587 return false;
3588 }
3589
Steve Antond25da372017-11-06 14:50:29 -08003590 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003591 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3592 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003593 return false;
3594 }
3595
3596 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003597 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003598 return false;
3599 }
3600
3601 size_t number_removed =
3602 mutable_remote_description()->RemoveCandidates(candidates);
3603 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003604 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003605 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003606 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003607 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003608 }
3609
3610 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003611 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3612 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003613 RTC_LOG(LS_ERROR)
3614 << "RemoveIceCandidates: Error when removing remote candidates: "
3615 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003616 }
3617 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003618}
3619
Niels Möller0c4f7be2018-05-07 14:01:37 +02003620RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003621 if (!worker_thread()->IsCurrent()) {
3622 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003623 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003624 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003625 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003626
Niels Möller0c4f7be2018-05-07 14:01:37 +02003627 const bool has_min = bitrate.min_bitrate_bps.has_value();
3628 const bool has_start = bitrate.start_bitrate_bps.has_value();
3629 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003630 if (has_min && *bitrate.min_bitrate_bps < 0) {
3631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3632 "min_bitrate_bps <= 0");
3633 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003634 if (has_start) {
3635 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003636 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003637 "start_bitrate_bps < min_bitrate_bps");
3638 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003639 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3640 "curent_bitrate_bps < 0");
3641 }
3642 }
3643 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003644 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003645 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003646 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003647 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3649 "max_bitrate_bps < min_bitrate_bps");
3650 } else if (*bitrate.max_bitrate_bps < 0) {
3651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3652 "max_bitrate_bps < 0");
3653 }
3654 }
3655
zstein4b979802017-06-02 14:37:37 -07003656 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003657 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003658
3659 return RTCError::OK();
3660}
3661
Alex Narest78609d52017-10-20 10:37:47 +02003662void PeerConnection::SetBitrateAllocationStrategy(
3663 std::unique_ptr<rtc::BitrateAllocationStrategy>
3664 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003665 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003666 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3667 // move-capture values in lambdas.
3668 struct Task {
3669 PeerConnection* const pc;
3670 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3671 void operator()() {
3672 RTC_DCHECK_RUN_ON(pc->worker_thread());
3673 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3674 }
3675 };
3676 worker_thread()->Invoke<void>(
3677 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003678 return;
3679 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003680 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003681 RTC_DCHECK(call_.get());
3682 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3683}
3684
henrika5f6bf242017-11-01 11:06:56 +01003685void PeerConnection::SetAudioPlayout(bool playout) {
3686 if (!worker_thread()->IsCurrent()) {
3687 worker_thread()->Invoke<void>(
3688 RTC_FROM_HERE,
3689 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3690 return;
3691 }
3692 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003693 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003694 audio_state->SetPlayout(playout);
3695}
3696
3697void PeerConnection::SetAudioRecording(bool recording) {
3698 if (!worker_thread()->IsCurrent()) {
3699 worker_thread()->Invoke<void>(
3700 RTC_FROM_HERE,
3701 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3702 return;
3703 }
3704 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003705 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003706 audio_state->SetRecording(recording);
3707}
3708
Steve Anton8c0f7a72017-10-03 10:03:10 -07003709std::unique_ptr<rtc::SSLCertificate>
3710PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003711 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3712 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003713 return nullptr;
3714 }
Steve Antonf25303e2018-10-16 15:23:31 -07003715 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003716}
3717
Zhi Huang70b820f2018-01-27 14:16:15 -08003718std::unique_ptr<rtc::SSLCertChain>
3719PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003720 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003721 auto audio_transceiver = GetFirstAudioTransceiver();
3722 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003723 return nullptr;
3724 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003725 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003726 audio_transceiver->internal()->channel()->transport_name());
3727}
3728
3729rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3730PeerConnection::GetFirstAudioTransceiver() const {
3731 for (auto transceiver : transceivers_) {
3732 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3733 return transceiver;
3734 }
3735 }
3736 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003737}
3738
ivoc14d5dbe2016-07-04 07:06:55 -07003739bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3740 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003741 // TODO(eladalon): It would be better to not allow negative values into PC.
3742 const size_t max_size = (max_size_bytes < 0)
3743 ? RtcEventLog::kUnlimitedOutput
3744 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003745 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3746 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3747 output_period_ms = 5000;
3748 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003749 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003750 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003751 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003752}
3753
Bjorn Tereliusde939432017-11-20 17:38:14 +01003754bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3755 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003756 // TODO(eladalon): In C++14, this can be done with a lambda.
3757 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003758 bool operator()() {
3759 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3760 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003761 PeerConnection* const pc;
3762 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003763 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003764 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003765 return worker_thread()->Invoke<bool>(
3766 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003767}
3768
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003769bool PeerConnection::StartRtcEventLog(
3770 std::unique_ptr<RtcEventLogOutput> output) {
3771 return StartRtcEventLog(std::move(output),
3772 webrtc::RtcEventLog::kImmediateOutput);
3773}
3774
ivoc14d5dbe2016-07-04 07:06:55 -07003775void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003776 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003777 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3778}
3779
Harald Alvestrandad88c882018-11-28 16:47:46 +01003780rtc::scoped_refptr<DtlsTransportInterface>
3781PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003782 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003783 return transport_controller_->LookupDtlsTransportByMid(mid);
3784}
3785
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003786rtc::scoped_refptr<DtlsTransport>
3787PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003788 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003789 return transport_controller_->LookupDtlsTransportByMid(mid);
3790}
3791
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003792rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3793 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003794 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003795 return sctp_transport_;
3796}
3797
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003798const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003799 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003800 return pending_local_description_ ? pending_local_description_.get()
3801 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003802}
3803
3804const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003805 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003806 return pending_remote_description_ ? pending_remote_description_.get()
3807 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003808}
3809
deadbeeffe4a8a42016-12-20 17:56:17 -08003810const SessionDescriptionInterface* PeerConnection::current_local_description()
3811 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003812 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003813 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003814}
3815
3816const SessionDescriptionInterface* PeerConnection::current_remote_description()
3817 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003818 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003819 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003820}
3821
3822const SessionDescriptionInterface* PeerConnection::pending_local_description()
3823 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003824 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003825 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003826}
3827
3828const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3829 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003830 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003831 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003832}
3833
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003834void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003835 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003836 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003837 // Update stats here so that we have the most recent stats for tracks and
3838 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003839 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003840
Steve Anton75737c02017-11-06 10:37:17 -08003841 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003842 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003843
Mirko Bonadei739baf02019-01-27 17:29:42 +01003844 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003845 transceiver->Stop();
3846 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003847
3848 // Ensure that all asynchronous stats requests are completed before destroying
3849 // the transport controller below.
3850 if (stats_collector_) {
3851 stats_collector_->WaitForPendingRequest();
3852 }
3853
3854 // Don't destroy BaseChannels until after stats has been cleaned up so that
3855 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003856 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003857
Qingsi Wang93a84392018-01-30 17:13:09 -08003858 // The event log is used in the transport controller, which must be outlived
3859 // by the former. CreateOffer by the peer connection is implemented
3860 // asynchronously and if the peer connection is closed without resetting the
3861 // WebRTC session description factory, the session description factory would
3862 // call the transport controller.
3863 webrtc_session_desc_factory_.reset();
3864 transport_controller_.reset();
3865
deadbeef42a42632017-03-10 15:18:00 -08003866 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003867 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3868 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003869
Steve Anton978b8762017-09-29 12:15:02 -07003870 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003871 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003872 call_.reset();
3873 // The event log must outlive call (and any other object that uses it).
3874 event_log_.reset();
3875 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003876 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003877 // The .h file says that observer can be discarded after close() returns.
3878 // Make sure this is true.
3879 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003880}
3881
Steve Antonad182762018-09-05 20:22:40 +00003882void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003883 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003884 switch (msg->message_id) {
3885 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3886 SetSessionDescriptionMsg* param =
3887 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3888 param->observer->OnSuccess();
3889 delete param;
3890 break;
3891 }
3892 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3893 SetSessionDescriptionMsg* param =
3894 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3895 param->observer->OnFailure(std::move(param->error));
3896 delete param;
3897 break;
3898 }
3899 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3900 CreateSessionDescriptionMsg* param =
3901 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3902 param->observer->OnFailure(std::move(param->error));
3903 delete param;
3904 break;
3905 }
3906 case MSG_GETSTATS: {
3907 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3908 StatsReports reports;
3909 stats_->GetStats(param->track, &reports);
3910 param->observer->OnComplete(reports);
3911 delete param;
3912 break;
3913 }
3914 case MSG_FREE_DATACHANNELS: {
3915 sctp_data_channels_to_free_.clear();
3916 break;
3917 }
3918 case MSG_REPORT_USAGE_PATTERN: {
3919 ReportUsagePattern();
3920 break;
3921 }
3922 default:
3923 RTC_NOTREACHED() << "Not implemented";
3924 break;
3925 }
3926}
3927
Steve Antonafb0bb72018-02-20 11:35:37 -08003928cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3929 RTC_DCHECK(!IsUnifiedPlan());
3930 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3931 GetAudioTransceiver()->internal()->channel());
3932 if (voice_channel) {
3933 return voice_channel->media_channel();
3934 } else {
3935 return nullptr;
3936 }
3937}
3938
3939cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3940 RTC_DCHECK(!IsUnifiedPlan());
3941 auto* video_channel = static_cast<cricket::VideoChannel*>(
3942 GetVideoTransceiver()->internal()->channel());
3943 if (video_channel) {
3944 return video_channel->media_channel();
3945 } else {
3946 return nullptr;
3947 }
3948}
3949
Steve Anton4171afb2017-11-20 10:20:22 -08003950void PeerConnection::CreateAudioReceiver(
3951 MediaStreamInterface* stream,
3952 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003953 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3954 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003955 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3956 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003957 auto* audio_receiver = new AudioRtpReceiver(
3958 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003959 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003960 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3961 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3962 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003963 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003964 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003965 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003966}
3967
Steve Anton4171afb2017-11-20 10:20:22 -08003968void PeerConnection::CreateVideoReceiver(
3969 MediaStreamInterface* stream,
3970 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003971 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3972 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003973 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3974 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003975 auto* video_receiver = new VideoRtpReceiver(
3976 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003977 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003978 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3979 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3980 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003981 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003982 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003983 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003984}
3985
deadbeef70ab1a12015-09-28 16:53:55 -07003986// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3987// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003988rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003989 const RtpSenderInfo& remote_sender_info) {
3990 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3991 if (!receiver) {
3992 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3993 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003994 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003995 }
Steve Anton4171afb2017-11-20 10:20:22 -08003996 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3997 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3998 } else {
3999 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4000 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004001 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004002}
4003
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004004void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4005 MediaStreamInterface* stream) {
4006 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004007 RTC_DCHECK(track);
4008 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004009 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004010 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004011 // We already have a sender for this track, so just change the stream_id
4012 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004013 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004014 return;
4015 }
4016
4017 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004018 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004019 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004020 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004021 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004022 // If the sender has already been configured in SDP, we call SetSsrc,
4023 // which will connect the sender to the underlying transport. This can
4024 // occur if a local session description that contains the ID of the sender
4025 // is set before AddStream is called. It can also occur if the local
4026 // session description is not changed and RemoveStream is called, and
4027 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004028 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004029 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004030 if (sender_info) {
4031 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004032 }
4033}
4034
4035// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4036// indefinitely, when we have unified plan SDP.
4037void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4038 MediaStreamInterface* stream) {
4039 RTC_DCHECK(!IsClosed());
4040 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004041 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004042 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4043 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004044 return;
4045 }
Steve Anton4171afb2017-11-20 10:20:22 -08004046 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004047}
4048
4049void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4050 MediaStreamInterface* stream) {
4051 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004052 RTC_DCHECK(track);
4053 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004054 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004055 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004056 // We already have a sender for this track, so just change the stream_id
4057 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004058 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004059 return;
4060 }
4061
4062 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004063 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004064 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004065 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004066 GetVideoTransceiver()->internal()->AddSender(new_sender);
4067 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004068 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004069 if (sender_info) {
4070 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004071 }
4072}
4073
4074void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4075 MediaStreamInterface* stream) {
4076 RTC_DCHECK(!IsClosed());
4077 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004078 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004079 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4080 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004081 return;
4082 }
Steve Anton4171afb2017-11-20 10:20:22 -08004083 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004084}
4085
Steve Antonba818672017-11-06 10:21:57 -08004086void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004087 if (ice_connection_state_ == new_state) {
4088 return;
4089 }
4090
deadbeefcbecd352015-09-23 11:50:27 -07004091 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004092 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004093 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004094 return;
4095 }
Steve Antonba818672017-11-06 10:21:57 -08004096
Mirko Bonadei675513b2017-11-09 11:09:25 +01004097 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4098 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004099 RTC_DCHECK(ice_connection_state_ !=
4100 PeerConnectionInterface::kIceConnectionClosed);
4101
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004102 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004103 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004104}
4105
Alex Loiko9289eda2018-11-23 16:18:59 +00004106void PeerConnection::SetStandardizedIceConnectionState(
4107 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004108 if (standardized_ice_connection_state_ == new_state)
4109 return;
4110 if (IsClosed())
4111 return;
4112 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004113 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004114}
4115
Jonas Olsson635474e2018-10-18 15:58:17 +02004116void PeerConnection::SetConnectionState(
4117 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004118 if (connection_state_ == new_state)
4119 return;
4120 if (IsClosed())
4121 return;
4122 connection_state_ = new_state;
4123 Observer()->OnConnectionChange(new_state);
4124}
4125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004126void PeerConnection::OnIceGatheringChange(
4127 PeerConnectionInterface::IceGatheringState new_state) {
4128 if (IsClosed()) {
4129 return;
4130 }
4131 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004132 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004133}
4134
jbauch81bf7b02017-03-25 08:31:12 -07004135void PeerConnection::OnIceCandidate(
4136 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004137 if (IsClosed()) {
4138 return;
4139 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004140 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004141 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4142 candidate->candidate().address().IsPrivateIP()) {
4143 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4144 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004145 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4146 candidate->candidate().address().IsUnresolvedIP()) {
4147 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4148 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004149 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004150}
4151
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004152void PeerConnection::OnIceCandidatesRemoved(
4153 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004154 if (IsClosed()) {
4155 return;
4156 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004157 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004158}
4159
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004160void PeerConnection::ChangeSignalingState(
4161 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004162 if (signaling_state_ == signaling_state) {
4163 return;
4164 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004165 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4166 << GetSignalingStateString(signaling_state_)
4167 << " New state: "
4168 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004169 signaling_state_ = signaling_state;
4170 if (signaling_state == kClosed) {
4171 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004172 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004173 standardized_ice_connection_state_ =
4174 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004175 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4176 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004177 if (ice_gathering_state_ != kIceGatheringComplete) {
4178 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004179 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004180 }
4181 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004182 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004183}
4184
deadbeefeb459812015-12-15 19:24:43 -08004185void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4186 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004187 if (IsClosed()) {
4188 return;
4189 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004190 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004191 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004192}
4193
deadbeefeb459812015-12-15 19:24:43 -08004194void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4195 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004196 if (IsClosed()) {
4197 return;
4198 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004199 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004200 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004201}
4202
4203void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4204 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004205 if (IsClosed()) {
4206 return;
4207 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004208 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004209 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004210}
4211
4212void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4213 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004214 if (IsClosed()) {
4215 return;
4216 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004218 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004219}
4220
Henrik Boström31638672017-11-23 17:48:32 +01004221void PeerConnection::PostSetSessionDescriptionSuccess(
4222 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004223 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4224 signaling_thread()->Post(RTC_FROM_HERE, this,
4225 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004226}
4227
deadbeefab9b2d12015-10-14 11:33:11 -07004228void PeerConnection::PostSetSessionDescriptionFailure(
4229 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004230 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004231 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004232 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4233 msg->error = std::move(error);
4234 signaling_thread()->Post(RTC_FROM_HERE, this,
4235 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004236}
4237
4238void PeerConnection::PostCreateSessionDescriptionFailure(
4239 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004240 RTCError error) {
4241 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004242 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4243 msg->error = std::move(error);
4244 signaling_thread()->Post(RTC_FROM_HERE, this,
4245 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004246}
4247
zhihuang1c378ed2017-08-17 14:10:50 -07004248void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004249 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004250 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004251 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004252
Steve Antondcc3c022017-12-22 16:02:54 -08004253 if (IsUnifiedPlan()) {
4254 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4255 } else {
4256 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4257 }
4258
Steve Antonfa2260d2017-12-28 16:38:23 -08004259 // Intentionally unset the data channel type for RTP data channel with the
4260 // second condition. Otherwise the RTP data channels would be successfully
4261 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4262 // when building with chromium. We want to leave RTP data channels broken, so
4263 // people won't try to use them.
4264 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4265 session_options->data_channel_type = data_channel_type();
4266 }
4267
Steve Antondcc3c022017-12-22 16:02:54 -08004268 // Apply ICE restart flag and renomination flag.
4269 for (auto& options : session_options->media_description_options) {
4270 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4271 options.transport_options.enable_ice_renomination =
4272 configuration_.enable_ice_renomination;
4273 }
4274
4275 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004276 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004277 session_options->pooled_ice_credentials =
4278 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4279 RTC_FROM_HERE,
4280 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4281 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004282 session_options->offer_extmap_allow_mixed =
4283 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004284
4285 if (configuration_.enable_dtls_srtp &&
4286 !configuration_.enable_dtls_srtp.value()) {
4287 session_options->media_transport_settings =
4288 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4289 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004290 // Allow fallback for using obsolete SCTP syntax.
4291 // Note that the default in |session_options| is true, while
4292 // the default in |options| is false.
4293 session_options->use_obsolete_sctp_sdp =
4294 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004295}
4296
4297void PeerConnection::GetOptionsForPlanBOffer(
4298 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4299 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004300 // Figure out transceiver directional preferences.
4301 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4302 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4303
4304 // By default, generate sendrecv/recvonly m= sections.
4305 bool recv_audio = true;
4306 bool recv_video = true;
4307
4308 // By default, only offer a new m= section if we have media to send with it.
4309 bool offer_new_audio_description = send_audio;
4310 bool offer_new_video_description = send_video;
4311 bool offer_new_data_description = HasDataChannels();
4312
4313 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004314 if (offer_answer_options.offer_to_receive_audio !=
4315 RTCOfferAnswerOptions::kUndefined) {
4316 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004317 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004318 offer_new_audio_description ||
4319 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004320 }
Steve Antondcc3c022017-12-22 16:02:54 -08004321 if (offer_answer_options.offer_to_receive_video !=
4322 RTCOfferAnswerOptions::kUndefined) {
4323 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004324 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004325 offer_new_video_description ||
4326 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004327 }
4328
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004329 absl::optional<size_t> audio_index;
4330 absl::optional<size_t> video_index;
4331 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004332 // If a current description exists, generate m= sections in the same order,
4333 // using the first audio/video/data section that appears and rejecting
4334 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004335 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004336 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004337 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004338 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4339 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4340 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004341 }
4342
zhihuang1c378ed2017-08-17 14:10:50 -07004343 // Add audio/video/data m= sections to the end if needed.
4344 if (!audio_index && offer_new_audio_description) {
4345 session_options->media_description_options.push_back(
4346 cricket::MediaDescriptionOptions(
4347 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004348 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4349 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004350 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004351 }
zhihuang1c378ed2017-08-17 14:10:50 -07004352 if (!video_index && offer_new_video_description) {
4353 session_options->media_description_options.push_back(
4354 cricket::MediaDescriptionOptions(
4355 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004356 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4357 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004358 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004359 }
zhihuang1c378ed2017-08-17 14:10:50 -07004360 if (!data_index && offer_new_data_description) {
4361 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004362 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004363 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004364 }
4365
4366 cricket::MediaDescriptionOptions* audio_media_description_options =
4367 !audio_index ? nullptr
4368 : &session_options->media_description_options[*audio_index];
4369 cricket::MediaDescriptionOptions* video_media_description_options =
4370 !video_index ? nullptr
4371 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004372
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004373 AddPlanBRtpSenderOptions(GetSendersInternal(),
4374 audio_media_description_options,
4375 video_media_description_options,
4376 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004377}
4378
Steve Antondcc3c022017-12-22 16:02:54 -08004379static cricket::MediaDescriptionOptions
4380GetMediaDescriptionOptionsForTransceiver(
4381 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4382 transceiver,
4383 const std::string& mid) {
4384 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004385 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004386 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004387 media_description_options.codec_preferences =
4388 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004389 // This behavior is specified in JSEP. The gist is that:
4390 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4391 // sendrecv.
4392 // 2. If the MSID is included, then it must be included in any subsequent
4393 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004394 if (transceiver->stopped() ||
4395 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4396 !transceiver->internal()->has_ever_been_used_to_send())) {
4397 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004398 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004399
4400 cricket::SenderOptions sender_options;
4401 sender_options.track_id = transceiver->sender()->id();
4402 sender_options.stream_ids = transceiver->sender()->stream_ids();
4403
4404 // The following sets up RIDs and Simulcast.
4405 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004406 RtpParameters send_parameters =
4407 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004408 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4409 send_parameters.encodings.end(),
4410 [](const RtpEncodingParameters& encoding) {
4411 return !encoding.rid.empty();
4412 });
4413
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004414 std::vector<RidDescription> send_rids;
4415 SimulcastLayerList send_layers;
4416 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4417 if (encoding.rid.empty()) {
4418 continue;
4419 }
4420 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4421 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4422 }
4423
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004424 if (has_rids) {
4425 sender_options.rids = send_rids;
4426 }
4427
4428 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004429 // When RIDs are configured, we must set num_sim_layers to 0 to.
4430 // Otherwise, num_sim_layers must be 1 because either there is no
4431 // simulcast, or simulcast is acheived by munging the SDP.
4432 sender_options.num_sim_layers = has_rids ? 0 : 1;
4433 media_description_options.sender_options.push_back(sender_options);
4434
Steve Antondcc3c022017-12-22 16:02:54 -08004435 return media_description_options;
4436}
4437
Steve Anton5c72e712018-12-10 14:25:30 -08004438// Returns the ContentInfo at mline index |i|, or null if none exists.
4439static const ContentInfo* GetContentByIndex(
4440 const SessionDescriptionInterface* sdesc,
4441 size_t i) {
4442 if (!sdesc) {
4443 return nullptr;
4444 }
4445 const ContentInfos& contents = sdesc->description()->contents();
4446 return (i < contents.size() ? &contents[i] : nullptr);
4447}
4448
Steve Antondcc3c022017-12-22 16:02:54 -08004449void PeerConnection::GetOptionsForUnifiedPlanOffer(
4450 const RTCOfferAnswerOptions& offer_answer_options,
4451 cricket::MediaSessionOptions* session_options) {
4452 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4453 // Offers) and 5.2.2 (Subsequent Offers).
4454 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4455 const ContentInfos& local_contents =
4456 (local_description() ? local_description()->description()->contents()
4457 : ContentInfos());
4458 const ContentInfos& remote_contents =
4459 (remote_description() ? remote_description()->description()->contents()
4460 : ContentInfos());
4461 // The mline indices that can be recycled. New transceivers should reuse these
4462 // slots first.
4463 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004464 // First, go through each media section that exists in either the local or
4465 // remote description and generate a media section in this offer for the
4466 // associated transceiver. If a media section can be recycled, generate a
4467 // default, rejected media section here that can be later overwritten.
4468 for (size_t i = 0;
4469 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4470 // Either |local_content| or |remote_content| is non-null.
4471 const ContentInfo* local_content =
4472 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004473 const ContentInfo* current_local_content =
4474 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004475 const ContentInfo* remote_content =
4476 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004477 const ContentInfo* current_remote_content =
4478 GetContentByIndex(current_remote_description(), i);
4479 bool had_been_rejected =
4480 (current_local_content && current_local_content->rejected) ||
4481 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004482 const std::string& mid =
4483 (local_content ? local_content->name : remote_content->name);
4484 cricket::MediaType media_type =
4485 (local_content ? local_content->media_description()->type()
4486 : remote_content->media_description()->type());
4487 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4488 media_type == cricket::MEDIA_TYPE_VIDEO) {
4489 auto transceiver = GetAssociatedTransceiver(mid);
4490 RTC_CHECK(transceiver);
4491 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004492 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004493 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004494 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004495 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4496 RtpTransceiverDirection::kInactive,
4497 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004498 recycleable_mline_indices.push(i);
4499 } else {
4500 session_options->media_description_options.push_back(
4501 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4502 // CreateOffer shouldn't really cause any state changes in
4503 // PeerConnection, but we need a way to match new transceivers to new
4504 // media sections in SetLocalDescription and JSEP specifies this is done
4505 // by recording the index of the media section generated for the
4506 // transceiver in the offer.
4507 transceiver->internal()->set_mline_index(i);
4508 }
4509 } else {
4510 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004511 RTC_CHECK(GetDataMid());
4512 if (had_been_rejected || mid != *GetDataMid()) {
4513 session_options->media_description_options.push_back(
4514 GetMediaDescriptionOptionsForRejectedData(mid));
4515 } else {
4516 session_options->media_description_options.push_back(
4517 GetMediaDescriptionOptionsForActiveData(mid));
4518 }
Steve Antondcc3c022017-12-22 16:02:54 -08004519 }
4520 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004521
Steve Antondcc3c022017-12-22 16:02:54 -08004522 // Next, look for transceivers that are newly added (that is, are not stopped
4523 // and not associated). Reuse media sections marked as recyclable first,
4524 // otherwise append to the end of the offer. New media sections should be
4525 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004526 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004527 if (transceiver->mid() || transceiver->stopped()) {
4528 continue;
4529 }
4530 size_t mline_index;
4531 if (!recycleable_mline_indices.empty()) {
4532 mline_index = recycleable_mline_indices.front();
4533 recycleable_mline_indices.pop();
4534 session_options->media_description_options[mline_index] =
4535 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004536 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004537 } else {
4538 mline_index = session_options->media_description_options.size();
4539 session_options->media_description_options.push_back(
4540 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004541 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004542 }
4543 // See comment above for why CreateOffer changes the transceiver's state.
4544 transceiver->internal()->set_mline_index(mline_index);
4545 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004546 // Lastly, add a m-section if we have local data channels and an m section
4547 // does not already exist.
4548 if (!GetDataMid() && HasDataChannels()) {
4549 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004550 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004551 }
Steve Antondcc3c022017-12-22 16:02:54 -08004552}
4553
4554void PeerConnection::GetOptionsForAnswer(
4555 const RTCOfferAnswerOptions& offer_answer_options,
4556 cricket::MediaSessionOptions* session_options) {
4557 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4558
4559 if (IsUnifiedPlan()) {
4560 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4561 } else {
4562 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4563 }
4564
Steve Antonfa2260d2017-12-28 16:38:23 -08004565 // Intentionally unset the data channel type for RTP data channel. Otherwise
4566 // the RTP data channels would be successfully negotiated by default and the
4567 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4568 // We want to leave RTP data channels broken, so people won't try to use them.
4569 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4570 session_options->data_channel_type = data_channel_type();
4571 }
4572
Steve Antondcc3c022017-12-22 16:02:54 -08004573 // Apply ICE renomination flag.
4574 for (auto& options : session_options->media_description_options) {
4575 options.transport_options.enable_ice_renomination =
4576 configuration_.enable_ice_renomination;
4577 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004578
4579 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004580 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004581 session_options->pooled_ice_credentials =
4582 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4583 RTC_FROM_HERE,
4584 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4585 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004586}
4587
Steve Antondcc3c022017-12-22 16:02:54 -08004588void PeerConnection::GetOptionsForPlanBAnswer(
4589 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004590 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004591 // Figure out transceiver directional preferences.
4592 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4593 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4594
4595 // By default, generate sendrecv/recvonly m= sections. The direction is also
4596 // restricted by the direction in the offer.
4597 bool recv_audio = true;
4598 bool recv_video = true;
4599
4600 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004601 if (offer_answer_options.offer_to_receive_audio !=
4602 RTCOfferAnswerOptions::kUndefined) {
4603 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004604 }
Steve Antondcc3c022017-12-22 16:02:54 -08004605 if (offer_answer_options.offer_to_receive_video !=
4606 RTCOfferAnswerOptions::kUndefined) {
4607 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004608 }
4609
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004610 absl::optional<size_t> audio_index;
4611 absl::optional<size_t> video_index;
4612 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004613
4614 // Generate m= sections that match those in the offer.
4615 // Note that mediasession.cc will handle intersection our preferred
4616 // direction with the offered direction.
4617 GenerateMediaDescriptionOptions(
4618 remote_description(),
4619 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4620 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4621 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004622
4623 cricket::MediaDescriptionOptions* audio_media_description_options =
4624 !audio_index ? nullptr
4625 : &session_options->media_description_options[*audio_index];
4626 cricket::MediaDescriptionOptions* video_media_description_options =
4627 !video_index ? nullptr
4628 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004629
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004630 AddPlanBRtpSenderOptions(GetSendersInternal(),
4631 audio_media_description_options,
4632 video_media_description_options,
4633 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004634}
zhihuangaf388472016-11-02 16:49:48 -07004635
Steve Antondcc3c022017-12-22 16:02:54 -08004636void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4637 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4638 cricket::MediaSessionOptions* session_options) {
4639 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4640 // Answers) and 5.3.2 (Subsequent Answers).
4641 RTC_DCHECK(remote_description());
4642 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4643 for (const ContentInfo& content :
4644 remote_description()->description()->contents()) {
4645 cricket::MediaType media_type = content.media_description()->type();
4646 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4647 media_type == cricket::MEDIA_TYPE_VIDEO) {
4648 auto transceiver = GetAssociatedTransceiver(content.name);
4649 RTC_CHECK(transceiver);
4650 session_options->media_description_options.push_back(
4651 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4652 } else {
4653 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004654 // Reject all data sections if data channels are disabled.
4655 // Reject a data section if it has already been rejected.
4656 // Reject all data sections except for the first one.
4657 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4658 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004659 session_options->media_description_options.push_back(
4660 GetMediaDescriptionOptionsForRejectedData(content.name));
4661 } else {
4662 session_options->media_description_options.push_back(
4663 GetMediaDescriptionOptionsForActiveData(content.name));
4664 }
Steve Antondcc3c022017-12-22 16:02:54 -08004665 }
4666 }
htaa2a49d92016-03-04 02:51:39 -08004667}
4668
zhihuang1c378ed2017-08-17 14:10:50 -07004669void PeerConnection::GenerateMediaDescriptionOptions(
4670 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004671 RtpTransceiverDirection audio_direction,
4672 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004673 absl::optional<size_t>* audio_index,
4674 absl::optional<size_t>* video_index,
4675 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004676 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004677 for (const cricket::ContentInfo& content :
4678 session_desc->description()->contents()) {
4679 if (IsAudioContent(&content)) {
4680 // If we already have an audio m= section, reject this extra one.
4681 if (*audio_index) {
4682 session_options->media_description_options.push_back(
4683 cricket::MediaDescriptionOptions(
4684 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004685 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004686 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004687 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004688 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004689 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4690 content.name, audio_direction,
4691 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004692 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004693 }
4694 } else if (IsVideoContent(&content)) {
4695 // If we already have an video m= section, reject this extra one.
4696 if (*video_index) {
4697 session_options->media_description_options.push_back(
4698 cricket::MediaDescriptionOptions(
4699 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004700 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004701 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004702 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004703 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004704 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4705 content.name, video_direction,
4706 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004707 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004708 }
4709 } else {
4710 RTC_DCHECK(IsDataContent(&content));
4711 // If we already have an data m= section, reject this extra one.
4712 if (*data_index) {
4713 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004714 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004715 } else {
4716 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004717 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004718 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004719 }
4720 }
htaa2a49d92016-03-04 02:51:39 -08004721 }
deadbeefab9b2d12015-10-14 11:33:11 -07004722}
4723
Steve Antonfa2260d2017-12-28 16:38:23 -08004724cricket::MediaDescriptionOptions
4725PeerConnection::GetMediaDescriptionOptionsForActiveData(
4726 const std::string& mid) const {
4727 // Direction for data sections is meaningless, but legacy endpoints might
4728 // expect sendrecv.
4729 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4730 RtpTransceiverDirection::kSendRecv,
4731 /*stopped=*/false);
4732 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4733 return options;
4734}
4735
4736cricket::MediaDescriptionOptions
4737PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4738 const std::string& mid) const {
4739 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4740 RtpTransceiverDirection::kInactive,
4741 /*stopped=*/true);
4742 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4743 return options;
4744}
4745
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004746absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004747 switch (data_channel_type_) {
4748 case cricket::DCT_RTP:
4749 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004750 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004751 }
4752 return rtp_data_channel_->content_name();
4753 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004754 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004755 case cricket::DCT_MEDIA_TRANSPORT:
4756 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004757 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004758 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004759 }
4760}
4761
Steve Anton4171afb2017-11-20 10:20:22 -08004762void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4763 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4764 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004765 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004766}
4767
Steve Anton4171afb2017-11-20 10:20:22 -08004768void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004769 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004770 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004771 cricket::MediaType media_type,
4772 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004773 RTC_DCHECK(!IsUnifiedPlan());
4774
Steve Anton4171afb2017-11-20 10:20:22 -08004775 std::vector<RtpSenderInfo>* current_senders =
4776 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004777
Steve Anton4171afb2017-11-20 10:20:22 -08004778 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004779 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004780 for (auto sender_it = current_senders->begin();
4781 sender_it != current_senders->end();
4782 /* incremented manually */) {
4783 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004784 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004785 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004786 std::string params_stream_id;
4787 if (params) {
4788 params_stream_id =
4789 (!params->first_stream_id().empty() ? params->first_stream_id()
4790 : kDefaultStreamId);
4791 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004792 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004793 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004794 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004795 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004796 sender_exists) {
4797 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004798 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004799 OnRemoteSenderRemoved(info, media_type);
4800 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004801 }
4802 }
4803
Steve Anton4171afb2017-11-20 10:20:22 -08004804 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004805 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004806 if (!params.has_ssrcs()) {
4807 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4808 // sender, this means it is coming from a Unified Plan endpoint,so we just
4809 // create a default.
4810 default_sender_needed = true;
4811 break;
4812 }
4813
Seth Hampson845e8782018-03-02 11:34:10 -08004814 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004815 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004816 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4817 // not supported in Plan B, we just take the first here and create the
4818 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004819 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004820 (!params.first_stream_id().empty() ? params.first_stream_id()
4821 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004822 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004823 uint32_t ssrc = params.first_ssrc();
4824
4825 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004826 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004827 if (!stream) {
4828 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004829 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004830 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004831 remote_streams_->AddStream(stream);
4832 new_streams->AddStream(stream);
4833 }
4834
Steve Anton4171afb2017-11-20 10:20:22 -08004835 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004836 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004837 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004838 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004839 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004840 }
4841 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004842
Steve Anton4171afb2017-11-20 10:20:22 -08004843 // Add default sender if necessary.
4844 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004845 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004846 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004847 if (!default_stream) {
4848 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004849 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004850 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004851 remote_streams_->AddStream(default_stream);
4852 new_streams->AddStream(default_stream);
4853 }
Steve Anton4171afb2017-11-20 10:20:22 -08004854 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4855 ? kDefaultAudioSenderId
4856 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004857 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004858 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004859 if (!default_sender_info) {
4860 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004861 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004862 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004863 }
4864 }
deadbeefab9b2d12015-10-14 11:33:11 -07004865}
4866
Steve Anton4171afb2017-11-20 10:20:22 -08004867void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4868 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004869 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4870 << " receiver for track_id=" << sender_info.sender_id
4871 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004872
Steve Anton3d954a62018-04-02 11:27:23 -07004873 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004875 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004876 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004877 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004878 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004879 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004880 }
4881}
4882
Steve Anton4171afb2017-11-20 10:20:22 -08004883void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4884 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004885 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4886 << " receiver for track_id=" << sender_info.sender_id
4887 << " and stream_id=" << sender_info.stream_id;
4888
Seth Hampson845e8782018-03-02 11:34:10 -08004889 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004890
Henrik Boström933d8b02017-10-10 10:05:16 -07004891 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004892 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004893 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4894 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004895 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004896 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004897 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004898 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004899 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004900 }
4901 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004902 // Stopping or destroying a VideoRtpReceiver will end the
4903 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004904 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004905 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004906 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004907 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004908 // There's no guarantee the track is still available, e.g. the track may
4909 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004910 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004911 }
4912 } else {
nisseede5da42017-01-12 05:15:36 -08004913 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004914 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004915 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004916 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004917 }
deadbeefab9b2d12015-10-14 11:33:11 -07004918}
4919
4920void PeerConnection::UpdateEndedRemoteMediaStreams() {
4921 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4922 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4923 MediaStreamInterface* stream = remote_streams_->at(i);
4924 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4925 streams_to_remove.push_back(stream);
4926 }
4927 }
4928
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004929 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004930 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004931 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004932 }
4933}
4934
Steve Anton4171afb2017-11-20 10:20:22 -08004935void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004936 const std::vector<cricket::StreamParams>& streams,
4937 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004938 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004939
Seth Hampson845e8782018-03-02 11:34:10 -08004940 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004941 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004942 for (auto sender_it = current_senders->begin();
4943 sender_it != current_senders->end();
4944 /* incremented manually */) {
4945 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004946 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004947 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4948 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004949 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004950 OnLocalSenderRemoved(info, media_type);
4951 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004952 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004953 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004954 }
4955 }
4956
Steve Anton4171afb2017-11-20 10:20:22 -08004957 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004958 for (const cricket::StreamParams& params : streams) {
4959 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004960 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004961 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004962 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004963 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004964 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004965 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004966 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004967 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004968 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004969 }
4970 }
4971}
4972
Steve Anton4171afb2017-11-20 10:20:22 -08004973void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4974 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004975 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004976 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004977 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004978 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4979 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004980 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004981 return;
4982 }
4983
deadbeeffac06552015-11-25 11:26:01 -08004984 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004985 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004986 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004987 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004988 }
deadbeeffac06552015-11-25 11:26:01 -08004989
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004990 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004991 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004992}
4993
Steve Anton4171afb2017-11-20 10:20:22 -08004994void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4995 cricket::MediaType media_type) {
4996 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004997 if (!sender) {
4998 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004999 // SessionDescriptions has been renegotiated.
5000 return;
5001 }
deadbeeffac06552015-11-25 11:26:01 -08005002
5003 // A sender has been removed from the SessionDescription but it's still
5004 // associated with the PeerConnection. This only occurs if the SDP doesn't
5005 // match with the calls to CreateSender, AddStream and RemoveStream.
5006 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005007 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005008 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005009 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005010 }
deadbeeffac06552015-11-25 11:26:01 -08005011
Steve Anton4171afb2017-11-20 10:20:22 -08005012 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005013}
5014
5015void PeerConnection::UpdateLocalRtpDataChannels(
5016 const cricket::StreamParamsVec& streams) {
5017 std::vector<std::string> existing_channels;
5018
5019 // Find new and active data channels.
5020 for (const cricket::StreamParams& params : streams) {
5021 // |it->sync_label| is actually the data channel label. The reason is that
5022 // we use the same naming of data channels as we do for
5023 // MediaStreams and Tracks.
5024 // For MediaStreams, the sync_label is the MediaStream label and the
5025 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005026 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005027 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005028 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005029 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005030 continue;
5031 }
5032 // Set the SSRC the data channel should use for sending.
5033 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5034 existing_channels.push_back(data_channel_it->first);
5035 }
5036
5037 UpdateClosingRtpDataChannels(existing_channels, true);
5038}
5039
5040void PeerConnection::UpdateRemoteRtpDataChannels(
5041 const cricket::StreamParamsVec& streams) {
5042 std::vector<std::string> existing_channels;
5043
5044 // Find new and active data channels.
5045 for (const cricket::StreamParams& params : streams) {
5046 // The data channel label is either the mslabel or the SSRC if the mslabel
5047 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005048 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005049 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005050 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005051 auto data_channel_it = rtp_data_channels_.find(label);
5052 if (data_channel_it == rtp_data_channels_.end()) {
5053 // This is a new data channel.
5054 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5055 } else {
5056 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5057 }
5058 existing_channels.push_back(label);
5059 }
5060
5061 UpdateClosingRtpDataChannels(existing_channels, false);
5062}
5063
5064void PeerConnection::UpdateClosingRtpDataChannels(
5065 const std::vector<std::string>& active_channels,
5066 bool is_local_update) {
5067 auto it = rtp_data_channels_.begin();
5068 while (it != rtp_data_channels_.end()) {
5069 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005070 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005071 ++it;
5072 continue;
5073 }
5074
5075 if (is_local_update) {
5076 data_channel->SetSendSsrc(0);
5077 } else {
5078 data_channel->RemotePeerRequestClose();
5079 }
5080
5081 if (data_channel->state() == DataChannel::kClosed) {
5082 rtp_data_channels_.erase(it);
5083 it = rtp_data_channels_.begin();
5084 } else {
5085 ++it;
5086 }
5087 }
5088}
5089
5090void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5091 uint32_t remote_ssrc) {
5092 rtc::scoped_refptr<DataChannel> channel(
5093 InternalCreateDataChannel(label, nullptr));
5094 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005095 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005096 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005097 return;
5098 }
5099 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005100 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5101 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005102 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005103}
5104
5105rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5106 const std::string& label,
5107 const InternalDataChannelInit* config) {
5108 if (IsClosed()) {
5109 return nullptr;
5110 }
Steve Anton75737c02017-11-06 10:37:17 -08005111 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005113 << "InternalCreateDataChannel: Data is not supported in this call.";
5114 return nullptr;
5115 }
5116 InternalDataChannelInit new_config =
5117 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005118 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005119 if (new_config.id < 0) {
5120 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005121 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005122 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005123 RTC_LOG(LS_ERROR)
5124 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005125 return nullptr;
5126 }
5127 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005128 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005129 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005130 return nullptr;
5131 }
5132 }
5133
Steve Anton75737c02017-11-06 10:37:17 -08005134 rtc::scoped_refptr<DataChannel> channel(
5135 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005136 if (!channel) {
5137 sid_allocator_.ReleaseSid(new_config.id);
5138 return nullptr;
5139 }
5140
5141 if (channel->data_channel_type() == cricket::DCT_RTP) {
5142 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005143 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5144 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005145 return nullptr;
5146 }
5147 rtp_data_channels_[channel->label()] = channel;
5148 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005149 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005150 sctp_data_channels_.push_back(channel);
5151 channel->SignalClosed.connect(this,
5152 &PeerConnection::OnSctpDataChannelClosed);
5153 }
5154
Steve Anton2d8609c2018-01-23 16:38:46 -08005155 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005156 return channel;
5157}
5158
5159bool PeerConnection::HasDataChannels() const {
5160 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5161}
5162
5163void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005164 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005165 for (const auto& channel : sctp_data_channels_) {
5166 if (channel->id() < 0) {
5167 int sid;
5168 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005169 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5170 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005171 continue;
5172 }
5173 channel->SetSctpSid(sid);
5174 }
5175 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005176 // Since closing modifies the list of channels, we have to do the actual
5177 // closing outside the loop.
5178 for (const auto& channel : channels_to_close) {
5179 channel->CloseAbruptly();
5180 }
deadbeefab9b2d12015-10-14 11:33:11 -07005181}
5182
5183void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005184 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005185 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5186 ++it) {
5187 if (it->get() == channel) {
5188 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005189 // After the closing procedure is done, it's safe to use this ID for
5190 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005191 sid_allocator_.ReleaseSid(channel->id());
5192 }
deadbeefbd292462015-12-14 18:15:29 -08005193 // Since this method is triggered by a signal from the DataChannel,
5194 // we can't free it directly here; we need to free it asynchronously.
5195 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005196 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005197 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5198 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005199 return;
5200 }
5201 }
5202}
5203
deadbeefab9b2d12015-10-14 11:33:11 -07005204void PeerConnection::OnDataChannelDestroyed() {
5205 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5206 // DataChannel may callback to us and try to modify the list.
5207 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5208 temp_rtp_dcs.swap(rtp_data_channels_);
5209 for (const auto& kv : temp_rtp_dcs) {
5210 kv.second->OnTransportChannelDestroyed();
5211 }
5212
5213 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5214 temp_sctp_dcs.swap(sctp_data_channels_);
5215 for (const auto& channel : temp_sctp_dcs) {
5216 channel->OnTransportChannelDestroyed();
5217 }
5218}
5219
5220void PeerConnection::OnDataChannelOpenMessage(
5221 const std::string& label,
5222 const InternalDataChannelInit& config) {
5223 rtc::scoped_refptr<DataChannel> channel(
5224 InternalCreateDataChannel(label, &config));
5225 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005226 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005227 return;
5228 }
5229
deadbeefa601f5c2016-06-06 14:27:39 -07005230 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5231 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005232 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005233 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005234}
5235
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005236bool PeerConnection::HandleOpenMessage_s(
5237 const cricket::ReceiveDataParams& params,
5238 const rtc::CopyOnWriteBuffer& buffer) {
5239 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5240 // Received OPEN message; parse and signal that a new data channel should
5241 // be created.
5242 std::string label;
5243 InternalDataChannelInit config;
5244 config.id = params.ssrc;
5245 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5246 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5247 << params.ssrc;
5248 return true;
5249 }
5250 config.open_handshake_role = InternalDataChannelInit::kAcker;
5251 OnDataChannelOpenMessage(label, config);
5252 return true;
5253 }
5254 return false;
5255}
5256
Steve Anton4171afb2017-11-20 10:20:22 -08005257rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5258PeerConnection::GetAudioTransceiver() const {
5259 // This method only works with Plan B SDP, where there is a single
5260 // audio/video transceiver.
5261 RTC_DCHECK(!IsUnifiedPlan());
5262 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005263 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005264 return transceiver;
5265 }
5266 }
5267 RTC_NOTREACHED();
5268 return nullptr;
5269}
5270
5271rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5272PeerConnection::GetVideoTransceiver() const {
5273 // This method only works with Plan B SDP, where there is a single
5274 // audio/video transceiver.
5275 RTC_DCHECK(!IsUnifiedPlan());
5276 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005277 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005278 return transceiver;
5279 }
5280 }
5281 RTC_NOTREACHED();
5282 return nullptr;
5283}
5284
5285// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5286// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005287bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005288 switch (type) {
5289 case cricket::MEDIA_TYPE_AUDIO:
5290 return !GetAudioTransceiver()->internal()->senders().empty();
5291 case cricket::MEDIA_TYPE_VIDEO:
5292 return !GetVideoTransceiver()->internal()->senders().empty();
5293 case cricket::MEDIA_TYPE_DATA:
5294 return false;
5295 }
5296 RTC_NOTREACHED();
5297 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005298}
5299
Steve Anton4171afb2017-11-20 10:20:22 -08005300rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5301PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005302 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005303 for (auto sender : transceiver->internal()->senders()) {
5304 if (sender->track() == track) {
5305 return sender;
5306 }
5307 }
5308 }
5309 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005310}
5311
Steve Anton4171afb2017-11-20 10:20:22 -08005312rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5313PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005314 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005315 for (auto sender : transceiver->internal()->senders()) {
5316 if (sender->id() == sender_id) {
5317 return sender;
5318 }
5319 }
5320 }
5321 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005322}
5323
Steve Anton4171afb2017-11-20 10:20:22 -08005324rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5325PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005326 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005327 for (auto receiver : transceiver->internal()->receivers()) {
5328 if (receiver->id() == receiver_id) {
5329 return receiver;
5330 }
5331 }
5332 }
5333 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005334}
5335
Steve Anton4171afb2017-11-20 10:20:22 -08005336std::vector<PeerConnection::RtpSenderInfo>*
5337PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5338 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5339 media_type == cricket::MEDIA_TYPE_VIDEO);
5340 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5341 ? &remote_audio_sender_infos_
5342 : &remote_video_sender_infos_;
5343}
5344
5345std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005346 cricket::MediaType media_type) {
5347 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5348 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005349 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5350 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005351}
5352
Steve Anton4171afb2017-11-20 10:20:22 -08005353const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5354 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005355 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005356 const std::string sender_id) const {
5357 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005358 if (sender_info.stream_id == stream_id &&
5359 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005360 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005361 }
5362 }
5363 return nullptr;
5364}
5365
5366DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5367 for (const auto& channel : sctp_data_channels_) {
5368 if (channel->id() == sid) {
5369 return channel;
5370 }
5371 }
5372 return nullptr;
5373}
5374
Karl Wibergfb3be392019-03-22 14:13:22 +01005375PeerConnection::InitializePortAllocatorResult
5376PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005377 const cricket::ServerAddresses& stun_servers,
5378 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005379 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005380 RTC_DCHECK_RUN_ON(network_thread());
5381
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005382 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005383 // To handle both internal and externally created port allocator, we will
5384 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005385 int port_allocator_flags = port_allocator_->flags();
5386 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5387 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5388 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005389 // If the disable-IPv6 flag was specified, we'll not override it
5390 // by experiment.
5391 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005392 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005393 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5394 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005395 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005396 }
5397
zhihuangb09b3f92017-03-07 14:40:51 -08005398 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005399 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005400 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005401 }
5402
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005404 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005405 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005406 }
5407
honghaiz60347052016-05-31 18:29:12 -07005408 if (configuration.candidate_network_policy ==
5409 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005410 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005411 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005412 }
5413
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005414 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005415 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005416 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5417 }
5418
Karl Wibergfb3be392019-03-22 14:13:22 +01005419 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005420 // No step delay is used while allocating ports.
5421 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005422 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005424 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005425
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005426 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005427 for (auto& turn_server : turn_servers_copy) {
5428 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005429 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005430 // Call this last since it may create pooled allocator sessions using the
5431 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005432 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005433 stun_servers, std::move(turn_servers_copy),
5434 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5435 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005436 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005437
5438 InitializePortAllocatorResult res;
5439 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5440 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005441}
5442
deadbeef91dd5672016-05-18 16:55:30 -07005443bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005444 const cricket::ServerAddresses& stun_servers,
5445 const std::vector<cricket::RelayServerConfig>& turn_servers,
5446 IceTransportsType type,
5447 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005448 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005449 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005450 absl::optional<int> stun_candidate_keepalive_interval,
5451 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005452 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005453 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005454 // According to JSEP, after setLocalDescription, changing the candidate pool
5455 // size is not allowed, and changing the set of ICE servers will not result
5456 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005457 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005458 port_allocator_->FreezeCandidatePool();
5459 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005460 // Add the custom tls turn servers if they exist.
5461 auto turn_servers_copy = turn_servers;
5462 for (auto& turn_server : turn_servers_copy) {
5463 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5464 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005465 // Call this last since it may create pooled allocator sessions using the
5466 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005467 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005468 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5469 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005470}
5471
Steve Antonba818672017-11-06 10:21:57 -08005472cricket::ChannelManager* PeerConnection::channel_manager() const {
5473 return factory_->channel_manager();
5474}
5475
Elad Alon99c3fe52017-10-13 16:29:40 +02005476bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005477 std::unique_ptr<RtcEventLogOutput> output,
5478 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005479 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005480 if (!event_log_) {
5481 return false;
5482 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005483 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005484}
5485
5486void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005487 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005488 if (event_log_) {
5489 event_log_->StopLogging();
5490 }
ivoc14d5dbe2016-07-04 07:06:55 -07005491}
nisseeaabdf62017-05-05 02:23:02 -07005492
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005493cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005494 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005495 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005496 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005497 if (channel && channel->content_name() == content_name) {
5498 return channel;
5499 }
Steve Anton75737c02017-11-06 10:37:17 -08005500 }
5501 if (rtp_data_channel() &&
5502 rtp_data_channel()->content_name() == content_name) {
5503 return rtp_data_channel();
5504 }
5505 return nullptr;
5506}
5507
5508bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005509 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005510 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005511 RTC_LOG(LS_INFO)
5512 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005513 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005514 return false;
5515 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005516 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005517 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005518 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005519 return false;
5520 }
5521
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005522 absl::optional<rtc::SSLRole> dtls_role;
5523 if (sctp_mid_) {
5524 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5525 } else if (is_caller_) {
5526 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5527 }
Zhi Huange830e682018-03-30 10:48:35 -07005528 if (dtls_role) {
5529 *role = *dtls_role;
5530 return true;
5531 }
5532 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005533}
5534
5535bool PeerConnection::GetSslRole(const std::string& content_name,
5536 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005537 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005538 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005539 RTC_LOG(LS_INFO)
5540 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005541 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005542 return false;
5543 }
5544
Zhi Huange830e682018-03-30 10:48:35 -07005545 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5546 if (dtls_role) {
5547 *role = *dtls_role;
5548 return true;
5549 }
5550 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005551}
5552
Steve Antonf8470812017-12-04 10:46:21 -08005553void PeerConnection::SetSessionError(SessionError error,
5554 const std::string& error_desc) {
5555 RTC_DCHECK_RUN_ON(signaling_thread());
5556 if (error != session_error_) {
5557 session_error_ = error;
5558 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005559 }
5560}
5561
Zhi Huange830e682018-03-30 10:48:35 -07005562RTCError PeerConnection::UpdateSessionState(
5563 SdpType type,
5564 cricket::ContentSource source,
5565 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005566 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005567
5568 // If there's already a pending error then no state transition should happen.
5569 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005570 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005571
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005572 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005573 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005574 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005575 }
5576
5577 // Update the signaling state according to the specified state machine (see
5578 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005579 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005580 ChangeSignalingState(source == cricket::CS_LOCAL
5581 ? PeerConnectionInterface::kHaveLocalOffer
5582 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005583 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005584 ChangeSignalingState(source == cricket::CS_LOCAL
5585 ? PeerConnectionInterface::kHaveLocalPrAnswer
5586 : PeerConnectionInterface::kHaveRemotePrAnswer);
5587 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005588 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005589 ChangeSignalingState(PeerConnectionInterface::kStable);
5590 }
5591
5592 // Update internal objects according to the session description's media
5593 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005594 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005595 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005596 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005597 }
5598
Steve Anton8a006912017-12-04 15:25:56 -08005599 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005600}
5601
Steve Anton8a006912017-12-04 15:25:56 -08005602RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005603 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005604 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005605 const SessionDescriptionInterface* sdesc =
5606 (source == cricket::CS_LOCAL ? local_description()
5607 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005608 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005609
5610 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005611 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005612 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005613 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005614 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005615 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005616 continue;
5617 }
5618 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005619 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005620 if (!content_desc) {
5621 continue;
5622 }
5623 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005624 bool success = (source == cricket::CS_LOCAL)
5625 ? channel->SetLocalContent(content_desc, type, &error)
5626 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005627 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005629 }
5630 }
5631
5632 // If using the RtpDataChannel, push down the new SDP section for it too.
5633 if (rtp_data_channel_) {
5634 const ContentInfo* data_content =
5635 cricket::GetFirstDataContent(sdesc->description());
5636 if (data_content && !data_content->rejected) {
5637 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005638 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005639 if (data_desc) {
5640 std::string error;
5641 bool success =
5642 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005643 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005644 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005645 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005647 }
Steve Anton75737c02017-11-06 10:37:17 -08005648 }
5649 }
5650 }
Steve Antoned10bd92017-12-05 10:52:59 -08005651
Steve Anton75737c02017-11-06 10:37:17 -08005652 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5653 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005654 if (sctp_transport_ && local_description() && remote_description()) {
5655 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5656 local_description()->description());
5657 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5658 remote_description()->description());
5659 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005660 int max_message_size;
5661 // A remote max message size of zero means "any size supported".
5662 // We configure the connection with our own max message size.
5663 if (remote_sctp_description->max_message_size() == 0) {
5664 max_message_size = local_sctp_description->max_message_size();
5665 } else {
5666 max_message_size =
5667 std::min(local_sctp_description->max_message_size(),
5668 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005669 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005670 sctp_transport_->Start(local_sctp_description->port(),
5671 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005672 }
Steve Anton75737c02017-11-06 10:37:17 -08005673 }
Steve Antoned10bd92017-12-05 10:52:59 -08005674
Steve Anton8a006912017-12-04 15:25:56 -08005675 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005676}
5677
Steve Anton8a006912017-12-04 15:25:56 -08005678RTCError PeerConnection::PushdownTransportDescription(
5679 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005680 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005681 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005682
Zhi Huange830e682018-03-30 10:48:35 -07005683 if (source == cricket::CS_LOCAL) {
5684 const SessionDescriptionInterface* sdesc = local_description();
5685 RTC_DCHECK(sdesc);
5686 return transport_controller_->SetLocalDescription(type,
5687 sdesc->description());
5688 } else {
5689 const SessionDescriptionInterface* sdesc = remote_description();
5690 RTC_DCHECK(sdesc);
5691 return transport_controller_->SetRemoteDescription(type,
5692 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005693 }
Steve Anton75737c02017-11-06 10:37:17 -08005694}
5695
5696bool PeerConnection::GetTransportDescription(
5697 const SessionDescription* description,
5698 const std::string& content_name,
5699 cricket::TransportDescription* tdesc) {
5700 if (!description || !tdesc) {
5701 return false;
5702 }
5703 const TransportInfo* transport_info =
5704 description->GetTransportInfoByName(content_name);
5705 if (!transport_info) {
5706 return false;
5707 }
5708 *tdesc = transport_info->description;
5709 return true;
5710}
5711
Steve Anton75737c02017-11-06 10:37:17 -08005712cricket::IceConfig PeerConnection::ParseIceConfig(
5713 const PeerConnectionInterface::RTCConfiguration& config) const {
5714 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005715 switch (config.continual_gathering_policy) {
5716 case PeerConnectionInterface::GATHER_ONCE:
5717 gathering_policy = cricket::GATHER_ONCE;
5718 break;
5719 case PeerConnectionInterface::GATHER_CONTINUALLY:
5720 gathering_policy = cricket::GATHER_CONTINUALLY;
5721 break;
5722 default:
5723 RTC_NOTREACHED();
5724 gathering_policy = cricket::GATHER_ONCE;
5725 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005726
Steve Anton75737c02017-11-06 10:37:17 -08005727 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005728 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5729 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005730 ice_config.prioritize_most_likely_candidate_pairs =
5731 config.prioritize_most_likely_ice_candidate_pairs;
5732 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005733 RTCConfigurationToIceConfigOptionalInt(
5734 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005735 ice_config.continual_gathering_policy = gathering_policy;
5736 ice_config.presume_writable_when_fully_relayed =
5737 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005738 ice_config.ice_check_interval_strong_connectivity =
5739 config.ice_check_interval_strong_connectivity;
5740 ice_config.ice_check_interval_weak_connectivity =
5741 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005742 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005743 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5744 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005745 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005746 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005747 ice_config.regather_all_networks_interval_range =
5748 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005749 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005750 return ice_config;
5751}
5752
Steve Anton75737c02017-11-06 10:37:17 -08005753bool PeerConnection::SendData(const cricket::SendDataParams& params,
5754 const rtc::CopyOnWriteBuffer& payload,
5755 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005756 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005757 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5758 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5759 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005760 return false;
5761 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005762 if (media_transport_) {
5763 SendDataParams send_params;
5764 send_params.type = ToWebrtcDataMessageType(params.type);
5765 send_params.ordered = params.ordered;
5766 if (params.max_rtx_count >= 0) {
5767 send_params.max_rtx_count = params.max_rtx_count;
5768 } else if (params.max_rtx_ms >= 0) {
5769 send_params.max_rtx_ms = params.max_rtx_ms;
5770 }
5771 return media_transport_->SendData(params.sid, send_params, payload).ok();
5772 }
Steve Anton75737c02017-11-06 10:37:17 -08005773 return rtp_data_channel_
5774 ? rtp_data_channel_->SendData(params, payload, result)
5775 : network_thread()->Invoke<bool>(
5776 RTC_FROM_HERE,
5777 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005778 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005779}
5780
5781bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005782 RTC_DCHECK_RUN_ON(signaling_thread());
5783 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005784 // Don't log an error here, because DataChannels are expected to call
5785 // ConnectDataChannel in this state. It's the only way to initially tell
5786 // whether or not the underlying transport is ready.
5787 return false;
5788 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005789 if (media_transport_) {
5790 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5791 &DataChannel::OnChannelReady);
5792 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5793 &DataChannel::OnDataReceived);
5794 SignalMediaTransportChannelClosing_s.connect(
5795 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5796 SignalMediaTransportChannelClosed_s.connect(
5797 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5798 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005799 rtp_data_channel_->SignalReadyToSendData.connect(
5800 webrtc_data_channel, &DataChannel::OnChannelReady);
5801 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5802 &DataChannel::OnDataReceived);
5803 } else {
5804 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5805 &DataChannel::OnChannelReady);
5806 SignalSctpDataReceived.connect(webrtc_data_channel,
5807 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005808 SignalSctpClosingProcedureStartedRemotely.connect(
5809 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5810 SignalSctpClosingProcedureComplete.connect(
5811 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005812 }
5813 return true;
5814}
5815
5816void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005817 RTC_DCHECK_RUN_ON(signaling_thread());
5818 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005819 RTC_LOG(LS_ERROR)
5820 << "DisconnectDataChannel called when rtp_data_channel_ and "
5821 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005822 return;
5823 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005824 if (media_transport_) {
5825 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5826 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5827 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5828 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5829 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005830 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5831 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5832 } else {
5833 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5834 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005835 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5836 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005837 }
5838}
5839
5840void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005841 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005842 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005843 return;
5844 }
Steve Anton75737c02017-11-06 10:37:17 -08005845 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005846 RTC_LOG(LS_ERROR)
5847 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005848 return;
5849 }
5850 network_thread()->Invoke<void>(
5851 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005852 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005853}
5854
5855void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005856 if (media_transport_) {
5857 media_transport_->CloseChannel(sid);
5858 return;
5859 }
Steve Anton75737c02017-11-06 10:37:17 -08005860 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005861 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005862 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005863 return;
5864 }
5865 network_thread()->Invoke<void>(
5866 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005867 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005868}
5869
5870bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005871 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005872 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005873 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005874 sctp_ready_to_send_data_;
5875}
5876
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005877void PeerConnection::OnDataReceived(int channel_id,
5878 DataMessageType type,
5879 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005880 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005881 cricket::ReceiveDataParams params;
5882 params.sid = channel_id;
5883 params.type = ToCricketDataMessageType(type);
5884 media_transport_invoker_->AsyncInvoke<void>(
5885 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5886 RTC_DCHECK_RUN_ON(signaling_thread());
5887 if (!HandleOpenMessage_s(params, buffer)) {
5888 SignalMediaTransportReceivedData_s(params, buffer);
5889 }
5890 });
5891}
5892
5893void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005894 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005895 media_transport_invoker_->AsyncInvoke<void>(
5896 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5897 RTC_DCHECK_RUN_ON(signaling_thread());
5898 SignalMediaTransportChannelClosing_s(channel_id);
5899 });
5900}
5901
5902void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005903 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005904 media_transport_invoker_->AsyncInvoke<void>(
5905 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5906 RTC_DCHECK_RUN_ON(signaling_thread());
5907 SignalMediaTransportChannelClosed_s(channel_id);
5908 });
5909}
5910
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005911absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005912 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005913 if (sctp_mid_ && transport_controller_) {
5914 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5915 if (dtls_transport) {
5916 return dtls_transport->transport_name();
5917 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005918 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005919 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005920 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005921}
5922
Qingsi Wang72a43a12018-02-20 16:03:18 -08005923cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5924 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005925 network_thread()->Invoke<void>(
5926 RTC_FROM_HERE,
5927 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5928 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005929 return candidate_states_list;
5930}
5931
Steve Anton5dfde182018-02-06 10:34:40 -08005932std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5933 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005934 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005935 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005936 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005937 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005938 if (channel) {
5939 transport_names_by_mid[channel->content_name()] =
5940 channel->transport_name();
5941 }
Steve Anton75737c02017-11-06 10:37:17 -08005942 }
Steve Anton5dfde182018-02-06 10:34:40 -08005943 if (rtp_data_channel_) {
5944 transport_names_by_mid[rtp_data_channel_->content_name()] =
5945 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005946 }
5947 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005948 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005949 RTC_DCHECK(transport_name);
5950 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005951 }
Steve Anton5dfde182018-02-06 10:34:40 -08005952 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005953}
5954
Steve Anton5dfde182018-02-06 10:34:40 -08005955std::map<std::string, cricket::TransportStats>
5956PeerConnection::GetTransportStatsByNames(
5957 const std::set<std::string>& transport_names) {
5958 if (!network_thread()->IsCurrent()) {
5959 return network_thread()
5960 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5961 RTC_FROM_HERE,
5962 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005963 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005964 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005965 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5966 for (const std::string& transport_name : transport_names) {
5967 cricket::TransportStats transport_stats;
5968 bool success =
5969 transport_controller_->GetStats(transport_name, &transport_stats);
5970 if (success) {
5971 transport_stats_by_name[transport_name] = std::move(transport_stats);
5972 } else {
5973 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5974 << transport_name;
5975 }
5976 }
5977 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005978}
5979
5980bool PeerConnection::GetLocalCertificate(
5981 const std::string& transport_name,
5982 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005983 if (!certificate) {
5984 return false;
5985 }
5986 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5987 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005988}
5989
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005990std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005991 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005992 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005993}
5994
5995cricket::DataChannelType PeerConnection::data_channel_type() const {
5996 return data_channel_type_;
5997}
5998
5999bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006000 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006001 return pending_ice_restarts_.find(content_name) !=
6002 pending_ice_restarts_.end();
6003}
6004
Steve Anton75737c02017-11-06 10:37:17 -08006005bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6006 return transport_controller_->NeedsIceRestart(content_name);
6007}
6008
6009void PeerConnection::OnCertificateReady(
6010 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6011 transport_controller_->SetLocalCertificate(certificate);
6012}
6013
6014void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006015 SetSessionError(SessionError::kTransport,
6016 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006017}
6018
Alex Loiko9289eda2018-11-23 16:18:59 +00006019void PeerConnection::OnTransportControllerConnectionState(
6020 cricket::IceConnectionState state) {
6021 switch (state) {
6022 case cricket::kIceConnectionConnecting:
6023 // If the current state is Connected or Completed, then there were
6024 // writable channels but now there are not, so the next state must
6025 // be Disconnected.
6026 // kIceConnectionConnecting is currently used as the default,
6027 // un-connected state by the TransportController, so its only use is
6028 // detecting disconnections.
6029 if (ice_connection_state_ ==
6030 PeerConnectionInterface::kIceConnectionConnected ||
6031 ice_connection_state_ ==
6032 PeerConnectionInterface::kIceConnectionCompleted) {
6033 SetIceConnectionState(
6034 PeerConnectionInterface::kIceConnectionDisconnected);
6035 }
6036 break;
6037 case cricket::kIceConnectionFailed:
6038 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6039 break;
6040 case cricket::kIceConnectionConnected:
6041 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6042 "all transports are writable.";
6043 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6044 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6045 break;
6046 case cricket::kIceConnectionCompleted:
6047 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6048 "all transports are complete.";
6049 if (ice_connection_state_ !=
6050 PeerConnectionInterface::kIceConnectionConnected) {
6051 // If jumping directly from "checking" to "connected",
6052 // signal "connected" first.
6053 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6054 }
6055 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6056 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6057 ReportTransportStats();
6058 break;
6059 default:
6060 RTC_NOTREACHED();
6061 }
6062}
6063
Steve Anton75737c02017-11-06 10:37:17 -08006064void PeerConnection::OnTransportControllerCandidatesGathered(
6065 const std::string& transport_name,
6066 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006067 int sdp_mline_index;
6068 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006069 RTC_LOG(LS_ERROR)
6070 << "OnTransportControllerCandidatesGathered: content name "
6071 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006072 return;
6073 }
6074
6075 for (cricket::Candidates::const_iterator citer = candidates.begin();
6076 citer != candidates.end(); ++citer) {
6077 // Use transport_name as the candidate media id.
6078 std::unique_ptr<JsepIceCandidate> candidate(
6079 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6080 if (local_description()) {
6081 mutable_local_description()->AddCandidate(candidate.get());
6082 }
6083 OnIceCandidate(std::move(candidate));
6084 }
6085}
6086
6087void PeerConnection::OnTransportControllerCandidatesRemoved(
6088 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006089 // Sanity check.
6090 for (const cricket::Candidate& candidate : candidates) {
6091 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006092 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006093 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006094 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006095 return;
6096 }
6097 }
6098
6099 if (local_description()) {
6100 mutable_local_description()->RemoveCandidates(candidates);
6101 }
6102 OnIceCandidatesRemoved(candidates);
6103}
6104
6105void PeerConnection::OnTransportControllerDtlsHandshakeError(
6106 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006107 RTC_HISTOGRAM_ENUMERATION(
6108 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6109 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006110}
6111
Steve Antoned10bd92017-12-05 10:52:59 -08006112void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006113 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006114 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006115 if (channel && !channel->enabled()) {
6116 channel->Enable(true);
6117 }
Steve Anton75737c02017-11-06 10:37:17 -08006118 }
6119
Steve Anton4171afb2017-11-20 10:20:22 -08006120 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006121 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006122 }
Steve Anton75737c02017-11-06 10:37:17 -08006123}
6124
6125// Returns the media index for a local ice candidate given the content name.
6126bool PeerConnection::GetLocalCandidateMediaIndex(
6127 const std::string& content_name,
6128 int* sdp_mline_index) {
6129 if (!local_description() || !sdp_mline_index) {
6130 return false;
6131 }
6132
6133 bool content_found = false;
6134 const ContentInfos& contents = local_description()->description()->contents();
6135 for (size_t index = 0; index < contents.size(); ++index) {
6136 if (contents[index].name == content_name) {
6137 *sdp_mline_index = static_cast<int>(index);
6138 content_found = true;
6139 break;
6140 }
6141 }
6142 return content_found;
6143}
6144
6145bool PeerConnection::UseCandidatesInSessionDescription(
6146 const SessionDescriptionInterface* remote_desc) {
6147 if (!remote_desc) {
6148 return true;
6149 }
6150 bool ret = true;
6151
6152 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6153 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6154 for (size_t n = 0; n < candidates->count(); ++n) {
6155 const IceCandidateInterface* candidate = candidates->at(n);
6156 bool valid = false;
6157 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6158 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006159 RTC_LOG(LS_INFO)
6160 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006161 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
6163 continue;
6164 }
6165 ret = UseCandidate(candidate);
6166 if (!ret) {
6167 break;
6168 }
6169 }
6170 }
6171 return ret;
6172}
6173
6174bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6175 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6176 size_t remote_content_size =
6177 remote_description()->description()->contents().size();
6178 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006179 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006180 return false;
6181 }
6182
6183 cricket::ContentInfo content =
6184 remote_description()->description()->contents()[mediacontent_index];
6185 std::vector<cricket::Candidate> candidates;
6186 candidates.push_back(candidate->candidate());
6187 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006188 RTCError error =
6189 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006190 if (error.ok()) {
6191 // Candidates successfully submitted for checking.
6192 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6193 ice_connection_state_ ==
6194 PeerConnectionInterface::kIceConnectionDisconnected) {
6195 // If state is New, then the session has just gotten its first remote ICE
6196 // candidates, so go to Checking.
6197 // If state is Disconnected, the session is re-using old candidates or
6198 // receiving additional ones, so go to Checking.
6199 // If state is Connected, stay Connected.
6200 // TODO(bemasc): If state is Connected, and the new candidates are for a
6201 // newly added transport, then the state actually _should_ move to
6202 // checking. Add a way to distinguish that case.
6203 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6204 }
6205 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006206 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006207 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006208 }
6209 return true;
6210}
6211
6212void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006213 // Destroy video channel first since it may have a pointer to the
6214 // voice channel.
6215 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006216 if (!video_info || video_info->rejected) {
6217 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006218 }
6219
Steve Anton6fec8802017-12-04 10:37:29 -08006220 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6221 if (!audio_info || audio_info->rejected) {
6222 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006223 }
6224
6225 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6226 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006227 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006228 }
6229}
6230
Steve Antondcc3c022017-12-22 16:02:54 -08006231RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6232 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006233 const cricket::ContentGroup* bundle_group = nullptr;
6234 if (configuration_.bundle_policy ==
6235 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006236 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006237 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006238 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6239 "max-bundle configured but session description "
6240 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006241 }
6242 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006243 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006244}
6245
6246RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006247 // Creating the media channels. Transports should already have been created
6248 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006249 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006250 if (voice && !voice->rejected &&
6251 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006252 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006253 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006254 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6255 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006256 }
6257 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6258 }
6259
Steve Antondcc3c022017-12-22 16:02:54 -08006260 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006261 if (video && !video->rejected &&
6262 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006263 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006264 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006265 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6266 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006267 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006268 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006269 }
6270
Steve Antondcc3c022017-12-22 16:02:54 -08006271 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006272 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006273 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006274 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006275 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6276 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006277 }
6278 }
6279
Steve Anton8a006912017-12-04 15:25:56 -08006280 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006281}
6282
Steve Anton4171afb2017-11-20 10:20:22 -08006283// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006284cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006285 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006286 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006287 MediaTransportInterface* media_transport = nullptr;
6288 if (configuration_.use_media_transport) {
6289 media_transport = GetMediaTransport(mid);
6290 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006291
Steve Anton75737c02017-11-06 10:37:17 -08006292 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006293 call_ptr_, configuration_.media_config, rtp_transport,
6294 MediaTransportConfig(media_transport), signaling_thread(), mid,
6295 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006296 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006297 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006298 }
Steve Anton75737c02017-11-06 10:37:17 -08006299 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6300 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006301 voice_channel->SignalSentPacket.connect(this,
6302 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006303 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006304
Steve Antoneda6ccd2017-12-04 10:21:55 -08006305 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006306}
6307
Steve Anton4171afb2017-11-20 10:20:22 -08006308// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006309cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006310 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006311 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006312 MediaTransportInterface* media_transport = nullptr;
6313 if (configuration_.use_media_transport) {
6314 media_transport = GetMediaTransport(mid);
6315 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006316
Steve Anton75737c02017-11-06 10:37:17 -08006317 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006318 call_ptr_, configuration_.media_config, rtp_transport,
6319 MediaTransportConfig(media_transport), signaling_thread(), mid,
6320 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_, video_options_,
6321 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006322 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006323 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006324 }
Steve Anton75737c02017-11-06 10:37:17 -08006325 video_channel->SignalDtlsSrtpSetupFailure.connect(
6326 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006327 video_channel->SignalSentPacket.connect(this,
6328 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006329 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006330
Steve Antoneda6ccd2017-12-04 10:21:55 -08006331 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006332}
6333
Zhi Huange830e682018-03-30 10:48:35 -07006334bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006335 switch (data_channel_type_) {
6336 case cricket::DCT_MEDIA_TRANSPORT:
6337 if (network_thread()->Invoke<bool>(
6338 RTC_FROM_HERE,
6339 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6340 this, mid))) {
6341 for (const auto& channel : sctp_data_channels_) {
6342 channel->OnTransportChannelCreated();
6343 }
6344 return true;
6345 }
Steve Anton75737c02017-11-06 10:37:17 -08006346 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006347 case cricket::DCT_SCTP:
6348 if (!sctp_factory_) {
6349 RTC_LOG(LS_ERROR)
6350 << "Trying to create SCTP transport, but didn't compile with "
6351 "SCTP support (HAVE_SCTP)";
6352 return false;
6353 }
6354 if (!network_thread()->Invoke<bool>(
6355 RTC_FROM_HERE,
6356 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6357 return false;
6358 }
6359 for (const auto& channel : sctp_data_channels_) {
6360 channel->OnTransportChannelCreated();
6361 }
6362 return true;
6363 case cricket::DCT_RTP:
6364 default:
6365 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6366 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6367 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006368 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006369 if (!rtp_data_channel_) {
6370 return false;
6371 }
6372 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6373 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6374 rtp_data_channel_->SignalSentPacket.connect(
6375 this, &PeerConnection::OnSentPacket_w);
6376 rtp_data_channel_->SetRtpTransport(rtp_transport);
6377 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006378 }
6379
Steve Anton75737c02017-11-06 10:37:17 -08006380 return true;
6381}
6382
6383Call::Stats PeerConnection::GetCallStats() {
6384 if (!worker_thread()->IsCurrent()) {
6385 return worker_thread()->Invoke<Call::Stats>(
6386 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6387 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006388 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006389 if (call_) {
6390 return call_->GetStats();
6391 } else {
6392 return Call::Stats();
6393 }
6394}
6395
Zhi Huange830e682018-03-30 10:48:35 -07006396bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006397 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006398 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006399 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6400 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006401 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006402 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006403 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006404 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6405 sctp_factory_->CreateSctpTransport(dtls_transport);
6406 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006407 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006408 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006409 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006410 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006411 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006412 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6413 // another thread. Would be nice if there was a helper class similar to
6414 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6415 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006416 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006417 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006418 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006419 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006420 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006421 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6422 std::move(cricket_sctp_transport));
6423 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006424 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006425}
6426
6427void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006428 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006429 sctp_transport_->Clear();
6430 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006431 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006432 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006433}
6434
6435void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006436 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006437 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006438 // Note: Cannot use rtc::Bind here because it will grab a reference to
6439 // PeerConnection and potentially cause PeerConnection to live longer than
6440 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6441 // be destroyed before PeerConnection is destroyed, and at that point all
6442 // pending tasks will be cleared.
6443 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6444 OnSctpTransportReadyToSendData_s(true);
6445 });
6446}
6447
6448void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006449 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006450 sctp_ready_to_send_data_ = ready;
6451 SignalSctpReadyToSendData(ready);
6452}
6453
6454void PeerConnection::OnSctpTransportDataReceived_n(
6455 const cricket::ReceiveDataParams& params,
6456 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006457 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006458 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006459 // Note: Cannot use rtc::Bind here because it will grab a reference to
6460 // PeerConnection and potentially cause PeerConnection to live longer than
6461 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6462 // be destroyed before PeerConnection is destroyed, and at that point all
6463 // pending tasks will be cleared.
6464 sctp_invoker_->AsyncInvoke<void>(
6465 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6466 OnSctpTransportDataReceived_s(params, payload);
6467 });
6468}
6469
6470void PeerConnection::OnSctpTransportDataReceived_s(
6471 const cricket::ReceiveDataParams& params,
6472 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006473 RTC_DCHECK_RUN_ON(signaling_thread());
6474 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006475 SignalSctpDataReceived(params, payload);
6476 }
6477}
6478
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006479void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006480 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006481 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006482 sctp_invoker_->AsyncInvoke<void>(
6483 RTC_FROM_HERE, signaling_thread(),
6484 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006485 &SignalSctpClosingProcedureStartedRemotely, sid));
6486}
6487
6488void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006489 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006490 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006491 sctp_invoker_->AsyncInvoke<void>(
6492 RTC_FROM_HERE, signaling_thread(),
6493 rtc::Bind(&sigslot::signal1<int>::operator(),
6494 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006495}
6496
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006497bool PeerConnection::SetupMediaTransportForDataChannels_n(
6498 const std::string& mid) {
6499 media_transport_ = transport_controller_->GetMediaTransport(mid);
6500 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006501 RTC_LOG(LS_ERROR)
6502 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006503 return false;
6504 }
6505
6506 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6507 media_transport_->SetDataSink(this);
6508 media_transport_data_mid_ = mid;
6509 transport_controller_->SignalMediaTransportStateChanged.connect(
6510 this, &PeerConnection::OnMediaTransportStateChanged_n);
6511 // Check the initial state right away, in case transport is already writable.
6512 OnMediaTransportStateChanged_n();
6513 return true;
6514}
6515
6516void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6517 if (!media_transport_) {
6518 return;
6519 }
6520 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6521 media_transport_data_mid_.reset();
6522 media_transport_->SetDataSink(nullptr);
6523 media_transport_invoker_ = nullptr;
6524 media_transport_ = nullptr;
6525}
6526
6527void PeerConnection::OnMediaTransportStateChanged_n() {
6528 if (!media_transport_data_mid_ ||
6529 transport_controller_->GetMediaTransportState(
6530 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6531 return;
6532 }
6533 media_transport_invoker_->AsyncInvoke<void>(
6534 RTC_FROM_HERE, signaling_thread(), [this] {
6535 RTC_DCHECK_RUN_ON(signaling_thread());
6536 media_transport_ready_to_send_data_ = true;
6537 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6538 });
6539}
6540
Steve Anton75737c02017-11-06 10:37:17 -08006541// Returns false if bundle is enabled and rtcp_mux is disabled.
6542bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6543 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6544 if (!bundle_enabled)
6545 return true;
6546
6547 const cricket::ContentGroup* bundle_group =
6548 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6549 RTC_DCHECK(bundle_group != NULL);
6550
6551 const cricket::ContentInfos& contents = desc->contents();
6552 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6553 citer != contents.end(); ++citer) {
6554 const cricket::ContentInfo* content = (&*citer);
6555 RTC_DCHECK(content != NULL);
6556 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006557 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006558 if (!HasRtcpMuxEnabled(content))
6559 return false;
6560 }
6561 }
6562 // RTCP-MUX is enabled in all the contents.
6563 return true;
6564}
6565
6566bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006567 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006568}
6569
Steve Anton06817cd2018-12-18 15:55:30 -08006570static RTCError ValidateMids(const cricket::SessionDescription& description) {
6571 std::set<std::string> mids;
6572 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006573 if (content.name.empty()) {
6574 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6575 "A media section is missing a MID attribute.");
6576 }
Steve Anton06817cd2018-12-18 15:55:30 -08006577 if (!mids.insert(content.name).second) {
6578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6579 "Duplicate a=mid value '" + content.name + "'.");
6580 }
6581 }
6582 return RTCError::OK();
6583}
6584
Steve Anton8a006912017-12-04 15:25:56 -08006585RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006586 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006587 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006588 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006589 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006590 }
6591
6592 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006593 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006594 }
6595
Steve Anton3828c062017-12-06 10:34:51 -08006596 SdpType type = sdesc->GetType();
6597 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6598 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006599 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006600 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006601 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603
Steve Anton06817cd2018-12-18 15:55:30 -08006604 RTCError error = ValidateMids(*sdesc->description());
6605 if (!error.ok()) {
6606 return error;
6607 }
6608
Steve Anton75737c02017-11-06 10:37:17 -08006609 // Verify crypto settings.
6610 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006611 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6612 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006613 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006614 if (!crypto_error.ok()) {
6615 return crypto_error;
6616 }
Steve Anton75737c02017-11-06 10:37:17 -08006617 }
6618
6619 // Verify ice-ufrag and ice-pwd.
6620 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006621 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6622 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006623 }
6624
6625 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006626 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6627 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006628 }
6629
6630 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6631 // m-lines that do not rtcp-mux enabled.
6632
6633 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006634 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006635 // With an answer we want to compare the new answer session description with
6636 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006637 const cricket::SessionDescription* offer_desc =
6638 (source == cricket::CS_LOCAL) ? remote_description()->description()
6639 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006640 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6641 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6642 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6644 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006645 }
6646 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006647 // The re-offers should respect the order of m= sections in current
6648 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006649 // With a re-offer, either the current local or current remote descriptions
6650 // could be the most up to date, so we would like to check against both of
6651 // them if they exist. It could be the case that one of them has a 0 port
6652 // for a media section, but the other does not. This is important to check
6653 // against in the case that we are recycling an m= section.
6654 const cricket::SessionDescription* current_desc = nullptr;
6655 const cricket::SessionDescription* secondary_current_desc = nullptr;
6656 if (local_description()) {
6657 current_desc = local_description()->description();
6658 if (remote_description()) {
6659 secondary_current_desc = remote_description()->description();
6660 }
6661 } else if (remote_description()) {
6662 current_desc = remote_description()->description();
6663 }
Steve Anton75737c02017-11-06 10:37:17 -08006664 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006665 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6666 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006667 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6668 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006669 }
6670 }
6671
Steve Antonba42e992018-04-09 14:10:01 -07006672 if (IsUnifiedPlan()) {
6673 // Ensure that each audio and video media section has at most one
6674 // "StreamParams". This will return an error if receiving a session
6675 // description from a "Plan B" endpoint which adds multiple tracks of the
6676 // same type. With Unified Plan, there can only be at most one track per
6677 // media section.
6678 for (const ContentInfo& content : sdesc->description()->contents()) {
6679 const MediaContentDescription& desc = *content.description;
6680 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6681 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6682 desc.streams().size() > 1u) {
6683 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6684 "Media section has more than one track specified "
6685 "with a=ssrc lines which is not supported with "
6686 "Unified Plan.");
6687 }
6688 }
6689 }
6690
Steve Anton8a006912017-12-04 15:25:56 -08006691 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006692}
6693
Steve Anton3828c062017-12-06 10:34:51 -08006694bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006695 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006696 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006697 return (state == PeerConnectionInterface::kStable) ||
6698 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006699 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006700 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006701 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6702 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6703 }
6704}
6705
Steve Anton3828c062017-12-06 10:34:51 -08006706bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006707 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006708 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006709 return (state == PeerConnectionInterface::kStable) ||
6710 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006711 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006712 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006713 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6714 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6715 }
6716}
6717
Steve Antonf8470812017-12-04 10:46:21 -08006718const char* PeerConnection::SessionErrorToString(SessionError error) const {
6719 switch (error) {
6720 case SessionError::kNone:
6721 return "ERROR_NONE";
6722 case SessionError::kContent:
6723 return "ERROR_CONTENT";
6724 case SessionError::kTransport:
6725 return "ERROR_TRANSPORT";
6726 }
6727 RTC_NOTREACHED();
6728 return "";
6729}
6730
Steve Anton75737c02017-11-06 10:37:17 -08006731std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006732 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006733 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6734 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006735 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006736}
6737
Steve Anton8e20f172018-03-06 10:55:04 -08006738void PeerConnection::ReportSdpFormatReceived(
6739 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006740 int num_audio_mlines = 0;
6741 int num_video_mlines = 0;
6742 int num_audio_tracks = 0;
6743 int num_video_tracks = 0;
6744 for (const ContentInfo& content : remote_offer.description()->contents()) {
6745 cricket::MediaType media_type = content.media_description()->type();
6746 int num_tracks = std::max(
6747 1, static_cast<int>(content.media_description()->streams().size()));
6748 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6749 num_audio_mlines += 1;
6750 num_audio_tracks += num_tracks;
6751 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6752 num_video_mlines += 1;
6753 num_video_tracks += num_tracks;
6754 }
6755 }
6756 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6757 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6758 format = kSdpFormatReceivedComplexUnifiedPlan;
6759 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6760 format = kSdpFormatReceivedComplexPlanB;
6761 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6762 format = kSdpFormatReceivedSimple;
6763 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006764 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6765 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006766}
6767
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006768void PeerConnection::NoteUsageEvent(UsageEvent event) {
6769 RTC_DCHECK_RUN_ON(signaling_thread());
6770 usage_event_accumulator_ |= static_cast<int>(event);
6771}
6772
6773void PeerConnection::ReportUsagePattern() const {
6774 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006775 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6776 usage_event_accumulator_,
6777 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006778 const int bad_bits =
6779 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6780 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6781 const int good_bits =
6782 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6783 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6784 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6785 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6786 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006787 // If called after close(), we can't report, because observer may have
6788 // been deallocated, and therefore pointer is null. Write to log instead.
6789 if (observer_) {
6790 Observer()->OnInterestingUsage(usage_event_accumulator_);
6791 } else {
6792 RTC_LOG(LS_INFO) << "Interesting usage signature "
6793 << usage_event_accumulator_
6794 << " observed after observer shutdown";
6795 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006796 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006797}
6798
Steve Anton0ffaaa22018-02-23 10:31:30 -08006799void PeerConnection::ReportNegotiatedSdpSemantics(
6800 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006801 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006802 switch (answer.description()->msid_signaling()) {
6803 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006804 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006805 break;
6806 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006807 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006808 break;
6809 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006810 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006811 break;
6812 case cricket::kMsidSignalingMediaSection |
6813 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006814 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006815 break;
6816 default:
6817 RTC_NOTREACHED();
6818 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006819 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6820 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006821}
6822
Steve Anton75737c02017-11-06 10:37:17 -08006823// We need to check the local/remote description for the Transport instead of
6824// the session, because a new Transport added during renegotiation may have
6825// them unset while the session has them set from the previous negotiation.
6826// Not doing so may trigger the auto generation of transport description and
6827// mess up DTLS identity information, ICE credential, etc.
6828bool PeerConnection::ReadyToUseRemoteCandidate(
6829 const IceCandidateInterface* candidate,
6830 const SessionDescriptionInterface* remote_desc,
6831 bool* valid) {
6832 *valid = true;
6833
6834 const SessionDescriptionInterface* current_remote_desc =
6835 remote_desc ? remote_desc : remote_description();
6836
6837 if (!current_remote_desc) {
6838 return false;
6839 }
6840
6841 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6842 size_t remote_content_size =
6843 current_remote_desc->description()->contents().size();
6844 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006845 RTC_LOG(LS_ERROR)
6846 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6847 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006848
6849 *valid = false;
6850 return false;
6851 }
6852
6853 cricket::ContentInfo content =
6854 current_remote_desc->description()->contents()[mediacontent_index];
6855
6856 const std::string transport_name = GetTransportName(content.name);
6857 if (transport_name.empty()) {
6858 return false;
6859 }
Zhi Huange830e682018-03-30 10:48:35 -07006860 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006861}
6862
6863bool PeerConnection::SrtpRequired() const {
6864 return dtls_enabled_ ||
6865 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6866}
6867
6868void PeerConnection::OnTransportControllerGatheringState(
6869 cricket::IceGatheringState state) {
6870 RTC_DCHECK(signaling_thread()->IsCurrent());
6871 if (state == cricket::kIceGatheringGathering) {
6872 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6873 } else if (state == cricket::kIceGatheringComplete) {
6874 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6875 }
6876}
6877
6878void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006879 std::map<std::string, std::set<cricket::MediaType>>
6880 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006881 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006882 if (transceiver->internal()->channel()) {
6883 const std::string& transport_name =
6884 transceiver->internal()->channel()->transport_name();
6885 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006886 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006887 }
Steve Anton75737c02017-11-06 10:37:17 -08006888 }
6889 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006890 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6891 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006892 }
Zhi Huange830e682018-03-30 10:48:35 -07006893
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006894 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006895 if (transport_name) {
6896 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006897 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006898 }
Zhi Huange830e682018-03-30 10:48:35 -07006899
Steve Antonc7b964c2018-02-01 14:39:45 -08006900 for (const auto& entry : media_types_by_transport_name) {
6901 const std::string& transport_name = entry.first;
6902 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006903 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006904 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006905 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006906 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006907 }
6908 }
6909}
6910// Walk through the ConnectionInfos to gather best connection usage
6911// for IPv4 and IPv6.
6912void PeerConnection::ReportBestConnectionState(
6913 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006914 for (const cricket::TransportChannelStats& channel_stats :
6915 stats.channel_stats) {
6916 for (const cricket::ConnectionInfo& connection_info :
6917 channel_stats.connection_infos) {
6918 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006919 continue;
6920 }
6921
Steve Antonc7b964c2018-02-01 14:39:45 -08006922 const cricket::Candidate& local = connection_info.local_candidate;
6923 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006924
6925 // Increment the counter for IceCandidatePairType.
6926 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6927 (local.type() == RELAY_PORT_TYPE &&
6928 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006929 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6930 GetIceCandidatePairCounter(local, remote),
6931 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006932 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006933 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6934 GetIceCandidatePairCounter(local, remote),
6935 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006936 } else {
6937 RTC_CHECK(0);
6938 }
Steve Anton75737c02017-11-06 10:37:17 -08006939
6940 // Increment the counter for IP type.
6941 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006942 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6943 kBestConnections_IPv4,
6944 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006945 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006946 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6947 kBestConnections_IPv6,
6948 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006949 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006950 RTC_CHECK(!local.address().hostname().empty() &&
6951 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006952 }
6953
6954 return;
6955 }
6956 }
6957}
6958
6959void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006960 const cricket::TransportStats& stats,
6961 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006962 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6963 return;
6964 }
6965
6966 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6967 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6968 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6969 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6970 return;
6971 }
6972
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006973 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6974 for (cricket::MediaType media_type : media_types) {
6975 switch (media_type) {
6976 case cricket::MEDIA_TYPE_AUDIO:
6977 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6978 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6979 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6980 break;
6981 case cricket::MEDIA_TYPE_VIDEO:
6982 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6983 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6984 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6985 break;
6986 case cricket::MEDIA_TYPE_DATA:
6987 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6988 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6989 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6990 break;
6991 default:
6992 RTC_NOTREACHED();
6993 continue;
6994 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006995 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006996 }
6997
6998 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6999 for (cricket::MediaType media_type : media_types) {
7000 switch (media_type) {
7001 case cricket::MEDIA_TYPE_AUDIO:
7002 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7003 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7004 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7005 break;
7006 case cricket::MEDIA_TYPE_VIDEO:
7007 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7008 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7009 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7010 break;
7011 case cricket::MEDIA_TYPE_DATA:
7012 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7013 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7014 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7015 break;
7016 default:
7017 RTC_NOTREACHED();
7018 continue;
7019 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007020 }
Steve Anton75737c02017-11-06 10:37:17 -08007021 }
7022}
7023
7024void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007025 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007026 RTC_DCHECK(call_);
7027 call_->OnSentPacket(sent_packet);
7028}
7029
7030const std::string PeerConnection::GetTransportName(
7031 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007032 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007033 if (channel) {
7034 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007035 }
Steve Anton6fec8802017-12-04 10:37:29 -08007036 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007037 RTC_DCHECK(sctp_mid_);
7038 if (content_name == *sctp_mid_) {
7039 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007040 }
7041 }
7042 // Return an empty string if failed to retrieve the transport name.
7043 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007044}
7045
Steve Anton6fec8802017-12-04 10:37:29 -08007046void PeerConnection::DestroyTransceiverChannel(
7047 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7048 transceiver) {
7049 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007050
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007051 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007052 if (channel) {
7053 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007054 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007055 }
7056}
7057
7058void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007059 if (rtp_data_channel_) {
7060 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007061 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007062 rtp_data_channel_ = nullptr;
7063 }
7064
7065 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7066 // grab a reference to this PeerConnection. If this is called from the
7067 // PeerConnection destructor, the RefCountedObject vtable will have already
7068 // been destroyed (since it is a subclass of PeerConnection) and using
7069 // rtc::Bind will cause "Pure virtual function called" error to appear.
7070
7071 if (sctp_transport_) {
7072 OnDataChannelDestroyed();
7073 network_thread()->Invoke<void>(RTC_FROM_HERE,
7074 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007075 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007076 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007077
7078 if (media_transport_) {
7079 OnDataChannelDestroyed();
7080 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7081 RTC_DCHECK_RUN_ON(network_thread());
7082 TeardownMediaTransportForDataChannels_n();
7083 });
7084 }
Steve Anton6fec8802017-12-04 10:37:29 -08007085}
7086
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007087void PeerConnection::DestroyChannelInterface(
7088 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007089 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007090 switch (channel->media_type()) {
7091 case cricket::MEDIA_TYPE_AUDIO:
7092 channel_manager()->DestroyVoiceChannel(
7093 static_cast<cricket::VoiceChannel*>(channel));
7094 break;
7095 case cricket::MEDIA_TYPE_VIDEO:
7096 channel_manager()->DestroyVideoChannel(
7097 static_cast<cricket::VideoChannel*>(channel));
7098 break;
7099 case cricket::MEDIA_TYPE_DATA:
7100 channel_manager()->DestroyRtpDataChannel(
7101 static_cast<cricket::RtpDataChannel*>(channel));
7102 break;
7103 default:
7104 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7105 break;
7106 }
Zhi Huange830e682018-03-30 10:48:35 -07007107}
Steve Anton6fec8802017-12-04 10:37:29 -08007108
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007109bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007110 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007111 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007112 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007113 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007114 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007115 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007116 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007117 auto base_channel = GetChannel(mid);
7118 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007119 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007120 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007121 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007122 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007123 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007124
Karl Wiberg5966c502019-02-21 23:55:09 +01007125 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007126 // Only pass media transport to call object if media transport is used
7127 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007128 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007129 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007130
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007131 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007132}
7133
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007134void PeerConnection::OnSetStreams() {
7135 RTC_DCHECK_RUN_ON(signaling_thread());
7136 if (IsUnifiedPlan())
7137 UpdateNegotiationNeeded();
7138}
7139
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007140PeerConnectionObserver* PeerConnection::Observer() const {
7141 // In earlier production code, the pointer was not cleared on close,
7142 // which might have led to undefined behavior if the observer was not
7143 // deallocated, or strange crashes if it was.
7144 // We use CHECK in order to catch such behavior if it exists.
7145 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7146 RTC_CHECK(observer_);
7147 return observer_;
7148}
7149
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007150CryptoOptions PeerConnection::GetCryptoOptions() {
7151 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7152 // after it has been removed.
7153 return configuration_.crypto_options.has_value()
7154 ? *configuration_.crypto_options
7155 : factory_->options().crypto_options;
7156}
7157
Harald Alvestrand89061872018-01-02 14:08:34 +01007158void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007159 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007160 if (stats_collector_) {
7161 stats_collector_->ClearCachedStatsReport();
7162 }
7163}
7164
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007165void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007166 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7167 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007168}
7169
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007170void PeerConnection::UpdateNegotiationNeeded() {
7171 RTC_DCHECK_RUN_ON(signaling_thread());
7172 if (!IsUnifiedPlan()) {
7173 Observer()->OnRenegotiationNeeded();
7174 return;
7175 }
7176
7177 // If connection's [[IsClosed]] slot is true, abort these steps.
7178 if (IsClosed())
7179 return;
7180
7181 // If connection's signaling state is not "stable", abort these steps.
7182 if (signaling_state() != kStable)
7183 return;
7184
7185 // NOTE
7186 // The negotiation-needed flag will be updated once the state transitions to
7187 // "stable", as part of the steps for setting an RTCSessionDescription.
7188
7189 // If the result of checking if negotiation is needed is false, clear the
7190 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7191 // to false, and abort these steps.
7192 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7193 if (!is_negotiation_needed) {
7194 is_negotiation_needed_ = false;
7195 return;
7196 }
7197
7198 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7199 // steps.
7200 if (is_negotiation_needed_)
7201 return;
7202
7203 // Set connection's [[NegotiationNeeded]] slot to true.
7204 is_negotiation_needed_ = true;
7205
7206 // Queue a task that runs the following steps:
7207 // If connection's [[IsClosed]] slot is true, abort these steps.
7208 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7209 // Fire an event named negotiationneeded at connection.
7210 Observer()->OnRenegotiationNeeded();
7211}
7212
7213bool PeerConnection::CheckIfNegotiationIsNeeded() {
7214 RTC_DCHECK_RUN_ON(signaling_thread());
7215 // 1. If any implementation-specific negotiation is required, as described at
7216 // the start of this section, return true.
7217
7218 // 2. Let description be connection.[[CurrentLocalDescription]].
7219 const SessionDescriptionInterface* description = current_local_description();
7220 if (!description)
7221 return true;
7222
7223 // 3. If connection has created any RTCDataChannels, and no m= section in
7224 // description has been negotiated yet for data, return true.
7225 if (!sctp_data_channels_.empty()) {
7226 if (!cricket::GetFirstDataContent(description->description()->contents()))
7227 return true;
7228 }
7229
7230 // 4. For each transceiver in connection's set of transceivers, perform the
7231 // following checks:
7232 for (const auto& transceiver : transceivers_) {
7233 const ContentInfo* current_local_msection =
7234 FindTransceiverMSection(transceiver.get(), description);
7235
7236 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7237 transceiver.get(), current_remote_description());
7238
7239 // 4.3 If transceiver is stopped and is associated with an m= section,
7240 // but the associated m= section is not yet rejected in
7241 // connection.[[CurrentLocalDescription]] or
7242 // connection.[[CurrentRemoteDescription]], return true.
7243 if (transceiver->stopped()) {
7244 if (current_local_msection && !current_local_msection->rejected &&
7245 ((current_remote_msection && !current_remote_msection->rejected) ||
7246 !current_remote_msection)) {
7247 return true;
7248 }
7249 continue;
7250 }
7251
7252 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7253 // section in description, return true.
7254 if (!current_local_msection)
7255 return true;
7256
7257 const MediaContentDescription* current_local_media_description =
7258 current_local_msection->media_description();
7259 // 4.2 If transceiver isn't stopped and is associated with an m= section
7260 // in description then perform the following checks:
7261
7262 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7263 // associated m= section in description either doesn't contain a single
7264 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7265 // m= section, or the MSID values themselves, differ from what is in
7266 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7267 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7268 if (current_local_media_description->streams().size() == 0)
7269 return true;
7270
7271 std::vector<std::string> msection_msids;
7272 for (const auto& stream : current_local_media_description->streams()) {
7273 for (const std::string& msid : stream.stream_ids())
7274 msection_msids.push_back(msid);
7275 }
7276
7277 std::vector<std::string> transceiver_msids =
7278 transceiver->sender()->stream_ids();
7279 if (msection_msids.size() != transceiver_msids.size())
7280 return true;
7281
7282 absl::c_sort(transceiver_msids);
7283 absl::c_sort(msection_msids);
7284 if (transceiver_msids != msection_msids)
7285 return true;
7286 }
7287
7288 // 4.2.2 If description is of type "offer", and the direction of the
7289 // associated m= section in neither connection.[[CurrentLocalDescription]]
7290 // nor connection.[[CurrentRemoteDescription]] matches
7291 // transceiver.[[Direction]], return true.
7292 if (description->GetType() == SdpType::kOffer) {
7293 if (!current_remote_description())
7294 return true;
7295
7296 if (!current_remote_msection)
7297 return true;
7298
7299 RtpTransceiverDirection current_local_direction =
7300 current_local_media_description->direction();
7301 RtpTransceiverDirection current_remote_direction =
7302 current_remote_msection->media_description()->direction();
7303 if (transceiver->direction() != current_local_direction &&
7304 transceiver->direction() !=
7305 RtpTransceiverDirectionReversed(current_remote_direction)) {
7306 return true;
7307 }
7308 }
7309
7310 // 4.2.3 If description is of type "answer", and the direction of the
7311 // associated m= section in the description does not match
7312 // transceiver.[[Direction]] intersected with the offered direction (as
7313 // described in [JSEP] (section 5.3.1.)), return true.
7314 if (description->GetType() == SdpType::kAnswer) {
7315 if (!remote_description())
7316 return true;
7317
7318 const ContentInfo* offered_remote_msection =
7319 FindTransceiverMSection(transceiver.get(), remote_description());
7320
7321 RtpTransceiverDirection offered_direction =
7322 offered_remote_msection
7323 ? offered_remote_msection->media_description()->direction()
7324 : RtpTransceiverDirection::kInactive;
7325
7326 if (current_local_media_description->direction() !=
7327 (RtpTransceiverDirectionIntersection(
7328 transceiver->direction(),
7329 RtpTransceiverDirectionReversed(offered_direction)))) {
7330 return true;
7331 }
7332 }
7333 }
7334
7335 // If all the preceding checks were performed and true was not returned,
7336 // nothing remains to be negotiated; return false.
7337 return false;
7338}
7339
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007340} // namespace webrtc