blob: d0698d8c65826b966faec39a0055b7099557d9c1 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010057#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080058#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020059#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800111// UMA metric names.
112const char kSimulcastVersionApplyLocalDescription[] =
113 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
114const char kSimulcastVersionApplyRemoteDescription[] =
115 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
116const char kSimulcastNumberOfEncodings[] =
117 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
118const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
119
Seth Hampson845e8782018-03-02 11:34:10 -0800120static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800121static const char kDefaultAudioSenderId[] = "defaulta0";
122static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700123
zhihuang8f65cdf2016-05-06 18:40:30 -0700124// The length of RTCP CNAMEs.
125static const int kRtcpCnameLength = 16;
126
Steve Antonad182762018-09-05 20:22:40 +0000127enum {
128 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
129 MSG_SET_SESSIONDESCRIPTION_FAILED,
130 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
131 MSG_GETSTATS,
132 MSG_FREE_DATACHANNELS,
133 MSG_REPORT_USAGE_PATTERN,
134};
135
Harald Alvestrand19793842018-06-25 12:03:50 +0200136static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
137
Steve Antonad182762018-09-05 20:22:40 +0000138struct SetSessionDescriptionMsg : public rtc::MessageData {
139 explicit SetSessionDescriptionMsg(
140 webrtc::SetSessionDescriptionObserver* observer)
141 : observer(observer) {}
142
143 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
144 RTCError error;
145};
146
147struct CreateSessionDescriptionMsg : public rtc::MessageData {
148 explicit CreateSessionDescriptionMsg(
149 webrtc::CreateSessionDescriptionObserver* observer)
150 : observer(observer) {}
151
152 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
153 RTCError error;
154};
155
156struct GetStatsMsg : public rtc::MessageData {
157 GetStatsMsg(webrtc::StatsObserver* observer,
158 webrtc::MediaStreamTrackInterface* track)
159 : observer(observer), track(track) {}
160 rtc::scoped_refptr<webrtc::StatsObserver> observer;
161 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
162};
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164// Check if we can send |new_stream| on a PeerConnection.
165bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
166 webrtc::MediaStreamInterface* new_stream) {
167 if (!new_stream || !current_streams) {
168 return false;
169 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700170 if (current_streams->find(new_stream->id()) != nullptr) {
171 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100172 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700173 return false;
174 }
175 return true;
176}
177
deadbeef5e97fb52015-10-15 12:49:08 -0700178// If the direction is "recvonly" or "inactive", treat the description
179// as containing no streams.
180// See: https://code.google.com/p/webrtc/issues/detail?id=5054
181std::vector<cricket::StreamParams> GetActiveStreams(
182 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800183 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700184 ? desc->streams()
185 : std::vector<cricket::StreamParams>();
186}
187
deadbeefab9b2d12015-10-14 11:33:11 -0700188bool IsValidOfferToReceiveMedia(int value) {
189 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
190 return (value >= Options::kUndefined) &&
191 (value <= Options::kMaxOfferToReceiveMedia);
192}
193
zhihuang1c378ed2017-08-17 14:10:50 -0700194// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800195void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700196 const std::vector<rtc::scoped_refptr<
197 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700198 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200199 cricket::MediaDescriptionOptions* video_media_description_options,
200 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700201 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
203 if (audio_media_description_options) {
204 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700205 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700206 }
207 } else {
208 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
209 if (video_media_description_options) {
210 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800211 sender->id(), sender->internal()->stream_ids(), {},
212 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700215 }
zhihuang1c378ed2017-08-17 14:10:50 -0700216}
olka3c747662017-08-17 06:50:32 -0700217
zhihuang1c378ed2017-08-17 14:10:50 -0700218// Add options to |session_options| from |rtp_data_channels|.
219void AddRtpDataChannelOptions(
220 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
221 rtp_data_channels,
222 cricket::MediaDescriptionOptions* data_media_description_options) {
223 if (!data_media_description_options) {
224 return;
225 }
deadbeefab9b2d12015-10-14 11:33:11 -0700226 // Check for data channels.
227 for (const auto& kv : rtp_data_channels) {
228 const DataChannel* channel = kv.second;
229 if (channel->state() == DataChannel::kConnecting ||
230 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700231 // Legacy RTP data channels are signaled with the track/stream ID set to
232 // the data channel's label.
233 data_media_description_options->AddRtpDataChannel(channel->label(),
234 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700235 }
236 }
237}
238
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700239uint32_t ConvertIceTransportTypeToCandidateFilter(
240 PeerConnectionInterface::IceTransportsType type) {
241 switch (type) {
242 case PeerConnectionInterface::kNone:
243 return cricket::CF_NONE;
244 case PeerConnectionInterface::kRelay:
245 return cricket::CF_RELAY;
246 case PeerConnectionInterface::kNoHost:
247 return (cricket::CF_ALL & ~cricket::CF_HOST);
248 case PeerConnectionInterface::kAll:
249 return cricket::CF_ALL;
250 default:
nissec80e7412017-01-11 05:56:46 -0800251 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700252 }
253 return cricket::CF_NONE;
254}
255
deadbeef293e9262017-01-11 12:28:30 -0800256// Helper to set an error and return from a method.
257bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
258 if (error) {
259 error->set_type(type);
260 }
261 return type == webrtc::RTCErrorType::NONE;
262}
263
Steve Anton038834f2017-07-14 15:59:59 -0700264bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700265 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700266 if (error_out) {
267 *error_out = std::move(error);
268 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700269 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700270}
271
Steve Antonba818672017-11-06 10:21:57 -0800272std::string GetSignalingStateString(
273 PeerConnectionInterface::SignalingState state) {
274 switch (state) {
275 case PeerConnectionInterface::kStable:
276 return "kStable";
277 case PeerConnectionInterface::kHaveLocalOffer:
278 return "kHaveLocalOffer";
279 case PeerConnectionInterface::kHaveLocalPrAnswer:
280 return "kHavePrAnswer";
281 case PeerConnectionInterface::kHaveRemoteOffer:
282 return "kHaveRemoteOffer";
283 case PeerConnectionInterface::kHaveRemotePrAnswer:
284 return "kHaveRemotePrAnswer";
285 case PeerConnectionInterface::kClosed:
286 return "kClosed";
287 }
288 RTC_NOTREACHED();
289 return "";
290}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700291
Steve Anton75737c02017-11-06 10:37:17 -0800292IceCandidatePairType GetIceCandidatePairCounter(
293 const cricket::Candidate& local,
294 const cricket::Candidate& remote) {
295 const auto& l = local.type();
296 const auto& r = remote.type();
297 const auto& host = LOCAL_PORT_TYPE;
298 const auto& srflx = STUN_PORT_TYPE;
299 const auto& relay = RELAY_PORT_TYPE;
300 const auto& prflx = PRFLX_PORT_TYPE;
301 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800302 bool local_hostname =
303 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
304 bool remote_hostname = !remote.address().hostname().empty() &&
305 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800306 bool local_private = IPIsPrivate(local.address().ipaddr());
307 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800308 if (local_hostname) {
309 if (remote_hostname) {
310 return kIceCandidatePairHostNameHostName;
311 } else if (remote_private) {
312 return kIceCandidatePairHostNameHostPrivate;
313 } else {
314 return kIceCandidatePairHostNameHostPublic;
315 }
316 } else if (local_private) {
317 if (remote_hostname) {
318 return kIceCandidatePairHostPrivateHostName;
319 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800320 return kIceCandidatePairHostPrivateHostPrivate;
321 } else {
322 return kIceCandidatePairHostPrivateHostPublic;
323 }
324 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800325 if (remote_hostname) {
326 return kIceCandidatePairHostPublicHostName;
327 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800328 return kIceCandidatePairHostPublicHostPrivate;
329 } else {
330 return kIceCandidatePairHostPublicHostPublic;
331 }
332 }
333 }
334 if (l == host && r == srflx)
335 return kIceCandidatePairHostSrflx;
336 if (l == host && r == relay)
337 return kIceCandidatePairHostRelay;
338 if (l == host && r == prflx)
339 return kIceCandidatePairHostPrflx;
340 if (l == srflx && r == host)
341 return kIceCandidatePairSrflxHost;
342 if (l == srflx && r == srflx)
343 return kIceCandidatePairSrflxSrflx;
344 if (l == srflx && r == relay)
345 return kIceCandidatePairSrflxRelay;
346 if (l == srflx && r == prflx)
347 return kIceCandidatePairSrflxPrflx;
348 if (l == relay && r == host)
349 return kIceCandidatePairRelayHost;
350 if (l == relay && r == srflx)
351 return kIceCandidatePairRelaySrflx;
352 if (l == relay && r == relay)
353 return kIceCandidatePairRelayRelay;
354 if (l == relay && r == prflx)
355 return kIceCandidatePairRelayPrflx;
356 if (l == prflx && r == host)
357 return kIceCandidatePairPrflxHost;
358 if (l == prflx && r == srflx)
359 return kIceCandidatePairPrflxSrflx;
360 if (l == prflx && r == relay)
361 return kIceCandidatePairPrflxRelay;
362 return kIceCandidatePairMax;
363}
364
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800365// Logic to decide if an m= section can be recycled. This means that the new
366// m= section is not rejected, but the old local or remote m= section is
367// rejected. |old_content_one| and |old_content_two| refer to the m= section
368// of the old remote and old local descriptions in no particular order.
369// We need to check both the old local and remote because either
370// could be the most current from the latest negotation.
371bool IsMediaSectionBeingRecycled(SdpType type,
372 const ContentInfo& content,
373 const ContentInfo* old_content_one,
374 const ContentInfo* old_content_two) {
375 return type == SdpType::kOffer && !content.rejected &&
376 ((old_content_one && old_content_one->rejected) ||
377 (old_content_two && old_content_two->rejected));
378}
379
Steve Anton75737c02017-11-06 10:37:17 -0800380// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800381// |current_desc|. The number of m= sections in |new_desc| should be no
382// less than |current_desc|. In the case of checking an answer's
383// |new_desc|, the |current_desc| is the last offer that was set as the
384// local or remote. In the case of checking an offer's |new_desc| we
385// check against the local and remote descriptions stored from the last
386// negotiation, because either of these could be the most up to date for
387// possible rejected m sections. These are the |current_desc| and
388// |secondary_current_desc|.
389bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
390 const SessionDescription* secondary_current_desc,
391 const SessionDescription& new_desc,
392 const SdpType type) {
393 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 return false;
395 }
396
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800397 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
398 const cricket::ContentInfo* secondary_content_info = nullptr;
399 if (secondary_current_desc &&
400 i < secondary_current_desc->contents().size()) {
401 secondary_content_info = &secondary_current_desc->contents()[i];
402 }
403 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
404 &current_desc.contents()[i],
405 secondary_content_info)) {
406 // For new offer descriptions, if the media section can be recycled, it's
407 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800408 continue;
409 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800411 return false;
412 }
413 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800414 new_desc.contents()[i].media_description();
415 const MediaContentDescription* current_desc_mdesc =
416 current_desc.contents()[i].media_description();
417 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 return false;
419 }
420 }
421 return true;
422}
423
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800424bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
425 const SessionDescription& desc2) {
426 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800427}
428
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700429void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
430 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200431 // Array of structs needed to map {KeyExchangeProtocolType,
432 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
433 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
434 static constexpr struct {
435 KeyExchangeProtocolType protocol_type;
436 cricket::MediaType media_type;
437 KeyExchangeProtocolMedia protocol_media;
438 } kEnumCounterKeyProtocolMediaMap[] = {
439 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
440 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
441 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
442 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
443 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
444 kEnumCounterKeyProtocolMediaTypeDtlsData},
445 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
446 kEnumCounterKeyProtocolMediaTypeSdesAudio},
447 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
448 kEnumCounterKeyProtocolMediaTypeSdesVideo},
449 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
450 kEnumCounterKeyProtocolMediaTypeSdesData},
451 };
452
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700453 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
454 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100455
Mirko Bonadeiab499822018-09-11 10:43:20 +0200456 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
457 if (i.protocol_type == protocol_type && i.media_type == media_type) {
458 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
459 i.protocol_media,
460 kEnumCounterKeyProtocolMediaTypeMax);
461 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100462 }
463}
464
Harald Alvestrand76829d72018-07-18 23:24:36 +0200465void NoteAddIceCandidateResult(int result) {
466 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
467 kAddIceCandidateMax);
468}
469
Steve Anton75737c02017-11-06 10:37:17 -0800470// Checks that each non-rejected content has SDES crypto keys or a DTLS
471// fingerprint, unless it's in a BUNDLE group, in which case only the
472// BUNDLE-tag section (first media section/description in the BUNDLE group)
473// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
474// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
475// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700476RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100483 // Note what media is used with each crypto protocol, for all sections.
484 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
485 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700486 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800487 const std::string& mid = content_info.name;
488 if (bundle && bundle->HasContentName(mid) &&
489 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800490 // This isn't the first media section in the BUNDLE group, so it's not
491 // required to have crypto attributes, since only the crypto attributes
492 // from the first section actually get used.
493 continue;
494 }
495
496 // If the content isn't rejected or bundled into another m= section, crypto
497 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800498 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800499 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800500 if (!media || !tinfo) {
501 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800503 }
504 if (dtls_enabled) {
505 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100506 RTC_LOG(LS_WARNING)
507 << "Session description must have DTLS fingerprint if "
508 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800509 return RTCError(RTCErrorType::INVALID_PARAMETER,
510 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800511 }
512 } else {
513 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800515 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800516 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800517 }
518 }
519 }
Steve Anton8a006912017-12-04 15:25:56 -0800520 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800521}
522
523// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
524// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
525// media section/description in the BUNDLE group) needs a ufrag and pwd.
526bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
527 const cricket::ContentGroup* bundle =
528 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800529 for (const cricket::ContentInfo& content_info : desc->contents()) {
530 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800531 continue;
532 }
Steve Anton8a006912017-12-04 15:25:56 -0800533 const std::string& mid = content_info.name;
534 if (bundle && bundle->HasContentName(mid) &&
535 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800536 // This isn't the first media section in the BUNDLE group, so it's not
537 // required to have ufrag/password, since only the ufrag/password from
538 // the first section actually get used.
539 continue;
540 }
541
542 // If the content isn't rejected or bundled into another m= section,
543 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800544 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800545 if (!tinfo) {
546 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100547 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800548 return false;
549 }
550 if (tinfo->description.ice_ufrag.empty() ||
551 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100552 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800553 return false;
554 }
555 }
556 return true;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200596 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200599 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800600}
601
Seth Hampson5b4f0752018-04-02 16:31:36 -0700602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200613absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200617 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700618 }
619 return rtc_configuration_parameter;
620}
621
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800622cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
623 switch (type) {
624 case DataMessageType::kText:
625 return cricket::DMT_TEXT;
626 case DataMessageType::kBinary:
627 return cricket::DMT_BINARY;
628 case DataMessageType::kControl:
629 return cricket::DMT_CONTROL;
630 default:
631 return cricket::DMT_NONE;
632 }
633 return cricket::DMT_NONE;
634}
635
636DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
637 switch (type) {
638 case cricket::DMT_TEXT:
639 return DataMessageType::kText;
640 case cricket::DMT_BINARY:
641 return DataMessageType::kBinary;
642 case cricket::DMT_CONTROL:
643 return DataMessageType::kControl;
644 case cricket::DMT_NONE:
645 default:
646 RTC_NOTREACHED();
647 }
648 return DataMessageType::kControl;
649}
650
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800651void ReportSimulcastApiVersion(const char* name,
652 const SessionDescription& session) {
653 bool has_legacy = false;
654 bool has_spec_compliant = false;
655 for (const ContentInfo& content : session.contents()) {
656 if (!content.description) {
657 continue;
658 }
659 has_spec_compliant |= content.description->HasSimulcast();
660 for (const StreamParams& sp : content.description->streams()) {
661 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
662 }
663 }
664
665 if (has_legacy) {
666 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
667 kSimulcastApiVersionMax);
668 }
669 if (has_spec_compliant) {
670 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
671 kSimulcastApiVersionMax);
672 }
673 if (!has_legacy && !has_spec_compliant) {
674 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
675 kSimulcastApiVersionMax);
676 }
677}
678
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200679const ContentInfo* FindTransceiverMSection(
680 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
681 const SessionDescriptionInterface* session_description) {
682 return transceiver->mid()
683 ? session_description->description()->GetContentByName(
684 *transceiver->mid())
685 : nullptr;
686}
687
Steve Anton75737c02017-11-06 10:37:17 -0800688} // namespace
689
Henrik Boström31638672017-11-23 17:48:32 +0100690// Upon completion, posts a task to execute the callback of the
691// SetSessionDescriptionObserver asynchronously on the same thread. At this
692// point, the state of the peer connection might no longer reflect the effects
693// of the SetRemoteDescription operation, as the peer connection could have been
694// modified during the post.
695// TODO(hbos): Remove this class once we remove the version of
696// PeerConnectionInterface::SetRemoteDescription() that takes a
697// SetSessionDescriptionObserver as an argument.
698class PeerConnection::SetRemoteDescriptionObserverAdapter
699 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
700 public:
701 SetRemoteDescriptionObserverAdapter(
702 rtc::scoped_refptr<PeerConnection> pc,
703 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
704 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
705
706 // SetRemoteDescriptionObserverInterface implementation.
707 void OnSetRemoteDescriptionComplete(RTCError error) override {
708 if (error.ok())
709 pc_->PostSetSessionDescriptionSuccess(wrapper_);
710 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100711 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100712 }
713
714 private:
715 rtc::scoped_refptr<PeerConnection> pc_;
716 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
717};
718
deadbeef293e9262017-01-11 12:28:30 -0800719bool PeerConnectionInterface::RTCConfiguration::operator==(
720 const PeerConnectionInterface::RTCConfiguration& o) const {
721 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700722 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800723 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000724 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700725 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800726 BundlePolicy bundle_policy;
727 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700728 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
729 int ice_candidate_pool_size;
730 bool disable_ipv6;
731 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700732 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100733 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<int> screencast_min_bitrate;
736 absl::optional<bool> combined_audio_video_bwe;
737 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800738 TcpCandidatePolicy tcp_candidate_policy;
739 CandidateNetworkPolicy candidate_network_policy;
740 int audio_jitter_buffer_max_packets;
741 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100742 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100743 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800744 int ice_connection_receiving_timeout;
745 int ice_backup_candidate_pair_ping_interval;
746 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800747 bool prioritize_most_likely_ice_candidate_pairs;
748 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800749 bool prune_turn_ports;
750 bool presume_writable_when_fully_relayed;
751 bool enable_ice_renomination;
752 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200753 absl::optional<int> ice_check_interval_strong_connectivity;
754 absl::optional<int> ice_check_interval_weak_connectivity;
755 absl::optional<int> ice_check_min_interval;
756 absl::optional<int> ice_unwritable_timeout;
757 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800758 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200759 absl::optional<int> stun_candidate_keepalive_interval;
760 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200761 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800762 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700764 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700765 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700767 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700768 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100769 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770 };
771 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
772 "Did you add something to RTCConfiguration and forget to "
773 "update operator==?");
774 return type == o.type && servers == o.servers &&
775 bundle_policy == o.bundle_policy &&
776 rtcp_mux_policy == o.rtcp_mux_policy &&
777 tcp_candidate_policy == o.tcp_candidate_policy &&
778 candidate_network_policy == o.candidate_network_policy &&
779 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
780 audio_jitter_buffer_fast_accelerate ==
781 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 audio_jitter_buffer_min_delay_ms ==
783 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100784 audio_jitter_buffer_enable_rtx_handling ==
785 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800786 ice_connection_receiving_timeout ==
787 o.ice_connection_receiving_timeout &&
788 ice_backup_candidate_pair_ping_interval ==
789 o.ice_backup_candidate_pair_ping_interval &&
790 continual_gathering_policy == o.continual_gathering_policy &&
791 certificates == o.certificates &&
792 prioritize_most_likely_ice_candidate_pairs ==
793 o.prioritize_most_likely_ice_candidate_pairs &&
794 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800795 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700796 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100797 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800798 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800799 screencast_min_bitrate == o.screencast_min_bitrate &&
800 combined_audio_video_bwe == o.combined_audio_video_bwe &&
801 enable_dtls_srtp == o.enable_dtls_srtp &&
802 ice_candidate_pool_size == o.ice_candidate_pool_size &&
803 prune_turn_ports == o.prune_turn_ports &&
804 presume_writable_when_fully_relayed ==
805 o.presume_writable_when_fully_relayed &&
806 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800807 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800808 ice_check_interval_strong_connectivity ==
809 o.ice_check_interval_strong_connectivity &&
810 ice_check_interval_weak_connectivity ==
811 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700812 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700813 ice_unwritable_timeout == o.ice_unwritable_timeout &&
814 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800815 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800816 stun_candidate_keepalive_interval ==
817 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200818 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800819 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800820 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700821 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700822 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700823 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700824 use_media_transport_for_data_channels ==
825 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700826 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100827 crypto_options == o.crypto_options &&
828 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800829}
830
831bool PeerConnectionInterface::RTCConfiguration::operator!=(
832 const PeerConnectionInterface::RTCConfiguration& o) const {
833 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800834}
835
zhihuang8f65cdf2016-05-06 18:40:30 -0700836// Generate a RTCP CNAME when a PeerConnection is created.
837std::string GenerateRtcpCname() {
838 std::string cname;
839 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800841 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700842 }
843 return cname;
844}
845
zhihuang1c378ed2017-08-17 14:10:50 -0700846bool ValidateOfferAnswerOptions(
847 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
848 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
849 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700850}
851
zhihuang1c378ed2017-08-17 14:10:50 -0700852// From |rtc_options|, fill parts of |session_options| shared by all generated
853// m= sections (in other words, nothing that involves a map/array).
854void ExtractSharedMediaSessionOptions(
855 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
856 cricket::MediaSessionOptions* session_options) {
857 session_options->vad_enabled = rtc_options.voice_activity_detection;
858 session_options->bundle_enabled = rtc_options.use_rtp_mux;
859}
zhihuanga77e6bb2017-08-14 18:17:48 -0700860
zhihuang38ede132017-06-15 12:52:32 -0700861PeerConnection::PeerConnection(PeerConnectionFactory* factory,
862 std::unique_ptr<RtcEventLog> event_log,
863 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700865 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100866 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700867 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700868 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700869 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100870 call_(std::move(call)),
871 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872
873PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100874 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800875 RTC_DCHECK_RUN_ON(signaling_thread());
876
Steve Anton8af21862017-12-15 11:20:13 -0800877 // Need to stop transceivers before destroying the stats collector because
878 // AudioRtpSender has a reference to the StatsCollector it will update when
879 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100880 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800881 transceiver->Stop();
882 }
Steve Anton4171afb2017-11-20 10:20:22 -0800883
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700884 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800885 if (stats_collector_) {
886 stats_collector_->WaitForPendingRequest();
887 stats_collector_ = nullptr;
888 }
Steve Anton75737c02017-11-06 10:37:17 -0800889
Steve Anton8af21862017-12-15 11:20:13 -0800890 // Don't destroy BaseChannels until after stats has been cleaned up so that
891 // the last stats request can still read from the channels.
892 DestroyAllChannels();
893
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800895
896 webrtc_session_desc_factory_.reset();
897 sctp_invoker_.reset();
898 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800899 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800900 transport_controller_.reset();
901
deadbeef91dd5672016-05-18 16:55:30 -0700902 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100903 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
904 RTC_DCHECK_RUN_ON(network_thread());
905 port_allocator_.reset();
906 });
eladalon248fd4f2017-09-06 05:18:15 -0700907 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700908 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100909 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700910 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800911 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700912 event_log_.reset();
913 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914}
915
Steve Anton8af21862017-12-15 11:20:13 -0800916void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800917 // Destroy video channels first since they may have a pointer to a voice
918 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100919 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800920 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800921 DestroyTransceiverChannel(transceiver);
922 }
923 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100924 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800925 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800926 DestroyTransceiverChannel(transceiver);
927 }
928 }
929 DestroyDataChannel();
930}
931
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000933 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700934 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100935 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100936 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100937 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700938
939 RTCError config_error = ValidateConfiguration(configuration);
940 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100941 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700942 return false;
943 }
944
Benjamin Wrightcab58882018-05-02 15:12:47 -0700945 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100946 RTC_LOG(LS_ERROR)
947 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100948 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800949 return false;
950 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200951
Benjamin Wrightcab58882018-05-02 15:12:47 -0700952 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800953 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100955 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800956 return false;
957 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700958
Benjamin Wrightcab58882018-05-02 15:12:47 -0700959 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700960 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700961 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700962 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800963
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200964 cricket::ServerAddresses stun_servers;
965 std::vector<cricket::RelayServerConfig> turn_servers;
966
967 RTCErrorType parse_error =
968 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
969 if (parse_error != RTCErrorType::NONE) {
970 return false;
971 }
972
deadbeef91dd5672016-05-18 16:55:30 -0700973 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700974 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100975 const auto pa_result =
976 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200977 RTC_FROM_HERE,
978 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100979 stun_servers, turn_servers, configuration));
980
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200981 // If initialization was successful, note if STUN or TURN servers
982 // were supplied.
983 if (!stun_servers.empty()) {
984 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
985 }
986 if (!turn_servers.empty()) {
987 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
988 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700990 // Send information about IPv4/IPv6 status.
991 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100992 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700993 address_family = kPeerConnection_IPv6;
994 } else {
995 address_family = kPeerConnection_IPv4;
996 }
997 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
998 kPeerConnectionAddressFamilyCounter_Max);
999
Zhi Huange830e682018-03-30 10:48:35 -07001000 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1001
Steve Anton75737c02017-11-06 10:37:17 -08001002 // RFC 3264: The numeric value of the session id and version in the
1003 // o line MUST be representable with a "64 bit signed integer".
1004 // Due to this constraint session id |session_id_| is max limited to
1005 // LLONG_MAX.
1006 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001007 JsepTransportController::Config config;
1008 config.redetermine_role_on_ice_restart =
1009 configuration.redetermine_role_on_ice_restart;
1010 config.ssl_max_version = factory_->options().ssl_max_version;
1011 config.disable_encryption = options.disable_encryption;
1012 config.bundle_policy = configuration.bundle_policy;
1013 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001014 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1015 // stub.
1016 config.crypto_options = configuration.crypto_options.has_value()
1017 ? *configuration.crypto_options
1018 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001019 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001020 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001021#if defined(ENABLE_EXTERNAL_AUTH)
1022 config.enable_external_auth = true;
1023#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001024 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001025
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001026 if (configuration.use_datagram_transport ||
1027 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001028 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001029 if (!factory_->media_transport_factory()) {
1030 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001031 << "PeerConnecton is initialized with use_media_transport = true or "
1032 << "use_media_transport_for_data_channels = true "
1033 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001034 return false;
1035 }
1036
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001037 if (configuration.use_media_transport ||
1038 configuration.use_media_transport_for_data_channels) {
1039 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1040 // RTP media transport is introduced. But until then, we require SDES to
1041 // be enabled.
1042 if (configuration.enable_dtls_srtp.has_value() &&
1043 configuration.enable_dtls_srtp.value()) {
1044 RTC_LOG(LS_WARNING)
1045 << "When media transport is used, SDES must be enabled. Set "
1046 "configuration.enable_dtls_srtp to false. use_media_transport="
1047 << configuration.use_media_transport
1048 << ", use_media_transport_for_data_channels="
1049 << configuration.use_media_transport_for_data_channels;
1050 return false;
1051 }
1052 }
1053
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001054 config.use_media_transport_for_media = configuration.use_media_transport;
1055 config.use_media_transport_for_data_channels =
1056 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001057 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001058 config.media_transport_factory = factory_->media_transport_factory();
1059 }
1060
Zhi Huange830e682018-03-30 10:48:35 -07001061 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001062 signaling_thread(), network_thread(), port_allocator_.get(),
1063 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001064 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001065 this, &PeerConnection::OnTransportControllerConnectionState);
1066 transport_controller_->SignalStandardizedIceConnectionState.connect(
1067 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001068 transport_controller_->SignalConnectionState.connect(
1069 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001070 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001071 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001072 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001073 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001074 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001075 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1076 transport_controller_->SignalDtlsHandshakeError.connect(
1077 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1078
1079 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001080
deadbeefab9b2d12015-10-14 11:33:11 -07001081 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001082 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083
Steve Antonba818672017-11-06 10:21:57 -08001084 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001085 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001086
Steve Anton75737c02017-11-06 10:37:17 -08001087 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1088 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1089 if (!configuration.certificates.empty()) {
1090 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1091 // just picking the first one. The decision should be made based on the DTLS
1092 // handshake. The DTLS negotiations need to know about all certificates.
1093 certificate = configuration.certificates[0];
1094 }
1095
Steve Antond25da372017-11-06 14:50:29 -08001096 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001097
1098 if (options.disable_encryption) {
1099 dtls_enabled_ = false;
1100 } else {
1101 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001102 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001103 // |configuration| can override the default |dtls_enabled_| value.
1104 if (configuration.enable_dtls_srtp) {
1105 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1106 }
1107 }
1108
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001109 if (configuration.use_media_transport_for_data_channels) {
1110 if (configuration.enable_rtp_data_channel) {
1111 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1112 "use_media_transport_for_data_channels are "
1113 "incompatible and cannot both be set to true";
1114 return false;
1115 }
1116 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1117 } else if (configuration.enable_rtp_data_channel) {
1118 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1119 // set. It takes precendence over the disable_sctp_data_channels
1120 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001121 data_channel_type_ = cricket::DCT_RTP;
1122 } else {
1123 // DTLS has to be enabled to use SCTP.
1124 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1125 data_channel_type_ = cricket::DCT_SCTP;
1126 }
1127 }
1128
1129 video_options_.screencast_min_bitrate_kbps =
1130 configuration.screencast_min_bitrate;
1131 audio_options_.combined_audio_video_bwe =
1132 configuration.combined_audio_video_bwe;
1133
1134 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001135 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001136
1137 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001138 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001139
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001140 audio_options_.audio_jitter_buffer_min_delay_ms =
1141 configuration.audio_jitter_buffer_min_delay_ms;
1142
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001143 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1144 configuration.audio_jitter_buffer_enable_rtx_handling;
1145
Steve Anton75737c02017-11-06 10:37:17 -08001146 // Whether the certificate generator/certificate is null or not determines
1147 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1148 // the right instructions by clearing the variables if needed.
1149 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001150 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001151 certificate = nullptr;
1152 } else if (certificate) {
1153 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001154 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001155 }
1156
1157 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1158 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001159 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001160 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1161 this, &PeerConnection::OnCertificateReady);
1162
1163 if (options.disable_encryption) {
1164 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1165 }
1166
1167 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001168 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001169 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170
Steve Anton4171afb2017-11-20 10:20:22 -08001171 // Add default audio/video transceivers for Plan B SDP.
1172 if (!IsUnifiedPlan()) {
1173 transceivers_.push_back(
1174 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1175 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1176 transceivers_.push_back(
1177 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1178 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1179 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001180 int delay_ms =
1181 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001182 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1183 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001184
1185 if (dependencies.video_bitrate_allocator_factory) {
1186 video_bitrate_allocator_factory_ =
1187 std::move(dependencies.video_bitrate_allocator_factory);
1188 } else {
1189 video_bitrate_allocator_factory_ =
1190 CreateBuiltinVideoBitrateAllocatorFactory();
1191 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001192 return true;
1193}
1194
Steve Anton038834f2017-07-14 15:59:59 -07001195RTCError PeerConnection::ValidateConfiguration(
1196 const RTCConfiguration& config) const {
1197 if (config.ice_regather_interval_range &&
1198 config.continual_gathering_policy == GATHER_ONCE) {
1199 return RTCError(RTCErrorType::INVALID_PARAMETER,
1200 "ice_regather_interval_range specified but continual "
1201 "gathering policy is GATHER_ONCE");
1202 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001203 auto result =
1204 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1205 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001206}
1207
Yves Gerey665174f2018-06-19 15:03:05 +02001208rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001209 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001210 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1211 "Plan SdpSemantics. Please use GetSenders "
1212 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001213 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214}
1215
Yves Gerey665174f2018-06-19 15:03:05 +02001216rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001217 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001218 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1219 "Plan SdpSemantics. Please use GetReceivers "
1220 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001221 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222}
1223
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001224bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001225 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001226 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1227 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001228 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229 if (IsClosed()) {
1230 return false;
1231 }
deadbeefab9b2d12015-10-14 11:33:11 -07001232 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 return false;
1234 }
deadbeefab9b2d12015-10-14 11:33:11 -07001235
1236 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001237 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1238 observer->SignalAudioTrackAdded.connect(this,
1239 &PeerConnection::OnAudioTrackAdded);
1240 observer->SignalAudioTrackRemoved.connect(
1241 this, &PeerConnection::OnAudioTrackRemoved);
1242 observer->SignalVideoTrackAdded.connect(this,
1243 &PeerConnection::OnVideoTrackAdded);
1244 observer->SignalVideoTrackRemoved.connect(
1245 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001246 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001247
deadbeefab9b2d12015-10-14 11:33:11 -07001248 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001249 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001250 }
1251 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001252 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001253 }
1254
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001255 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001256 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257 return true;
1258}
1259
1260void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001261 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001262 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1263 "Plan SdpSemantics. Please use RemoveTrack "
1264 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001265 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001266 if (!IsClosed()) {
1267 for (const auto& track : local_stream->GetAudioTracks()) {
1268 RemoveAudioTrack(track.get(), local_stream);
1269 }
1270 for (const auto& track : local_stream->GetVideoTracks()) {
1271 RemoveVideoTrack(track.get(), local_stream);
1272 }
deadbeefab9b2d12015-10-14 11:33:11 -07001273 }
deadbeefab9b2d12015-10-14 11:33:11 -07001274 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001275 stream_observers_.erase(
1276 std::remove_if(
1277 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001278 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001279 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001280 }),
1281 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 if (IsClosed()) {
1284 return;
1285 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001286 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287}
1288
Steve Anton2d6c76a2018-01-05 17:10:52 -08001289RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001290 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001291 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001292 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001293 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001294 if (!track) {
1295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1296 }
1297 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1298 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1300 "Track has invalid kind: " + track->kind());
1301 }
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (IsClosed()) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1304 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001305 }
Steve Anton4171afb2017-11-20 10:20:22 -08001306 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001307 LOG_AND_RETURN_ERROR(
1308 RTCErrorType::INVALID_PARAMETER,
1309 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001310 }
Steve Antonf9381f02017-12-14 10:23:57 -08001311 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001312 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1313 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001314 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001315 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001316 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001317 }
1318 return sender_or_error;
1319}
deadbeefe1f9d832016-01-14 15:35:42 -08001320
Steve Antonf9381f02017-12-14 10:23:57 -08001321RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1322PeerConnection::AddTrackPlanB(
1323 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001324 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001325 if (stream_ids.size() > 1u) {
1326 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1327 "AddTrack with more than one stream is not "
1328 "supported with Plan B semantics.");
1329 }
1330 std::vector<std::string> adjusted_stream_ids = stream_ids;
1331 if (adjusted_stream_ids.empty()) {
1332 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1333 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001334 cricket::MediaType media_type =
1335 (track->kind() == MediaStreamTrackInterface::kAudioKind
1336 ? cricket::MEDIA_TYPE_AUDIO
1337 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001338 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001339 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001340 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001341 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001342 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001343 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001344 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001345 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001346 if (sender_info) {
1347 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001348 }
Steve Antonf9381f02017-12-14 10:23:57 -08001349 } else {
1350 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001351 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001353 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001354 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001355 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001356 if (sender_info) {
1357 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001358 }
deadbeefe1f9d832016-01-14 15:35:42 -08001359 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001360 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001361}
deadbeefe1f9d832016-01-14 15:35:42 -08001362
Steve Antonf9381f02017-12-14 10:23:57 -08001363RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1364PeerConnection::AddTrackUnifiedPlan(
1365 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001366 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001367 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1368 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001369 RTC_LOG(LS_INFO) << "Reusing an existing "
1370 << cricket::MediaTypeToString(transceiver->media_type())
1371 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001372 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001379 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001380 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 } else {
1382 cricket::MediaType media_type =
1383 (track->kind() == MediaStreamTrackInterface::kAudioKind
1384 ? cricket::MEDIA_TYPE_AUDIO
1385 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001386 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1387 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001388 std::string sender_id = track->id();
1389 // Avoid creating a sender with an existing ID by generating a random ID.
1390 // This can happen if this is the second time AddTrack has created a sender
1391 // for this track.
1392 if (FindSenderById(sender_id)) {
1393 sender_id = rtc::CreateRandomUuid();
1394 }
Florent Castelli892acf02018-10-01 22:47:20 +02001395 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001396 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1397 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001398 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001399 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001400 }
Steve Antonf9381f02017-12-14 10:23:57 -08001401 return transceiver->sender();
1402}
1403
1404rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1405PeerConnection::FindFirstTransceiverForAddedTrack(
1406 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1407 RTC_DCHECK(track);
1408 for (auto transceiver : transceivers_) {
1409 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001410 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001411 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001412 !transceiver->internal()->has_ever_been_used_to_send() &&
1413 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001414 return transceiver;
1415 }
1416 }
1417 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001418}
1419
1420bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1421 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001422 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001423}
1424
Steve Anton24db5732018-07-23 10:27:33 -07001425RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001426 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001427 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001428 if (!sender) {
1429 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1430 }
deadbeefe1f9d832016-01-14 15:35:42 -08001431 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1433 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001434 }
Steve Antonf9381f02017-12-14 10:23:57 -08001435 if (IsUnifiedPlan()) {
1436 auto transceiver = FindTransceiverBySender(sender);
1437 if (!transceiver || !sender->track()) {
1438 return RTCError::OK();
1439 }
1440 sender->SetTrack(nullptr);
1441 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001442 transceiver->internal()->set_direction(
1443 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001444 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001445 transceiver->internal()->set_direction(
1446 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001447 }
Steve Anton4171afb2017-11-20 10:20:22 -08001448 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001449 bool removed;
1450 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1451 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1452 } else {
1453 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1454 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1455 }
1456 if (!removed) {
1457 LOG_AND_RETURN_ERROR(
1458 RTCErrorType::INVALID_PARAMETER,
1459 "Couldn't find sender " + sender->id() + " to remove.");
1460 }
Steve Anton4171afb2017-11-20 10:20:22 -08001461 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001462 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001463 return RTCError::OK();
1464}
1465
1466rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1467PeerConnection::FindTransceiverBySender(
1468 rtc::scoped_refptr<RtpSenderInterface> sender) {
1469 for (auto transceiver : transceivers_) {
1470 if (transceiver->sender() == sender) {
1471 return transceiver;
1472 }
1473 }
1474 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001475}
1476
Steve Anton9158ef62017-11-27 13:01:52 -08001477RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1478PeerConnection::AddTransceiver(
1479 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1480 return AddTransceiver(track, RtpTransceiverInit());
1481}
1482
1483RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1484PeerConnection::AddTransceiver(
1485 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1486 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001487 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001488 RTC_CHECK(IsUnifiedPlan())
1489 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001490 if (!track) {
1491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1492 }
1493 cricket::MediaType media_type;
1494 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1495 media_type = cricket::MEDIA_TYPE_AUDIO;
1496 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1497 media_type = cricket::MEDIA_TYPE_VIDEO;
1498 } else {
1499 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1500 "Track kind is not audio or video");
1501 }
1502 return AddTransceiver(media_type, track, init);
1503}
1504
1505RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1506PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1507 return AddTransceiver(media_type, RtpTransceiverInit());
1508}
1509
1510RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1511PeerConnection::AddTransceiver(cricket::MediaType media_type,
1512 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001513 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001514 RTC_CHECK(IsUnifiedPlan())
1515 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001516 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1517 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1519 "media type is not audio or video");
1520 }
1521 return AddTransceiver(media_type, nullptr, init);
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(
1526 cricket::MediaType media_type,
1527 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001528 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001529 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001530 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1531 media_type == cricket::MEDIA_TYPE_VIDEO));
1532 if (track) {
1533 RTC_DCHECK_EQ(media_type,
1534 (track->kind() == MediaStreamTrackInterface::kAudioKind
1535 ? cricket::MEDIA_TYPE_AUDIO
1536 : cricket::MEDIA_TYPE_VIDEO));
1537 }
1538
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001539 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1540 init.send_encodings.size(), 0, 7, 8);
1541
Amit Hilbuchaa584152019-02-06 17:09:52 -08001542 size_t num_rids = absl::c_count_if(init.send_encodings,
1543 [](const RtpEncodingParameters& encoding) {
1544 return !encoding.rid.empty();
1545 });
1546 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001547 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001548 RTCErrorType::INVALID_PARAMETER,
1549 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001550 }
1551
Amit Hilbuchf4770402019-04-08 14:11:57 -07001552 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1553 [](const RtpEncodingParameters& encoding) {
1554 return !IsLegalRsidName(encoding.rid);
1555 })) {
1556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1557 "Invalid RID value provided.");
1558 }
1559
Amit Hilbuchaa584152019-02-06 17:09:52 -08001560 if (absl::c_any_of(init.send_encodings,
1561 [](const RtpEncodingParameters& encoding) {
1562 return encoding.ssrc.has_value();
1563 })) {
1564 LOG_AND_RETURN_ERROR(
1565 RTCErrorType::UNSUPPORTED_PARAMETER,
1566 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001567 }
1568
1569 RtpParameters parameters;
1570 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001571
1572 // Encodings are dropped from the tail if too many are provided.
1573 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1574 parameters.encodings.erase(
1575 parameters.encodings.begin() + kMaxSimulcastStreams,
1576 parameters.encodings.end());
1577 }
1578
1579 // Single RID should be removed.
1580 if (parameters.encodings.size() == 1 &&
1581 !parameters.encodings[0].rid.empty()) {
1582 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1583 parameters.encodings[0].rid.clear();
1584 }
1585
1586 // If RIDs were not provided, they are generated for simulcast scenario.
1587 if (parameters.encodings.size() > 1 && num_rids == 0) {
1588 rtc::UniqueStringGenerator rid_generator;
1589 for (RtpEncodingParameters& encoding : parameters.encodings) {
1590 encoding.rid = rid_generator();
1591 }
1592 }
1593
Florent Castelli892acf02018-10-01 22:47:20 +02001594 if (UnimplementedRtpParameterHasValue(parameters)) {
1595 LOG_AND_RETURN_ERROR(
1596 RTCErrorType::UNSUPPORTED_PARAMETER,
1597 "Attempted to set an unimplemented parameter of RtpParameters.");
1598 }
Steve Anton9158ef62017-11-27 13:01:52 -08001599
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001600 auto result = cricket::CheckRtpParametersValues(parameters);
1601 if (!result.ok()) {
1602 LOG_AND_RETURN_ERROR(result.type(), result.message());
1603 }
1604
Steve Anton3d954a62018-04-02 11:27:23 -07001605 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1606 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001607 // Set the sender ID equal to the track ID if the track is specified unless
1608 // that sender ID is already in use.
1609 std::string sender_id =
1610 (track && !FindSenderById(track->id()) ? track->id()
1611 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001612 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001613 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001614 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1615 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1616 transceiver->internal()->set_direction(init.direction);
1617
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001618 if (update_negotiation_needed) {
1619 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001620 }
Steve Antonf9381f02017-12-14 10:23:57 -08001621
1622 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1623}
1624
Steve Anton02ee47c2018-01-10 16:26:06 -08001625rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1626PeerConnection::CreateSender(
1627 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001628 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001629 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001630 const std::vector<std::string>& stream_ids,
1631 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001632 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001633 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001634 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1635 RTC_DCHECK(!track ||
1636 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1637 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1638 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001639 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001640 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001641 } else {
1642 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1643 RTC_DCHECK(!track ||
1644 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1645 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001646 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001647 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001648 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001649 bool set_track_succeeded = sender->SetTrack(track);
1650 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001651 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001652 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001653 return sender;
1654}
1655
1656rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1657PeerConnection::CreateReceiver(cricket::MediaType media_type,
1658 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001659 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1660 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001661 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001662 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001663 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1664 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001665 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001666 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001668 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001669 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1670 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001671 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001672 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001673 return receiver;
1674}
1675
1676rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1677PeerConnection::CreateAndAddTransceiver(
1678 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1679 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1680 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001681 // Ensure that the new sender does not have an ID that is already in use by
1682 // another sender.
1683 // Allow receiver IDs to conflict since those come from remote SDP (which
1684 // could be invalid, but should not cause a crash).
1685 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001686 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001687 signaling_thread(),
1688 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001689 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001690 transceiver->internal()->SignalNegotiationNeeded.connect(
1691 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001692 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001693}
1694
Steve Anton52d86772018-02-20 15:48:12 -08001695void PeerConnection::OnNegotiationNeeded() {
1696 RTC_DCHECK_RUN_ON(signaling_thread());
1697 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001698 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001699}
1700
deadbeeffac06552015-11-25 11:26:01 -08001701rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001702 const std::string& kind,
1703 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001704 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001705 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1706 "Plan SdpSemantics. Please use AddTransceiver "
1707 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001708 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001709 if (IsClosed()) {
1710 return nullptr;
1711 }
Steve Anton4171afb2017-11-20 10:20:22 -08001712
Seth Hampson5b4f0752018-04-02 16:31:36 -07001713 // Internally we need to have one stream with Plan B semantics, so we
1714 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001715 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001716 if (stream_id.empty()) {
1717 stream_ids.push_back(rtc::CreateRandomUuid());
1718 RTC_LOG(LS_INFO)
1719 << "No stream_id specified for sender. Generated stream ID: "
1720 << stream_ids[0];
1721 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001722 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001723 }
1724
Steve Anton4171afb2017-11-20 10:20:22 -08001725 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001726 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001727 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001728 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001729 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001730 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001731 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001732 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001733 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001734 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001735 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001736 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001737 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001738 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001740 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001741 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001743 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001744 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001745 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001746
deadbeefe1f9d832016-01-14 15:35:42 -08001747 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001748}
1749
deadbeef70ab1a12015-09-28 16:53:55 -07001750std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1751 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001752 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001753 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001754 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001755 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001756 }
1757 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001758}
1759
Steve Anton4171afb2017-11-20 10:20:22 -08001760std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1761PeerConnection::GetSendersInternal() const {
1762 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1763 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001764 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001765 auto senders = transceiver->internal()->senders();
1766 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1767 }
1768 return all_senders;
1769}
1770
deadbeef70ab1a12015-09-28 16:53:55 -07001771std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1772PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001773 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001774 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001775 for (const auto& receiver : GetReceiversInternal()) {
1776 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001777 }
1778 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001779}
1780
Steve Anton4171afb2017-11-20 10:20:22 -08001781std::vector<
1782 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1783PeerConnection::GetReceiversInternal() const {
1784 std::vector<
1785 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1786 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001787 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001788 auto receivers = transceiver->internal()->receivers();
1789 all_receivers.insert(all_receivers.end(), receivers.begin(),
1790 receivers.end());
1791 }
1792 return all_receivers;
1793}
1794
Steve Anton9158ef62017-11-27 13:01:52 -08001795std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1796PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001797 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001798 RTC_CHECK(IsUnifiedPlan())
1799 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001800 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001801 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001802 all_transceivers.push_back(transceiver);
1803 }
1804 return all_transceivers;
1805}
1806
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001808 MediaStreamTrackInterface* track,
1809 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001810 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001811 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001812 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001813 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 return false;
1815 }
1816
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001817 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001818 // The StatsCollector is used to tell if a track is valid because it may
1819 // remember tracks that the PeerConnection previously removed.
1820 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001821 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1822 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001823 return false;
1824 }
Steve Antonad182762018-09-05 20:22:40 +00001825 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1826 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return true;
1828}
1829
hbos74e1a4f2016-09-15 23:33:01 -07001830void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001831 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001832 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001833 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001834 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001835 stats_collector_->GetStatsReport(callback);
1836}
1837
Henrik Boström1df1bf82018-03-20 13:24:20 +01001838void PeerConnection::GetStats(
1839 rtc::scoped_refptr<RtpSenderInterface> selector,
1840 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1841 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001842 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001843 RTC_DCHECK(callback);
1844 RTC_DCHECK(stats_collector_);
1845 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1846 if (selector) {
1847 for (const auto& proxy_transceiver : transceivers_) {
1848 for (const auto& proxy_sender :
1849 proxy_transceiver->internal()->senders()) {
1850 if (proxy_sender == selector) {
1851 internal_sender = proxy_sender->internal();
1852 break;
1853 }
1854 }
1855 if (internal_sender)
1856 break;
1857 }
1858 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001859 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001860 // belong to the PeerConnection (in Plan B, senders can be removed from the
1861 // PeerConnection). This means that "all the stats objects representing the
1862 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1863 // produces an empty stats report.
1864 stats_collector_->GetStatsReport(internal_sender, callback);
1865}
1866
1867void PeerConnection::GetStats(
1868 rtc::scoped_refptr<RtpReceiverInterface> selector,
1869 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1870 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001871 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001872 RTC_DCHECK(callback);
1873 RTC_DCHECK(stats_collector_);
1874 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1875 if (selector) {
1876 for (const auto& proxy_transceiver : transceivers_) {
1877 for (const auto& proxy_receiver :
1878 proxy_transceiver->internal()->receivers()) {
1879 if (proxy_receiver == selector) {
1880 internal_receiver = proxy_receiver->internal();
1881 break;
1882 }
1883 }
1884 if (internal_receiver)
1885 break;
1886 }
1887 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001888 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001889 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1890 // the PeerConnection). This means that "all the stats objects representing
1891 // the selector" is an empty set. Invoking GetStatsReport() with a null
1892 // selector produces an empty stats report.
1893 stats_collector_->GetStatsReport(internal_receiver, callback);
1894}
1895
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001897 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 return signaling_state_;
1899}
1900
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001901PeerConnectionInterface::IceConnectionState
1902PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001903 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 return ice_connection_state_;
1905}
1906
Alex Loiko9289eda2018-11-23 16:18:59 +00001907PeerConnectionInterface::IceConnectionState
1908PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001909 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001910 return standardized_ice_connection_state_;
1911}
1912
Jonas Olsson635474e2018-10-18 15:58:17 +02001913PeerConnectionInterface::PeerConnectionState
1914PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001916 return connection_state_;
1917}
1918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919PeerConnectionInterface::IceGatheringState
1920PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 return ice_gathering_state_;
1923}
1924
Yves Gerey665174f2018-06-19 15:03:05 +02001925rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 const std::string& label,
1927 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001928 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001929 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001930
deadbeefab9b2d12015-10-14 11:33:11 -07001931 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001932
kwibergd1fe2812016-04-27 06:47:29 -07001933 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001934 if (config) {
1935 internal_config.reset(new InternalDataChannelInit(*config));
1936 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001937 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001938 InternalCreateDataChannel(label, internal_config.get()));
1939 if (!channel.get()) {
1940 return nullptr;
1941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001943 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1944 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001945 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001946 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001947 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001948 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 return DataChannelProxy::Create(signaling_thread(), channel.get());
1950}
1951
1952void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001953 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001954 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001955 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
nisse7ce109a2017-01-31 00:57:56 -08001957 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001958 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001959 return;
1960 }
deadbeefab9b2d12015-10-14 11:33:11 -07001961
Steve Anton8d3444d2017-10-20 15:30:51 -07001962 if (IsClosed()) {
1963 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001965 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001966 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001967 return;
1968 }
1969
zhihuang1c378ed2017-08-17 14:10:50 -07001970 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001971 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001973 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001974 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001975 return;
1976 }
1977
Steve Anton22da89f2018-01-25 13:58:07 -08001978 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1979 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1980 if (IsUnifiedPlan()) {
1981 RTCError error = HandleLegacyOfferOptions(options);
1982 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001983 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001984 return;
1985 }
1986 }
1987
zhihuang1c378ed2017-08-17 14:10:50 -07001988 cricket::MediaSessionOptions session_options;
1989 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001990 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991}
1992
Steve Anton22da89f2018-01-25 13:58:07 -08001993RTCError PeerConnection::HandleLegacyOfferOptions(
1994 const RTCOfferAnswerOptions& options) {
1995 RTC_DCHECK(IsUnifiedPlan());
1996
1997 if (options.offer_to_receive_audio == 0) {
1998 RemoveRecvDirectionFromReceivingTransceiversOfType(
1999 cricket::MEDIA_TYPE_AUDIO);
2000 } else if (options.offer_to_receive_audio == 1) {
2001 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2002 } else if (options.offer_to_receive_audio > 1) {
2003 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2004 "offer_to_receive_audio > 1 is not supported.");
2005 }
2006
2007 if (options.offer_to_receive_video == 0) {
2008 RemoveRecvDirectionFromReceivingTransceiversOfType(
2009 cricket::MEDIA_TYPE_VIDEO);
2010 } else if (options.offer_to_receive_video == 1) {
2011 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2012 } else if (options.offer_to_receive_video > 1) {
2013 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2014 "offer_to_receive_video > 1 is not supported.");
2015 }
2016
2017 return RTCError::OK();
2018}
2019
2020void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2021 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002022 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002023 RtpTransceiverDirection new_direction =
2024 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2025 if (new_direction != transceiver->direction()) {
2026 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2027 << " transceiver (MID="
2028 << transceiver->mid().value_or("<not set>") << ") from "
2029 << RtpTransceiverDirectionToString(
2030 transceiver->direction())
2031 << " to "
2032 << RtpTransceiverDirectionToString(new_direction)
2033 << " since CreateOffer specified offer_to_receive=0";
2034 transceiver->internal()->set_direction(new_direction);
2035 }
Steve Anton22da89f2018-01-25 13:58:07 -08002036 }
2037}
2038
2039void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2040 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002041 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002042 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002043 RTC_LOG(LS_INFO)
2044 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2045 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002046 RtpTransceiverInit init;
2047 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002048 AddTransceiver(media_type, nullptr, init,
2049 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002050 }
2051}
2052
2053std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2054PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2055 std::vector<
2056 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2057 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002058 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002059 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002060 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2061 receiving_transceivers.push_back(transceiver);
2062 }
2063 }
2064 return receiving_transceivers;
2065}
2066
htaa2a49d92016-03-04 02:51:39 -08002067void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2068 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002069 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002070 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002071 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002072 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002073 return;
2074 }
2075
Steve Antondffead82018-02-06 10:31:29 -08002076 if (!(signaling_state_ == kHaveRemoteOffer ||
2077 signaling_state_ == kHaveLocalPrAnswer)) {
2078 std::string error =
2079 "PeerConnection cannot create an answer in a state other than "
2080 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002081 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002082 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002083 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002084 return;
2085 }
2086
Steve Antondffead82018-02-06 10:31:29 -08002087 // The remote description should be set if we're in the right state.
2088 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002089
Steve Anton22da89f2018-01-25 13:58:07 -08002090 if (IsUnifiedPlan()) {
2091 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2092 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2093 "supported with Unified Plan semantics. Use the "
2094 "RtpTransceiver API instead.";
2095 }
2096 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2097 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2098 "supported with Unified Plan semantics. Use the "
2099 "RtpTransceiver API instead.";
2100 }
2101 }
2102
htaa2a49d92016-03-04 02:51:39 -08002103 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002104 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002105
Steve Antond25da372017-11-06 14:50:29 -08002106 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107}
2108
2109void PeerConnection::SetLocalDescription(
2110 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002111 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002112 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002113 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002114
Steve Anton80dd7b52018-02-16 17:08:42 -08002115 // The SetLocalDescription contract is that we take ownership of the session
2116 // description regardless of the outcome, so wrap it in a unique_ptr right
2117 // away. Ideally, SetLocalDescription's signature will be changed to take the
2118 // description as a unique_ptr argument to formalize this agreement.
2119 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2120
nisse7ce109a2017-01-31 00:57:56 -08002121 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002122 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123 return;
2124 }
Steve Anton8a006912017-12-04 15:25:56 -08002125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002127 PostSetSessionDescriptionFailure(
2128 observer,
2129 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 return;
2131 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002132
Steve Anton80dd7b52018-02-16 17:08:42 -08002133 // If a session error has occurred the PeerConnection is in a possibly
2134 // inconsistent state so fail right away.
2135 if (session_error() != SessionError::kNone) {
2136 std::string error_message = GetSessionErrorMsg();
2137 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002138 PostSetSessionDescriptionFailure(
2139 observer,
2140 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002141 return;
2142 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002143
Steve Anton80dd7b52018-02-16 17:08:42 -08002144 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2145 if (!error.ok()) {
2146 std::string error_message = GetSetDescriptionErrorMessage(
2147 cricket::CS_LOCAL, desc->GetType(), error);
2148 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002149 PostSetSessionDescriptionFailure(
2150 observer,
2151 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002152 return;
2153 }
2154
2155 // Grab the description type before moving ownership to ApplyLocalDescription,
2156 // which may destroy it before returning.
2157 const SdpType type = desc->GetType();
2158
2159 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002160 // |desc| may be destroyed at this point.
2161
2162 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002163 // If ApplyLocalDescription fails, the PeerConnection could be in an
2164 // inconsistent state, so act conservatively here and set the session error
2165 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2166 SetSessionError(SessionError::kContent, error.message());
2167 std::string error_message =
2168 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2169 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002170 PostSetSessionDescriptionFailure(
2171 observer,
2172 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002173 return;
2174 }
Steve Anton8a006912017-12-04 15:25:56 -08002175 RTC_DCHECK(local_description());
2176
2177 PostSetSessionDescriptionSuccess(observer);
2178
Steve Antonad182762018-09-05 20:22:40 +00002179 // MaybeStartGathering needs to be called after posting
2180 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2181 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002182 transport_controller_->MaybeStartGathering();
2183
Steve Antona3a92c22017-12-07 10:27:41 -08002184 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002185 // TODO(deadbeef): We already had to hop to the network thread for
2186 // MaybeStartGathering...
2187 network_thread()->Invoke<void>(
2188 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2189 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002190 // Make UMA notes about what was agreed to.
2191 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002192 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002193
2194 if (IsUnifiedPlan()) {
2195 bool was_negotiation_needed = is_negotiation_needed_;
2196 UpdateNegotiationNeeded();
2197 if (signaling_state() == kStable && was_negotiation_needed &&
2198 is_negotiation_needed_) {
2199 Observer()->OnRenegotiationNeeded();
2200 }
2201 }
2202
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002203 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002204}
2205
2206RTCError PeerConnection::ApplyLocalDescription(
2207 std::unique_ptr<SessionDescriptionInterface> desc) {
2208 RTC_DCHECK_RUN_ON(signaling_thread());
2209 RTC_DCHECK(desc);
2210
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 // Update stats here so that we have the most recent stats for tracks and
2212 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002213 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Take a reference to the old local description since it's used below to
2216 // compare against the new local description. When setting the new local
2217 // description, grab ownership of the replaced session description in case it
2218 // is the same as |old_local_description|, to keep it alive for the duration
2219 // of the method.
2220 const SessionDescriptionInterface* old_local_description =
2221 local_description();
2222 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002223 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002224 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002225 replaced_local_description = pending_local_description_
2226 ? std::move(pending_local_description_)
2227 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002228 current_local_description_ = std::move(desc);
2229 pending_local_description_ = nullptr;
2230 current_remote_description_ = std::move(pending_remote_description_);
2231 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002232 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002233 pending_local_description_ = std::move(desc);
2234 }
2235 // The session description to apply now must be accessed by
2236 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002237 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002238
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002239 // Report statistics about any use of simulcast.
2240 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2241 *local_description()->description());
2242
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002243 if (!is_caller_) {
2244 if (remote_description()) {
2245 // Remote description was applied first, so this PC is the callee.
2246 is_caller_ = false;
2247 } else {
2248 // Local description is applied first, so this PC is the caller.
2249 is_caller_ = true;
2250 }
2251 }
2252
Zhi Huange830e682018-03-30 10:48:35 -07002253 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2254 if (!error.ok()) {
2255 return error;
2256 }
2257
Steve Antondcc3c022017-12-22 16:02:54 -08002258 if (IsUnifiedPlan()) {
2259 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002260 cricket::CS_LOCAL, *local_description(), old_local_description,
2261 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002262 if (!error.ok()) {
2263 return error;
2264 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002265 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2266 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002267 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002268 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2269 // Note that code paths that don't set MID won't be able to use
2270 // information about DTLS transports.
2271 if (transceiver->mid()) {
2272 auto dtls_transport =
2273 LookupDtlsTransportByMidInternal(*transceiver->mid());
2274 transceiver->internal()->sender_internal()->set_transport(
2275 dtls_transport);
2276 transceiver->internal()->receiver_internal()->set_transport(
2277 dtls_transport);
2278 }
2279
Steve Antondcc3c022017-12-22 16:02:54 -08002280 const ContentInfo* content =
2281 FindMediaSectionForTransceiver(transceiver, local_description());
2282 if (!content) {
2283 continue;
2284 }
2285 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002286 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2287 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002288 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002289 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2290 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2291 // "recvonly", process the removal of a remote track for the media
2292 // description, given transceiver, removeList, and muteTracks.
2293 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2294 (transceiver->internal()->fired_direction() &&
2295 RtpTransceiverDirectionHasRecv(
2296 *transceiver->internal()->fired_direction()))) {
2297 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2298 &removed_streams);
2299 }
2300 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2301 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002302 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002303 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002304 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002305 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002306 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002307 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002308 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002309 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002310 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002311 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002312 }
2313 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002314 // Media channels will be created only when offer is set. These may use new
2315 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002316 if (type == SdpType::kOffer) {
2317 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2318 // description is applied. Restore back to old description.
2319 RTCError error = CreateChannels(*local_description()->description());
2320 if (!error.ok()) {
2321 return error;
2322 }
2323 }
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // Remove unused channels if MediaContentDescription is rejected.
2325 RemoveUnusedChannels(local_description()->description());
2326 }
Steve Anton8a006912017-12-04 15:25:56 -08002327
Zhi Huange830e682018-03-30 10:48:35 -07002328 error = UpdateSessionState(type, cricket::CS_LOCAL,
2329 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002330 if (!error.ok()) {
2331 return error;
2332 }
Steve Antondcc3c022017-12-22 16:02:54 -08002333
Steve Anton8a006912017-12-04 15:25:56 -08002334 if (remote_description()) {
2335 // Now that we have a local description, we can push down remote candidates.
2336 UseCandidatesInSessionDescription(remote_description());
2337 }
2338
2339 pending_ice_restarts_.clear();
2340 if (session_error() != SessionError::kNone) {
2341 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2342 }
2343
deadbeefab9b2d12015-10-14 11:33:11 -07002344 // If setting the description decided our SSL role, allocate any necessary
2345 // SCTP sids.
2346 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002347 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002348 AllocateSctpSids(role);
2349 }
2350
Steve Antond3679212018-01-17 17:41:02 -08002351 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002352 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002353 const ContentInfo* content =
2354 FindMediaSectionForTransceiver(transceiver, local_description());
2355 if (!content) {
2356 continue;
2357 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002358 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2359 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002360 // 0 is a special value meaning "this sender has no associated send
2361 // stream". Need to call this so the sender won't attempt to configure
2362 // a no longer existing stream and run into DCHECKs in the lower
2363 // layers.
2364 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002365 } else {
2366 // Get the StreamParams from the channel which could generate SSRCs.
2367 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002368 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002369 streams[0].stream_ids());
2370 transceiver->internal()->sender_internal()->SetSsrc(
2371 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002372 }
2373 }
2374 } else {
2375 // Plan B semantics.
2376
Steve Antondcc3c022017-12-22 16:02:54 -08002377 // Update state and SSRC of local MediaStreams and DataChannels based on the
2378 // local session description.
2379 const cricket::ContentInfo* audio_content =
2380 GetFirstAudioContent(local_description()->description());
2381 if (audio_content) {
2382 if (audio_content->rejected) {
2383 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2384 } else {
2385 const cricket::AudioContentDescription* audio_desc =
2386 audio_content->media_description()->as_audio();
2387 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2388 }
deadbeeffaac4972015-11-12 15:33:07 -08002389 }
deadbeefab9b2d12015-10-14 11:33:11 -07002390
Steve Antondcc3c022017-12-22 16:02:54 -08002391 const cricket::ContentInfo* video_content =
2392 GetFirstVideoContent(local_description()->description());
2393 if (video_content) {
2394 if (video_content->rejected) {
2395 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2396 } else {
2397 const cricket::VideoContentDescription* video_desc =
2398 video_content->media_description()->as_video();
2399 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2400 }
deadbeeffaac4972015-11-12 15:33:07 -08002401 }
deadbeefab9b2d12015-10-14 11:33:11 -07002402 }
2403
2404 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002405 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002406 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002407 const cricket::RtpDataContentDescription* rtp_data_desc =
2408 data_content->media_description()->as_rtp_data();
2409 // rtp_data_desc will be null if this is an SCTP description.
2410 if (rtp_data_desc) {
2411 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002412 }
2413 }
2414
Steve Anton8a006912017-12-04 15:25:56 -08002415 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416}
2417
Steve Anton06817cd2018-12-18 15:55:30 -08002418// The SDP parser used to populate these values by default for the 'content
2419// name' if an a=mid line was absent.
2420static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2421 switch (media_type) {
2422 case cricket::MEDIA_TYPE_AUDIO:
2423 return cricket::CN_AUDIO;
2424 case cricket::MEDIA_TYPE_VIDEO:
2425 return cricket::CN_VIDEO;
2426 case cricket::MEDIA_TYPE_DATA:
2427 return cricket::CN_DATA;
2428 }
2429 RTC_NOTREACHED();
2430 return "";
2431}
2432
2433void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002434 cricket::SessionDescription* new_remote_description) {
2435 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002436 const cricket::ContentInfos& local_contents =
2437 (local_description() ? local_description()->description()->contents()
2438 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002439 const cricket::ContentInfos& remote_contents =
2440 (remote_description() ? remote_description()->description()->contents()
2441 : cricket::ContentInfos());
2442 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2443 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002444 if (!content.name.empty()) {
2445 continue;
2446 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002447 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002448 absl::string_view source_explanation;
2449 if (IsUnifiedPlan()) {
2450 if (i < local_contents.size()) {
2451 new_mid = local_contents[i].name;
2452 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002453 } else if (i < remote_contents.size()) {
2454 new_mid = remote_contents[i].name;
2455 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002456 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002457 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002458 source_explanation = "generated just now";
2459 }
2460 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002461 new_mid = std::string(
2462 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002463 source_explanation = "to match pre-existing behavior";
2464 }
Steve Antond7180cc2019-02-07 10:44:53 -08002465 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002466 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002467 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002468 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2469 << " is missing an a=mid line. Filling in the value '"
2470 << new_mid << "' " << source_explanation << ".";
2471 }
2472}
2473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002475 SetSessionDescriptionObserver* observer,
2476 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002477 SetRemoteDescription(
2478 std::unique_ptr<SessionDescriptionInterface>(desc),
2479 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2480 new SetRemoteDescriptionObserverAdapter(this, observer)));
2481}
2482
2483void PeerConnection::SetRemoteDescription(
2484 std::unique_ptr<SessionDescriptionInterface> desc,
2485 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002486 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002487 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002488
nisse7ce109a2017-01-31 00:57:56 -08002489 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002490 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002491 return;
2492 }
Steve Anton8a006912017-12-04 15:25:56 -08002493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002495 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002496 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 return;
2498 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002499
Steve Anton80dd7b52018-02-16 17:08:42 -08002500 // If a session error has occurred the PeerConnection is in a possibly
2501 // inconsistent state so fail right away.
2502 if (session_error() != SessionError::kNone) {
2503 std::string error_message = GetSessionErrorMsg();
2504 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2505 observer->OnSetRemoteDescriptionComplete(
2506 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2507 return;
2508 }
Steve Anton71439a62018-02-15 11:53:06 -08002509
Steve Antonba42e992018-04-09 14:10:01 -07002510 if (desc->GetType() == SdpType::kOffer) {
2511 // Report to UMA the format of the received offer.
2512 ReportSdpFormatReceived(*desc);
2513 }
2514
Steve Anton06817cd2018-12-18 15:55:30 -08002515 // Handle remote descriptions missing a=mid lines for interop with legacy end
2516 // points.
2517 FillInMissingRemoteMids(desc->description());
2518
Steve Anton80dd7b52018-02-16 17:08:42 -08002519 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002520 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002521 std::string error_message = GetSetDescriptionErrorMessage(
2522 cricket::CS_REMOTE, desc->GetType(), error);
2523 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002524 observer->OnSetRemoteDescriptionComplete(
2525 RTCError(error.type(), std::move(error_message)));
2526 return;
2527 }
Steve Anton71439a62018-02-15 11:53:06 -08002528
Steve Anton80dd7b52018-02-16 17:08:42 -08002529 // Grab the description type before moving ownership to
2530 // ApplyRemoteDescription, which may destroy it before returning.
2531 const SdpType type = desc->GetType();
2532
2533 error = ApplyRemoteDescription(std::move(desc));
2534 // |desc| may be destroyed at this point.
2535
2536 if (!error.ok()) {
2537 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2538 // inconsistent state, so act conservatively here and set the session error
2539 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2540 SetSessionError(SessionError::kContent, error.message());
2541 std::string error_message =
2542 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2543 RTC_LOG(LS_ERROR) << error_message;
2544 observer->OnSetRemoteDescriptionComplete(
2545 RTCError(error.type(), std::move(error_message)));
2546 return;
2547 }
2548 RTC_DCHECK(remote_description());
2549
2550 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002551 // TODO(deadbeef): We already had to hop to the network thread for
2552 // MaybeStartGathering...
2553 network_thread()->Invoke<void>(
2554 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2555 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002556 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002557 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002558 }
2559
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002560 if (IsUnifiedPlan()) {
2561 bool was_negotiation_needed = is_negotiation_needed_;
2562 UpdateNegotiationNeeded();
2563 if (signaling_state() == kStable && was_negotiation_needed &&
2564 is_negotiation_needed_) {
2565 Observer()->OnRenegotiationNeeded();
2566 }
2567 }
2568
Steve Anton8a006912017-12-04 15:25:56 -08002569 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002570 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002571}
2572
2573RTCError PeerConnection::ApplyRemoteDescription(
2574 std::unique_ptr<SessionDescriptionInterface> desc) {
2575 RTC_DCHECK_RUN_ON(signaling_thread());
2576 RTC_DCHECK(desc);
2577
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578 // Update stats here so that we have the most recent stats for tracks and
2579 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002580 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002581
Steve Antondcc3c022017-12-22 16:02:54 -08002582 // Take a reference to the old remote description since it's used below to
2583 // compare against the new remote description. When setting the new remote
2584 // description, grab ownership of the replaced session description in case it
2585 // is the same as |old_remote_description|, to keep it alive for the duration
2586 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002587 const SessionDescriptionInterface* old_remote_description =
2588 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002589 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002590 SdpType type = desc->GetType();
2591 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002592 replaced_remote_description = pending_remote_description_
2593 ? std::move(pending_remote_description_)
2594 : std::move(current_remote_description_);
2595 current_remote_description_ = std::move(desc);
2596 pending_remote_description_ = nullptr;
2597 current_local_description_ = std::move(pending_local_description_);
2598 } else {
2599 replaced_remote_description = std::move(pending_remote_description_);
2600 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 }
Steve Anton8a006912017-12-04 15:25:56 -08002602 // The session description to apply now must be accessed by
2603 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002604 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002605
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002606 // Report statistics about any use of simulcast.
2607 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2608 *remote_description()->description());
2609
Zhi Huange830e682018-03-30 10:48:35 -07002610 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2611 if (!error.ok()) {
2612 return error;
2613 }
Steve Anton8a006912017-12-04 15:25:56 -08002614 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002615 if (IsUnifiedPlan()) {
2616 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002617 cricket::CS_REMOTE, *remote_description(), local_description(),
2618 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002619 if (!error.ok()) {
2620 return error;
2621 }
Steve Antondcc3c022017-12-22 16:02:54 -08002622 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002623 // Media channels will be created only when offer is set. These may use new
2624 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002625 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002626 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002627 // description is applied. Restore back to old description.
2628 RTCError error = CreateChannels(*remote_description()->description());
2629 if (!error.ok()) {
2630 return error;
2631 }
2632 }
Steve Antondcc3c022017-12-22 16:02:54 -08002633 // Remove unused channels if MediaContentDescription is rejected.
2634 RemoveUnusedChannels(remote_description()->description());
2635 }
Steve Anton8a006912017-12-04 15:25:56 -08002636
Zhi Huange830e682018-03-30 10:48:35 -07002637 // NOTE: Candidates allocation will be initiated only when
2638 // SetLocalDescription is called.
2639 error = UpdateSessionState(type, cricket::CS_REMOTE,
2640 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002641 if (!error.ok()) {
2642 return error;
2643 }
2644
2645 if (local_description() &&
2646 !UseCandidatesInSessionDescription(remote_description())) {
2647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2648 }
2649
2650 if (old_remote_description) {
2651 for (const cricket::ContentInfo& content :
2652 old_remote_description->description()->contents()) {
2653 // Check if this new SessionDescription contains new ICE ufrag and
2654 // password that indicates the remote peer requests an ICE restart.
2655 // TODO(deadbeef): When we start storing both the current and pending
2656 // remote description, this should reset pending_ice_restarts and compare
2657 // against the current description.
2658 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2659 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002660 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002661 pending_ice_restarts_.insert(content.name);
2662 }
2663 } else {
2664 // We retain all received candidates only if ICE is not restarted.
2665 // When ICE is restarted, all previous candidates belong to an old
2666 // generation and should not be kept.
2667 // TODO(deadbeef): This goes against the W3C spec which says the remote
2668 // description should only contain candidates from the last set remote
2669 // description plus any candidates added since then. We should remove
2670 // this once we're sure it won't break anything.
2671 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2672 old_remote_description, content.name, mutable_remote_description());
2673 }
2674 }
2675 }
2676
2677 if (session_error() != SessionError::kNone) {
2678 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2679 }
2680
2681 // Set the the ICE connection state to connecting since the connection may
2682 // become writable with peer reflexive candidates before any remote candidate
2683 // is signaled.
2684 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2685 // is to have a new signal the indicates a change in checking state from the
2686 // transport and expose a new checking() member from transport that can be
2687 // read to determine the current checking state. The existing SignalConnecting
2688 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002689 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002690 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002691 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2692 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2693 }
2694
deadbeefab9b2d12015-10-14 11:33:11 -07002695 // If setting the description decided our SSL role, allocate any necessary
2696 // SCTP sids.
2697 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002698 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002699 AllocateSctpSids(role);
2700 }
2701
Steve Antondcc3c022017-12-22 16:02:54 -08002702 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002703 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002704 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002705 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002706 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002707 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002708 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002709 const ContentInfo* content =
2710 FindMediaSectionForTransceiver(transceiver, remote_description());
2711 if (!content) {
2712 continue;
2713 }
2714 const MediaContentDescription* media_desc = content->media_description();
2715 RtpTransceiverDirection local_direction =
2716 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002717 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2718 // RTCSessionDescription: Set the associated remote streams given
2719 // transceiver.[[Receiver]], msids, addList, and removeList".
2720 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2721 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2722 std::vector<std::string> stream_ids;
2723 if (!media_desc->streams().empty()) {
2724 // The remote description has signaled the stream IDs.
2725 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002726 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002727 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2728 << " (" << GetStreamIdsString(stream_ids) << ").";
2729 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2730 stream_ids, &added_streams,
2731 &removed_streams);
2732 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2733 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2734 // and transceiver's current direction is neither sendrecv nor recvonly,
2735 // process the addition of a remote track for the media description.
2736 if (!transceiver->fired_direction() ||
2737 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2738 RTC_LOG(LS_INFO)
2739 << "Processing the addition of a remote track for MID="
2740 << content->name << ".";
2741 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002742 }
Steve Antondcc3c022017-12-22 16:02:54 -08002743 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002744 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002745 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2746 // removal of a remote track for the media description, given transceiver,
2747 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002748 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002749 (transceiver->fired_direction() &&
2750 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2751 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2752 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002753 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002754 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002755 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002756 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002757 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002758 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002759 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002760 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002761 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2763 if (transceiver->mid()) {
2764 auto dtls_transport =
2765 LookupDtlsTransportByMidInternal(*transceiver->mid());
2766 transceiver->internal()->sender_internal()->set_transport(
2767 dtls_transport);
2768 transceiver->internal()->receiver_internal()->set_transport(
2769 dtls_transport);
2770 }
Steve Antondcc3c022017-12-22 16:02:54 -08002771 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002772 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002773 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002774 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002775 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2776 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002777 transceiver->Stop();
2778 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002779 if (!content->rejected &&
2780 RtpTransceiverDirectionHasRecv(local_direction)) {
2781 // Set ssrc to 0 in the case of an unsignalled ssrc.
2782 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002783 if (!media_desc->streams().empty() &&
2784 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002785 ssrc = media_desc->streams()[0].first_ssrc();
2786 }
2787 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002788 }
Steve Antondcc3c022017-12-22 16:02:54 -08002789 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002790 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002791 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002792 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002793 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002794 observer->OnTrack(transceiver);
2795 observer->OnAddTrack(transceiver->receiver(),
2796 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002797 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002798 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002799 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002800 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002801 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002802 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002803 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002804 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002805 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002806 }
Steve Antondcc3c022017-12-22 16:02:54 -08002807 }
2808
Henrik Boströmfdb92012017-11-09 19:55:44 +01002809 const cricket::ContentInfo* audio_content =
2810 GetFirstAudioContent(remote_description()->description());
2811 const cricket::ContentInfo* video_content =
2812 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002813 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002814 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002815 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002816 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002817 const cricket::RtpDataContentDescription* rtp_data_desc =
2818 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002819
2820 // Check if the descriptions include streams, just in case the peer supports
2821 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002822 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002823 (audio_desc && !audio_desc->streams().empty()) ||
2824 (video_desc && !video_desc->streams().empty())) {
2825 remote_peer_supports_msid_ = true;
2826 }
deadbeefab9b2d12015-10-14 11:33:11 -07002827
2828 // We wait to signal new streams until we finish processing the description,
2829 // since only at that point will new streams have all their tracks.
2830 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2831
Steve Antondcc3c022017-12-22 16:02:54 -08002832 if (!IsUnifiedPlan()) {
2833 // TODO(steveanton): When removing RTP senders/receivers in response to a
2834 // rejected media section, there is some cleanup logic that expects the
2835 // voice/ video channel to still be set. But in this method the voice/video
2836 // channel would have been destroyed by the SetRemoteDescription caller
2837 // above so the cleanup that relies on them fails to run. The RemoveSenders
2838 // calls should be moved to right before the DestroyChannel calls to fix
2839 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002840
Steve Antondcc3c022017-12-22 16:02:54 -08002841 // Find all audio rtp streams and create corresponding remote AudioTracks
2842 // and MediaStreams.
2843 if (audio_content) {
2844 if (audio_content->rejected) {
2845 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2846 } else {
2847 bool default_audio_track_needed =
2848 !remote_peer_supports_msid_ &&
2849 RtpTransceiverDirectionHasSend(audio_desc->direction());
2850 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2851 default_audio_track_needed, audio_desc->type(),
2852 new_streams);
2853 }
deadbeeffaac4972015-11-12 15:33:07 -08002854 }
deadbeefab9b2d12015-10-14 11:33:11 -07002855
Steve Antondcc3c022017-12-22 16:02:54 -08002856 // Find all video rtp streams and create corresponding remote VideoTracks
2857 // and MediaStreams.
2858 if (video_content) {
2859 if (video_content->rejected) {
2860 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2861 } else {
2862 bool default_video_track_needed =
2863 !remote_peer_supports_msid_ &&
2864 RtpTransceiverDirectionHasSend(video_desc->direction());
2865 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2866 default_video_track_needed, video_desc->type(),
2867 new_streams);
2868 }
deadbeeffaac4972015-11-12 15:33:07 -08002869 }
deadbeefab9b2d12015-10-14 11:33:11 -07002870
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002871 // If this is an RTP data transport, update the DataChannels with the
2872 // information from the remote peer.
2873 if (rtp_data_desc) {
2874 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002875 }
deadbeefab9b2d12015-10-14 11:33:11 -07002876
Steve Antondcc3c022017-12-22 16:02:54 -08002877 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002878 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002879 for (size_t i = 0; i < new_streams->count(); ++i) {
2880 MediaStreamInterface* new_stream = new_streams->at(i);
2881 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002882 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002883 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2884 }
deadbeefab9b2d12015-10-14 11:33:11 -07002885
Steve Antondcc3c022017-12-22 16:02:54 -08002886 UpdateEndedRemoteMediaStreams();
2887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888
Steve Anton8a006912017-12-04 15:25:56 -08002889 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002890}
2891
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002892void PeerConnection::SetAssociatedRemoteStreams(
2893 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2894 const std::vector<std::string>& stream_ids,
2895 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2896 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2897 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2898 for (const std::string& stream_id : stream_ids) {
2899 rtc::scoped_refptr<MediaStreamInterface> stream =
2900 remote_streams_->find(stream_id);
2901 if (!stream) {
2902 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2903 MediaStream::Create(stream_id));
2904 remote_streams_->AddStream(stream);
2905 added_streams->push_back(stream);
2906 }
2907 media_streams.push_back(stream);
2908 }
2909 // Special case: "a=msid" missing, use random stream ID.
2910 if (media_streams.empty() &&
2911 !(remote_description()->description()->msid_signaling() &
2912 cricket::kMsidSignalingMediaSection)) {
2913 if (!missing_msid_default_stream_) {
2914 missing_msid_default_stream_ = MediaStreamProxy::Create(
2915 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2916 added_streams->push_back(missing_msid_default_stream_);
2917 }
2918 media_streams.push_back(missing_msid_default_stream_);
2919 }
2920 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2921 receiver->streams();
2922 // SetStreams() will add/remove the receiver's track to/from the streams. This
2923 // differs from the spec - the spec uses an "addList" and "removeList" to
2924 // update the stream-track relationships in a later step. We do this earlier,
2925 // changing the order of things, but the end-result is the same.
2926 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2927 // instead. https://crbug.com/webrtc/9480
2928 receiver->SetStreams(media_streams);
2929 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2930}
2931
Steve Anton0f5400a2018-07-17 14:25:36 -07002932void PeerConnection::ProcessRemovalOfRemoteTrack(
2933 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2934 transceiver,
2935 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2936 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2937 RTC_DCHECK(transceiver->mid());
2938 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2939 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002940 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002941 transceiver->internal()->receiver_internal()->streams();
2942 // This will remove the remote track from the streams.
2943 transceiver->internal()->receiver_internal()->set_stream_ids({});
2944 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002945 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2946}
2947
2948void PeerConnection::RemoveRemoteStreamsIfEmpty(
2949 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2950 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2951 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2952 // streams, see if the stream was removed by checking if this was the last
2953 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002954 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002955 if (remote_stream->GetAudioTracks().empty() &&
2956 remote_stream->GetVideoTracks().empty()) {
2957 remote_streams_->RemoveStream(remote_stream);
2958 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002959 }
2960 }
2961}
2962
Steve Antondcc3c022017-12-22 16:02:54 -08002963RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2964 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002965 const SessionDescriptionInterface& new_session,
2966 const SessionDescriptionInterface* old_local_description,
2967 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002968 RTC_DCHECK(IsUnifiedPlan());
2969
Steve Anton7464fca2018-01-19 11:10:37 -08002970 const cricket::ContentGroup* bundle_group = nullptr;
2971 if (new_session.GetType() == SdpType::kOffer) {
2972 auto bundle_group_or_error =
2973 GetEarlyBundleGroup(*new_session.description());
2974 if (!bundle_group_or_error.ok()) {
2975 return bundle_group_or_error.MoveError();
2976 }
2977 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002978 }
Steve Antondcc3c022017-12-22 16:02:54 -08002979
Steve Antondcc3c022017-12-22 16:02:54 -08002980 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002981 for (size_t i = 0; i < new_contents.size(); ++i) {
2982 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002983 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002984 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002985 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2986 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002987 const cricket::ContentInfo* old_local_content = nullptr;
2988 if (old_local_description &&
2989 i < old_local_description->description()->contents().size()) {
2990 old_local_content =
2991 &old_local_description->description()->contents()[i];
2992 }
2993 const cricket::ContentInfo* old_remote_content = nullptr;
2994 if (old_remote_description &&
2995 i < old_remote_description->description()->contents().size()) {
2996 old_remote_content =
2997 &old_remote_description->description()->contents()[i];
2998 }
Steve Antondcc3c022017-12-22 16:02:54 -08002999 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003000 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3001 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003002 if (!transceiver_or_error.ok()) {
3003 return transceiver_or_error.MoveError();
3004 }
3005 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003006 RTCError error =
3007 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3008 if (!error.ok()) {
3009 return error;
3010 }
3011 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003012 if (GetDataMid() && new_content.name != *GetDataMid()) {
3013 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003014 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3015 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003016 continue;
3017 }
3018 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3019 if (!error.ok()) {
3020 return error;
3021 }
Steve Antondcc3c022017-12-22 16:02:54 -08003022 } else {
3023 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3024 "Unknown section type.");
3025 }
3026 }
3027
3028 return RTCError::OK();
3029}
3030
3031RTCError PeerConnection::UpdateTransceiverChannel(
3032 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3033 transceiver,
3034 const cricket::ContentInfo& content,
3035 const cricket::ContentGroup* bundle_group) {
3036 RTC_DCHECK(IsUnifiedPlan());
3037 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003038 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003039 if (content.rejected) {
3040 if (channel) {
3041 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003042 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003043 }
3044 } else {
3045 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003046 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003047 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003048 } else {
Steve Anton69470252018-02-09 11:43:08 -08003049 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003050 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003051 }
3052 if (!channel) {
3053 LOG_AND_RETURN_ERROR(
3054 RTCErrorType::INTERNAL_ERROR,
3055 "Failed to create channel for mid=" + content.name);
3056 }
3057 transceiver->internal()->SetChannel(channel);
3058 }
3059 }
3060 return RTCError::OK();
3061}
3062
Steve Antonfa2260d2017-12-28 16:38:23 -08003063RTCError PeerConnection::UpdateDataChannel(
3064 cricket::ContentSource source,
3065 const cricket::ContentInfo& content,
3066 const cricket::ContentGroup* bundle_group) {
3067 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003068 // If data channels are disabled, ignore this media section. CreateAnswer
3069 // will take care of rejecting it.
3070 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003071 }
3072 if (content.rejected) {
3073 DestroyDataChannel();
3074 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003075 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003076 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003077 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3078 "Failed to create data channel.");
3079 }
3080 }
3081 if (source == cricket::CS_REMOTE) {
3082 const MediaContentDescription* data_desc = content.media_description();
3083 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3084 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3085 }
3086 }
3087 }
3088 return RTCError::OK();
3089}
3090
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003091// This method will extract any send encodings that were sent by the remote
3092// connection. This is currently only relevant for Simulcast scenario (where
3093// the number of layers may be communicated by the server).
3094static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3095 const MediaContentDescription& desc) {
3096 if (!desc.HasSimulcast()) {
3097 return {};
3098 }
3099 std::vector<RtpEncodingParameters> result;
3100 const SimulcastDescription& simulcast = desc.simulcast_description();
3101
3102 // This is a remote description, the parameters we are after should appear
3103 // as receive streams.
3104 for (const auto& alternatives : simulcast.receive_layers()) {
3105 RTC_DCHECK(!alternatives.empty());
3106 // There is currently no way to specify or choose from alternatives.
3107 // We will always use the first alternative, which is the most preferred.
3108 const SimulcastLayer& layer = alternatives[0];
3109 RtpEncodingParameters parameters;
3110 parameters.rid = layer.rid;
3111 parameters.active = !layer.is_paused;
3112 result.push_back(parameters);
3113 }
3114
3115 return result;
3116}
3117
3118static RTCError UpdateSimulcastLayerStatusInSender(
3119 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003120 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003121 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003122 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003123 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003124
3125 // The simulcast envelope cannot be changed, only the status of the streams.
3126 // So we will iterate over the send encodings rather than the layers.
3127 for (RtpEncodingParameters& encoding : parameters.encodings) {
3128 auto iter = std::find_if(layers.begin(), layers.end(),
3129 [&encoding](const SimulcastLayer& layer) {
3130 return layer.rid == encoding.rid;
3131 });
3132 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003133 if (iter == layers.end()) {
3134 disabled_layers.push_back(encoding.rid);
3135 continue;
3136 }
3137
3138 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003139 }
3140
Amit Hilbuch619b2942019-02-26 15:55:19 -08003141 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003142 if (result.ok()) {
3143 result = sender->DisableEncodingLayers(disabled_layers);
3144 }
3145
3146 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003147}
3148
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003149static bool SimulcastIsRejected(
3150 const ContentInfo* local_content,
3151 const MediaContentDescription& answer_media_desc) {
3152 bool simulcast_offered = local_content &&
3153 local_content->media_description() &&
3154 local_content->media_description()->HasSimulcast();
3155 bool simulcast_answered = answer_media_desc.HasSimulcast();
3156 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3157 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3158 return simulcast_offered && (!simulcast_answered || !rids_supported);
3159}
3160
Amit Hilbuch2297d332019-02-19 12:49:22 -08003161static RTCError DisableSimulcastInSender(
3162 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003163 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003164 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003165 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003166 return RTCError::OK();
3167 }
3168
Amit Hilbuch2297d332019-02-19 12:49:22 -08003169 std::vector<std::string> disabled_layers;
3170 std::transform(
3171 parameters.encodings.begin() + 1, parameters.encodings.end(),
3172 std::back_inserter(disabled_layers),
3173 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3174 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003175}
3176
Steve Antondcc3c022017-12-22 16:02:54 -08003177RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3178PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003179 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003180 size_t mline_index,
3181 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003182 const ContentInfo* old_local_content,
3183 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003184 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003185 // If this is an offer then the m= section might be recycled. If the m=
3186 // section is being recycled (defined as: rejected in the current local or
3187 // remote description and not rejected in new description), dissociate the
3188 // currently associated RtpTransceiver by setting its mid property to null,
3189 // and discard the mapping between the transceiver and its m= section index.
3190 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3191 old_remote_content)) {
3192 // We want to dissociate the transceiver that has the rejected mid.
3193 const std::string& old_mid =
3194 (old_local_content && old_local_content->rejected)
3195 ? old_local_content->name
3196 : old_remote_content->name;
3197 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003198 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003199 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3200 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003201 old_transceiver->internal()->set_mid(absl::nullopt);
3202 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003203 }
3204 }
3205 const MediaContentDescription* media_desc = content.media_description();
3206 auto transceiver = GetAssociatedTransceiver(content.name);
3207 if (source == cricket::CS_LOCAL) {
3208 // Find the RtpTransceiver that corresponds to this m= section, using the
3209 // mapping between transceivers and m= section indices established when
3210 // creating the offer.
3211 if (!transceiver) {
3212 transceiver = GetTransceiverByMLineIndex(mline_index);
3213 }
3214 if (!transceiver) {
3215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3216 "Unknown transceiver");
3217 }
3218 } else {
3219 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3220 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3221 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003222 // When simulcast is requested, a transceiver cannot be associated because
3223 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003224 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003225 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3226 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003227 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3228 }
3229 // If no RtpTransceiver was found in the previous step, create one with a
3230 // recvonly direction.
3231 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003232 RTC_LOG(LS_INFO) << "Adding "
3233 << cricket::MediaTypeToString(media_desc->type())
3234 << " transceiver for MID=" << content.name
3235 << " at i=" << mline_index
3236 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003237 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003238 std::vector<RtpEncodingParameters> send_encodings =
3239 GetSendEncodingsFromRemoteDescription(*media_desc);
3240 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3241 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003242 std::string receiver_id;
3243 if (!media_desc->streams().empty()) {
3244 receiver_id = media_desc->streams()[0].id;
3245 } else {
3246 receiver_id = rtc::CreateRandomUuid();
3247 }
3248 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003249 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003250 transceiver->internal()->set_direction(
3251 RtpTransceiverDirection::kRecvOnly);
3252 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003253
3254 // Check if the offer indicated simulcast but the answer rejected it.
3255 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003256 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003257 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003258 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003259 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003260 if (!error.ok()) {
3261 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3262 return std::move(error);
3263 }
3264 }
Steve Antondcc3c022017-12-22 16:02:54 -08003265 }
3266 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003267 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003268 LOG_AND_RETURN_ERROR(
3269 RTCErrorType::INVALID_PARAMETER,
3270 "Transceiver type does not match media description type.");
3271 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003272 if (media_desc->HasSimulcast()) {
3273 std::vector<SimulcastLayer> layers =
3274 source == cricket::CS_LOCAL
3275 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3276 : media_desc->simulcast_description()
3277 .receive_layers()
3278 .GetAllLayers();
3279 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003280 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003281 if (!error.ok()) {
3282 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3283 return std::move(error);
3284 }
3285 }
Steve Antondcc3c022017-12-22 16:02:54 -08003286 // Associate the found or created RtpTransceiver with the m= section by
3287 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3288 // section, and establish a mapping between the transceiver and the index of
3289 // the m= section.
3290 transceiver->internal()->set_mid(content.name);
3291 transceiver->internal()->set_mline_index(mline_index);
3292 return std::move(transceiver);
3293}
3294
3295rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3296PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3297 RTC_DCHECK(IsUnifiedPlan());
3298 for (auto transceiver : transceivers_) {
3299 if (transceiver->mid() == mid) {
3300 return transceiver;
3301 }
3302 }
3303 return nullptr;
3304}
3305
3306rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3307PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3308 RTC_DCHECK(IsUnifiedPlan());
3309 for (auto transceiver : transceivers_) {
3310 if (transceiver->internal()->mline_index() == mline_index) {
3311 return transceiver;
3312 }
3313 }
3314 return nullptr;
3315}
3316
3317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3318PeerConnection::FindAvailableTransceiverToReceive(
3319 cricket::MediaType media_type) const {
3320 RTC_DCHECK(IsUnifiedPlan());
3321 // From JSEP section 5.10 (Applying a Remote Description):
3322 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3323 // the same type that were added to the PeerConnection by addTrack and are not
3324 // associated with any m= section and are not stopped, find the first such
3325 // RtpTransceiver.
3326 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003327 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003328 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3329 !transceiver->stopped()) {
3330 return transceiver;
3331 }
3332 }
3333 return nullptr;
3334}
3335
Steve Antoned10bd92017-12-05 10:52:59 -08003336const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3337 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3338 transceiver,
3339 const SessionDescriptionInterface* sdesc) const {
3340 RTC_DCHECK(transceiver);
3341 RTC_DCHECK(sdesc);
3342 if (IsUnifiedPlan()) {
3343 if (!transceiver->internal()->mid()) {
3344 // This transceiver is not associated with a media section yet.
3345 return nullptr;
3346 }
3347 return sdesc->description()->GetContentByName(
3348 *transceiver->internal()->mid());
3349 } else {
3350 // Plan B only allows at most one audio and one video section, so use the
3351 // first media section of that type.
3352 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003353 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003354 }
3355}
3356
deadbeef46c73892016-11-16 19:42:04 -08003357PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003358 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003359 return configuration_;
3360}
3361
deadbeef293e9262017-01-11 12:28:30 -08003362bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3363 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003364 RTC_DCHECK_RUN_ON(signaling_thread());
3365 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003366 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003367 if (IsClosed()) {
3368 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3369 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3370 }
3371
Qingsi Wanga2d60672018-04-11 16:57:45 -07003372 // According to JSEP, after setLocalDescription, changing the candidate pool
3373 // size is not allowed, and changing the set of ICE servers will not result
3374 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003375 if (local_description() && configuration.ice_candidate_pool_size !=
3376 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003377 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3378 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003379 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003380 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003381
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003382 if (local_description() &&
3383 configuration.use_media_transport != configuration_.use_media_transport) {
3384 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3385 "SetLocalDescription.";
3386 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3387 }
3388
3389 if (remote_description() &&
3390 configuration.use_media_transport != configuration_.use_media_transport) {
3391 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3392 "SetRemoteDescription.";
3393 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3394 }
3395
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003396 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003397 configuration.use_media_transport_for_data_channels !=
3398 configuration_.use_media_transport_for_data_channels) {
3399 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3400 "after calling SetLocalDescription.";
3401 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3402 }
3403
3404 if (remote_description() &&
3405 configuration.use_media_transport_for_data_channels !=
3406 configuration_.use_media_transport_for_data_channels) {
3407 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3408 "after calling SetRemoteDescription.";
3409 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3410 }
3411
3412 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003413 configuration.crypto_options != configuration_.crypto_options) {
3414 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3415 "SetLocalDescription.";
3416 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3417 }
3418
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003419 if (local_description() && configuration.use_datagram_transport !=
3420 configuration_.use_datagram_transport) {
3421 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3422 "after calling SetLocalDescription.";
3423 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3424 }
3425
3426 if (remote_description() && configuration.use_datagram_transport !=
3427 configuration_.use_datagram_transport) {
3428 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3429 "after calling SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003433 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003434 configuration.use_media_transport ||
3435 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003436 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3437 << "Media transport requires MaxBundle policy.";
3438 }
3439
deadbeef293e9262017-01-11 12:28:30 -08003440 // The simplest (and most future-compatible) way to tell if the config was
3441 // modified in an invalid way is to copy each property we do support
3442 // modifying, then use operator==. There are far more properties we don't
3443 // support modifying than those we do, and more could be added.
3444 RTCConfiguration modified_config = configuration_;
3445 modified_config.servers = configuration.servers;
3446 modified_config.type = configuration.type;
3447 modified_config.ice_candidate_pool_size =
3448 configuration.ice_candidate_pool_size;
3449 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003450 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003451 modified_config.ice_check_interval_strong_connectivity =
3452 configuration.ice_check_interval_strong_connectivity;
3453 modified_config.ice_check_interval_weak_connectivity =
3454 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003455 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3456 modified_config.ice_unwritable_min_checks =
3457 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003458 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003459 modified_config.stun_candidate_keepalive_interval =
3460 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003461 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003462 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003463 modified_config.active_reset_srtp_params =
3464 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003465 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003466 modified_config.use_media_transport_for_data_channels =
3467 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003468 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003469 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003470 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3471 }
3472
Steve Anton038834f2017-07-14 15:59:59 -07003473 // Validate the modified configuration.
3474 RTCError validate_error = ValidateConfiguration(modified_config);
3475 if (!validate_error.ok()) {
3476 return SafeSetError(std::move(validate_error), error);
3477 }
3478
deadbeef293e9262017-01-11 12:28:30 -08003479 // Note that this isn't possible through chromium, since it's an unsigned
3480 // short in WebIDL.
3481 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003482 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003483 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3484 }
3485
3486 // Parse ICE servers before hopping to network thread.
3487 cricket::ServerAddresses stun_servers;
3488 std::vector<cricket::RelayServerConfig> turn_servers;
3489 RTCErrorType parse_error =
3490 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3491 if (parse_error != RTCErrorType::NONE) {
3492 return SafeSetError(parse_error, error);
3493 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003494 // Note if STUN or TURN servers were supplied.
3495 if (!stun_servers.empty()) {
3496 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3497 }
3498 if (!turn_servers.empty()) {
3499 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3500 }
deadbeef293e9262017-01-11 12:28:30 -08003501
3502 // In theory this shouldn't fail.
3503 if (!network_thread()->Invoke<bool>(
3504 RTC_FROM_HERE,
3505 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3506 stun_servers, turn_servers, modified_config.type,
3507 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003508 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003509 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003510 modified_config.stun_candidate_keepalive_interval,
3511 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003513 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3514 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003515
deadbeefd1a38b52016-12-10 13:15:33 -08003516 // As described in JSEP, calling setConfiguration with new ICE servers or
3517 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3518 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003519 if (modified_config.servers != configuration_.servers ||
3520 modified_config.type != configuration_.type ||
3521 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003522 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003523 }
skvladd1f5fda2017-02-03 16:54:05 -08003524
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003525 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003526 transport_controller_->SetMediaTransportSettings(
3527 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003528 modified_config.use_media_transport_for_data_channels,
3529 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003530
Zhi Huangb57e1692018-06-12 11:41:11 -07003531 if (configuration_.active_reset_srtp_params !=
3532 modified_config.active_reset_srtp_params) {
3533 transport_controller_->SetActiveResetSrtpParams(
3534 modified_config.active_reset_srtp_params);
3535 }
3536
deadbeef293e9262017-01-11 12:28:30 -08003537 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003538 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003539 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003540}
3541
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003542bool PeerConnection::AddIceCandidate(
3543 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003544 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003545 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003546 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003547 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003548 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003549 return false;
3550 }
Steve Antond25da372017-11-06 14:50:29 -08003551
3552 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003553 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003554 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003555 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003556 return false;
3557 }
3558
3559 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003560 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003561 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003562 return false;
3563 }
3564
3565 bool valid = false;
3566 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3567 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003568 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003569 return false;
3570 }
3571
3572 // Add this candidate to the remote session description.
3573 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003574 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003575 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003576 return false;
3577 }
3578
3579 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003580 bool result = UseCandidate(ice_candidate);
3581 if (result) {
3582 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003583 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3584 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3585 }
3586 if (ice_candidate->candidate().address().IsPrivateIP()) {
3587 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3588 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003589 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3590 } else {
3591 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3592 }
3593 return result;
Steve Antond25da372017-11-06 14:50:29 -08003594 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003595 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003596 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003597 return true;
3598 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003599}
3600
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003601bool PeerConnection::RemoveIceCandidates(
3602 const std::vector<cricket::Candidate>& candidates) {
3603 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003604 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003605 if (IsClosed()) {
3606 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3607 return false;
3608 }
3609
Steve Antond25da372017-11-06 14:50:29 -08003610 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003611 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3612 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003613 return false;
3614 }
3615
3616 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003617 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003618 return false;
3619 }
3620
3621 size_t number_removed =
3622 mutable_remote_description()->RemoveCandidates(candidates);
3623 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003624 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003625 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003626 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003627 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003628 }
3629
3630 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003631 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3632 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003633 RTC_LOG(LS_ERROR)
3634 << "RemoveIceCandidates: Error when removing remote candidates: "
3635 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003636 }
3637 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003638}
3639
Niels Möller0c4f7be2018-05-07 14:01:37 +02003640RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003641 if (!worker_thread()->IsCurrent()) {
3642 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003643 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003644 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003645 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003646
Niels Möller0c4f7be2018-05-07 14:01:37 +02003647 const bool has_min = bitrate.min_bitrate_bps.has_value();
3648 const bool has_start = bitrate.start_bitrate_bps.has_value();
3649 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003650 if (has_min && *bitrate.min_bitrate_bps < 0) {
3651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3652 "min_bitrate_bps <= 0");
3653 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003654 if (has_start) {
3655 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003657 "start_bitrate_bps < min_bitrate_bps");
3658 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003659 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3660 "curent_bitrate_bps < 0");
3661 }
3662 }
3663 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003664 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003666 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003667 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3668 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3669 "max_bitrate_bps < min_bitrate_bps");
3670 } else if (*bitrate.max_bitrate_bps < 0) {
3671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3672 "max_bitrate_bps < 0");
3673 }
3674 }
3675
zstein4b979802017-06-02 14:37:37 -07003676 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003677 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003678
3679 return RTCError::OK();
3680}
3681
Alex Narest78609d52017-10-20 10:37:47 +02003682void PeerConnection::SetBitrateAllocationStrategy(
3683 std::unique_ptr<rtc::BitrateAllocationStrategy>
3684 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003685 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003686 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3687 // move-capture values in lambdas.
3688 struct Task {
3689 PeerConnection* const pc;
3690 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3691 void operator()() {
3692 RTC_DCHECK_RUN_ON(pc->worker_thread());
3693 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3694 }
3695 };
3696 worker_thread()->Invoke<void>(
3697 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003698 return;
3699 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003700 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003701 RTC_DCHECK(call_.get());
3702 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3703}
3704
henrika5f6bf242017-11-01 11:06:56 +01003705void PeerConnection::SetAudioPlayout(bool playout) {
3706 if (!worker_thread()->IsCurrent()) {
3707 worker_thread()->Invoke<void>(
3708 RTC_FROM_HERE,
3709 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3710 return;
3711 }
3712 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003713 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003714 audio_state->SetPlayout(playout);
3715}
3716
3717void PeerConnection::SetAudioRecording(bool recording) {
3718 if (!worker_thread()->IsCurrent()) {
3719 worker_thread()->Invoke<void>(
3720 RTC_FROM_HERE,
3721 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3722 return;
3723 }
3724 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003725 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003726 audio_state->SetRecording(recording);
3727}
3728
Steve Anton8c0f7a72017-10-03 10:03:10 -07003729std::unique_ptr<rtc::SSLCertificate>
3730PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003731 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3732 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003733 return nullptr;
3734 }
Steve Antonf25303e2018-10-16 15:23:31 -07003735 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003736}
3737
Zhi Huang70b820f2018-01-27 14:16:15 -08003738std::unique_ptr<rtc::SSLCertChain>
3739PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003741 auto audio_transceiver = GetFirstAudioTransceiver();
3742 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003743 return nullptr;
3744 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003745 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003746 audio_transceiver->internal()->channel()->transport_name());
3747}
3748
3749rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3750PeerConnection::GetFirstAudioTransceiver() const {
3751 for (auto transceiver : transceivers_) {
3752 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3753 return transceiver;
3754 }
3755 }
3756 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003757}
3758
ivoc14d5dbe2016-07-04 07:06:55 -07003759bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3760 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003761 // TODO(eladalon): It would be better to not allow negative values into PC.
3762 const size_t max_size = (max_size_bytes < 0)
3763 ? RtcEventLog::kUnlimitedOutput
3764 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003765 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3766 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3767 output_period_ms = 5000;
3768 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003769 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003770 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003771 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003772}
3773
Bjorn Tereliusde939432017-11-20 17:38:14 +01003774bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3775 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003776 // TODO(eladalon): In C++14, this can be done with a lambda.
3777 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003778 bool operator()() {
3779 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3780 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003781 PeerConnection* const pc;
3782 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003783 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003784 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003785 return worker_thread()->Invoke<bool>(
3786 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003787}
3788
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003789bool PeerConnection::StartRtcEventLog(
3790 std::unique_ptr<RtcEventLogOutput> output) {
3791 return StartRtcEventLog(std::move(output),
3792 webrtc::RtcEventLog::kImmediateOutput);
3793}
3794
ivoc14d5dbe2016-07-04 07:06:55 -07003795void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003796 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003797 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3798}
3799
Harald Alvestrandad88c882018-11-28 16:47:46 +01003800rtc::scoped_refptr<DtlsTransportInterface>
3801PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003802 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003803 return transport_controller_->LookupDtlsTransportByMid(mid);
3804}
3805
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003806rtc::scoped_refptr<DtlsTransport>
3807PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003808 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003809 return transport_controller_->LookupDtlsTransportByMid(mid);
3810}
3811
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003812rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3813 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003814 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003815 return sctp_transport_;
3816}
3817
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003819 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003820 return pending_local_description_ ? pending_local_description_.get()
3821 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003822}
3823
3824const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003825 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003826 return pending_remote_description_ ? pending_remote_description_.get()
3827 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003828}
3829
deadbeeffe4a8a42016-12-20 17:56:17 -08003830const SessionDescriptionInterface* PeerConnection::current_local_description()
3831 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003832 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003833 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003834}
3835
3836const SessionDescriptionInterface* PeerConnection::current_remote_description()
3837 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003838 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003839 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003840}
3841
3842const SessionDescriptionInterface* PeerConnection::pending_local_description()
3843 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003844 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003845 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003846}
3847
3848const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3849 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003850 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003851 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003852}
3853
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003854void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003855 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003856 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003857 // Update stats here so that we have the most recent stats for tracks and
3858 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003859 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003860
Steve Anton75737c02017-11-06 10:37:17 -08003861 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003862 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003863
Mirko Bonadei739baf02019-01-27 17:29:42 +01003864 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003865 transceiver->Stop();
3866 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003867
3868 // Ensure that all asynchronous stats requests are completed before destroying
3869 // the transport controller below.
3870 if (stats_collector_) {
3871 stats_collector_->WaitForPendingRequest();
3872 }
3873
3874 // Don't destroy BaseChannels until after stats has been cleaned up so that
3875 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003876 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003877
Qingsi Wang93a84392018-01-30 17:13:09 -08003878 // The event log is used in the transport controller, which must be outlived
3879 // by the former. CreateOffer by the peer connection is implemented
3880 // asynchronously and if the peer connection is closed without resetting the
3881 // WebRTC session description factory, the session description factory would
3882 // call the transport controller.
3883 webrtc_session_desc_factory_.reset();
3884 transport_controller_.reset();
3885
deadbeef42a42632017-03-10 15:18:00 -08003886 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003887 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3888 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003889
Steve Anton978b8762017-09-29 12:15:02 -07003890 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003891 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003892 call_.reset();
3893 // The event log must outlive call (and any other object that uses it).
3894 event_log_.reset();
3895 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003896 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003897 // The .h file says that observer can be discarded after close() returns.
3898 // Make sure this is true.
3899 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003900}
3901
Steve Antonad182762018-09-05 20:22:40 +00003902void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003903 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003904 switch (msg->message_id) {
3905 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3906 SetSessionDescriptionMsg* param =
3907 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3908 param->observer->OnSuccess();
3909 delete param;
3910 break;
3911 }
3912 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3913 SetSessionDescriptionMsg* param =
3914 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3915 param->observer->OnFailure(std::move(param->error));
3916 delete param;
3917 break;
3918 }
3919 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3920 CreateSessionDescriptionMsg* param =
3921 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3922 param->observer->OnFailure(std::move(param->error));
3923 delete param;
3924 break;
3925 }
3926 case MSG_GETSTATS: {
3927 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3928 StatsReports reports;
3929 stats_->GetStats(param->track, &reports);
3930 param->observer->OnComplete(reports);
3931 delete param;
3932 break;
3933 }
3934 case MSG_FREE_DATACHANNELS: {
3935 sctp_data_channels_to_free_.clear();
3936 break;
3937 }
3938 case MSG_REPORT_USAGE_PATTERN: {
3939 ReportUsagePattern();
3940 break;
3941 }
3942 default:
3943 RTC_NOTREACHED() << "Not implemented";
3944 break;
3945 }
3946}
3947
Steve Antonafb0bb72018-02-20 11:35:37 -08003948cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3949 RTC_DCHECK(!IsUnifiedPlan());
3950 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3951 GetAudioTransceiver()->internal()->channel());
3952 if (voice_channel) {
3953 return voice_channel->media_channel();
3954 } else {
3955 return nullptr;
3956 }
3957}
3958
3959cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3960 RTC_DCHECK(!IsUnifiedPlan());
3961 auto* video_channel = static_cast<cricket::VideoChannel*>(
3962 GetVideoTransceiver()->internal()->channel());
3963 if (video_channel) {
3964 return video_channel->media_channel();
3965 } else {
3966 return nullptr;
3967 }
3968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970void PeerConnection::CreateAudioReceiver(
3971 MediaStreamInterface* stream,
3972 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003973 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3974 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003975 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3976 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003977 auto* audio_receiver = new AudioRtpReceiver(
3978 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003979 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003980 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3981 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3982 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003983 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003984 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003985 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003986}
3987
Steve Anton4171afb2017-11-20 10:20:22 -08003988void PeerConnection::CreateVideoReceiver(
3989 MediaStreamInterface* stream,
3990 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003991 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3992 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003993 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3994 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003995 auto* video_receiver = new VideoRtpReceiver(
3996 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003997 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003998 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3999 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4000 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004001 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004002 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004003 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004004}
4005
deadbeef70ab1a12015-09-28 16:53:55 -07004006// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4007// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004008rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004009 const RtpSenderInfo& remote_sender_info) {
4010 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4011 if (!receiver) {
4012 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4013 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004014 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004015 }
Steve Anton4171afb2017-11-20 10:20:22 -08004016 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4017 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4018 } else {
4019 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4020 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004021 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004022}
4023
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004024void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4025 MediaStreamInterface* stream) {
4026 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004027 RTC_DCHECK(track);
4028 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004030 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004031 // We already have a sender for this track, so just change the stream_id
4032 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004033 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 return;
4035 }
4036
4037 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004038 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004039 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004040 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004041 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004042 // If the sender has already been configured in SDP, we call SetSsrc,
4043 // which will connect the sender to the underlying transport. This can
4044 // occur if a local session description that contains the ID of the sender
4045 // is set before AddStream is called. It can also occur if the local
4046 // session description is not changed and RemoveStream is called, and
4047 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004048 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004049 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004050 if (sender_info) {
4051 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004052 }
4053}
4054
4055// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4056// indefinitely, when we have unified plan SDP.
4057void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4058 MediaStreamInterface* stream) {
4059 RTC_DCHECK(!IsClosed());
4060 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004061 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004062 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4063 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004064 return;
4065 }
Steve Anton4171afb2017-11-20 10:20:22 -08004066 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004067}
4068
4069void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4070 MediaStreamInterface* stream) {
4071 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004072 RTC_DCHECK(track);
4073 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004075 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004076 // We already have a sender for this track, so just change the stream_id
4077 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004078 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004079 return;
4080 }
4081
4082 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004083 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004084 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004085 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004086 GetVideoTransceiver()->internal()->AddSender(new_sender);
4087 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004088 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004089 if (sender_info) {
4090 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004091 }
4092}
4093
4094void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4095 MediaStreamInterface* stream) {
4096 RTC_DCHECK(!IsClosed());
4097 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004098 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004099 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4100 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004101 return;
4102 }
Steve Anton4171afb2017-11-20 10:20:22 -08004103 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004104}
4105
Steve Antonba818672017-11-06 10:21:57 -08004106void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004107 if (ice_connection_state_ == new_state) {
4108 return;
4109 }
4110
deadbeefcbecd352015-09-23 11:50:27 -07004111 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004112 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004113 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004114 return;
4115 }
Steve Antonba818672017-11-06 10:21:57 -08004116
Mirko Bonadei675513b2017-11-09 11:09:25 +01004117 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4118 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004119 RTC_DCHECK(ice_connection_state_ !=
4120 PeerConnectionInterface::kIceConnectionClosed);
4121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004122 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004123 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004124}
4125
Alex Loiko9289eda2018-11-23 16:18:59 +00004126void PeerConnection::SetStandardizedIceConnectionState(
4127 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004128 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004129 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004130 }
4131
4132 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004133 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004134 }
4135
4136 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4137 << standardized_ice_connection_state_ << " => " << new_state;
4138
Alex Loiko9289eda2018-11-23 16:18:59 +00004139 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004140 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004141}
4142
Jonas Olsson635474e2018-10-18 15:58:17 +02004143void PeerConnection::SetConnectionState(
4144 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004145 if (connection_state_ == new_state)
4146 return;
4147 if (IsClosed())
4148 return;
4149 connection_state_ = new_state;
4150 Observer()->OnConnectionChange(new_state);
4151}
4152
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004153void PeerConnection::OnIceGatheringChange(
4154 PeerConnectionInterface::IceGatheringState new_state) {
4155 if (IsClosed()) {
4156 return;
4157 }
4158 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004159 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004160}
4161
jbauch81bf7b02017-03-25 08:31:12 -07004162void PeerConnection::OnIceCandidate(
4163 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004164 if (IsClosed()) {
4165 return;
4166 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004167 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004168 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4169 candidate->candidate().address().IsPrivateIP()) {
4170 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4171 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004172 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4173 candidate->candidate().address().IsUnresolvedIP()) {
4174 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4175 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004176 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004177}
4178
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004179void PeerConnection::OnIceCandidatesRemoved(
4180 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004181 if (IsClosed()) {
4182 return;
4183 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004184 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004185}
4186
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004187void PeerConnection::ChangeSignalingState(
4188 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004189 if (signaling_state_ == signaling_state) {
4190 return;
4191 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004192 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4193 << GetSignalingStateString(signaling_state_)
4194 << " New state: "
4195 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004196 signaling_state_ = signaling_state;
4197 if (signaling_state == kClosed) {
4198 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004199 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004200 standardized_ice_connection_state_ =
4201 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004202 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4203 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004204 if (ice_gathering_state_ != kIceGatheringComplete) {
4205 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004206 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004207 }
4208 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004209 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004210}
4211
deadbeefeb459812015-12-15 19:24:43 -08004212void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4213 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004214 if (IsClosed()) {
4215 return;
4216 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004218 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004219}
4220
deadbeefeb459812015-12-15 19:24:43 -08004221void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4222 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004223 if (IsClosed()) {
4224 return;
4225 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004226 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004227 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004228}
4229
4230void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4231 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004232 if (IsClosed()) {
4233 return;
4234 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004235 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004236 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004237}
4238
4239void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4240 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004241 if (IsClosed()) {
4242 return;
4243 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004244 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004245 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004246}
4247
Henrik Boström31638672017-11-23 17:48:32 +01004248void PeerConnection::PostSetSessionDescriptionSuccess(
4249 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004250 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4251 signaling_thread()->Post(RTC_FROM_HERE, this,
4252 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004253}
4254
deadbeefab9b2d12015-10-14 11:33:11 -07004255void PeerConnection::PostSetSessionDescriptionFailure(
4256 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004257 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004258 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004259 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4260 msg->error = std::move(error);
4261 signaling_thread()->Post(RTC_FROM_HERE, this,
4262 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004263}
4264
4265void PeerConnection::PostCreateSessionDescriptionFailure(
4266 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004267 RTCError error) {
4268 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004269 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4270 msg->error = std::move(error);
4271 signaling_thread()->Post(RTC_FROM_HERE, this,
4272 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004273}
4274
zhihuang1c378ed2017-08-17 14:10:50 -07004275void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004276 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004277 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004278 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004279
Steve Antondcc3c022017-12-22 16:02:54 -08004280 if (IsUnifiedPlan()) {
4281 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4282 } else {
4283 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4284 }
4285
Steve Antonfa2260d2017-12-28 16:38:23 -08004286 // Intentionally unset the data channel type for RTP data channel with the
4287 // second condition. Otherwise the RTP data channels would be successfully
4288 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4289 // when building with chromium. We want to leave RTP data channels broken, so
4290 // people won't try to use them.
4291 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4292 session_options->data_channel_type = data_channel_type();
4293 }
4294
Steve Antondcc3c022017-12-22 16:02:54 -08004295 // Apply ICE restart flag and renomination flag.
4296 for (auto& options : session_options->media_description_options) {
4297 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4298 options.transport_options.enable_ice_renomination =
4299 configuration_.enable_ice_renomination;
4300 }
4301
4302 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004303 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004304 session_options->pooled_ice_credentials =
4305 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4306 RTC_FROM_HERE,
4307 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4308 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004309 session_options->offer_extmap_allow_mixed =
4310 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004311
4312 if (configuration_.enable_dtls_srtp &&
4313 !configuration_.enable_dtls_srtp.value()) {
4314 session_options->media_transport_settings =
4315 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4316 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004317 // Allow fallback for using obsolete SCTP syntax.
4318 // Note that the default in |session_options| is true, while
4319 // the default in |options| is false.
4320 session_options->use_obsolete_sctp_sdp =
4321 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004322}
4323
4324void PeerConnection::GetOptionsForPlanBOffer(
4325 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4326 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004327 // Figure out transceiver directional preferences.
4328 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4329 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4330
4331 // By default, generate sendrecv/recvonly m= sections.
4332 bool recv_audio = true;
4333 bool recv_video = true;
4334
4335 // By default, only offer a new m= section if we have media to send with it.
4336 bool offer_new_audio_description = send_audio;
4337 bool offer_new_video_description = send_video;
4338 bool offer_new_data_description = HasDataChannels();
4339
4340 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004341 if (offer_answer_options.offer_to_receive_audio !=
4342 RTCOfferAnswerOptions::kUndefined) {
4343 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004344 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004345 offer_new_audio_description ||
4346 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004347 }
Steve Antondcc3c022017-12-22 16:02:54 -08004348 if (offer_answer_options.offer_to_receive_video !=
4349 RTCOfferAnswerOptions::kUndefined) {
4350 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004351 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004352 offer_new_video_description ||
4353 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004354 }
4355
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004356 absl::optional<size_t> audio_index;
4357 absl::optional<size_t> video_index;
4358 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004359 // If a current description exists, generate m= sections in the same order,
4360 // using the first audio/video/data section that appears and rejecting
4361 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004362 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004363 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004364 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004365 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4366 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4367 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004368 }
4369
zhihuang1c378ed2017-08-17 14:10:50 -07004370 // Add audio/video/data m= sections to the end if needed.
4371 if (!audio_index && offer_new_audio_description) {
4372 session_options->media_description_options.push_back(
4373 cricket::MediaDescriptionOptions(
4374 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004375 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4376 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004377 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004378 }
zhihuang1c378ed2017-08-17 14:10:50 -07004379 if (!video_index && offer_new_video_description) {
4380 session_options->media_description_options.push_back(
4381 cricket::MediaDescriptionOptions(
4382 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004383 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4384 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004385 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004386 }
zhihuang1c378ed2017-08-17 14:10:50 -07004387 if (!data_index && offer_new_data_description) {
4388 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004389 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004390 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004391 }
4392
4393 cricket::MediaDescriptionOptions* audio_media_description_options =
4394 !audio_index ? nullptr
4395 : &session_options->media_description_options[*audio_index];
4396 cricket::MediaDescriptionOptions* video_media_description_options =
4397 !video_index ? nullptr
4398 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004399
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004400 AddPlanBRtpSenderOptions(GetSendersInternal(),
4401 audio_media_description_options,
4402 video_media_description_options,
4403 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004404}
4405
Steve Antondcc3c022017-12-22 16:02:54 -08004406static cricket::MediaDescriptionOptions
4407GetMediaDescriptionOptionsForTransceiver(
4408 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4409 transceiver,
4410 const std::string& mid) {
4411 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004412 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004413 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004414 media_description_options.codec_preferences =
4415 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004416 // This behavior is specified in JSEP. The gist is that:
4417 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4418 // sendrecv.
4419 // 2. If the MSID is included, then it must be included in any subsequent
4420 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004421 if (transceiver->stopped() ||
4422 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4423 !transceiver->internal()->has_ever_been_used_to_send())) {
4424 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004425 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004426
4427 cricket::SenderOptions sender_options;
4428 sender_options.track_id = transceiver->sender()->id();
4429 sender_options.stream_ids = transceiver->sender()->stream_ids();
4430
4431 // The following sets up RIDs and Simulcast.
4432 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004433 RtpParameters send_parameters =
4434 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004435 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4436 send_parameters.encodings.end(),
4437 [](const RtpEncodingParameters& encoding) {
4438 return !encoding.rid.empty();
4439 });
4440
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004441 std::vector<RidDescription> send_rids;
4442 SimulcastLayerList send_layers;
4443 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4444 if (encoding.rid.empty()) {
4445 continue;
4446 }
4447 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4448 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4449 }
4450
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004451 if (has_rids) {
4452 sender_options.rids = send_rids;
4453 }
4454
4455 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004456 // When RIDs are configured, we must set num_sim_layers to 0 to.
4457 // Otherwise, num_sim_layers must be 1 because either there is no
4458 // simulcast, or simulcast is acheived by munging the SDP.
4459 sender_options.num_sim_layers = has_rids ? 0 : 1;
4460 media_description_options.sender_options.push_back(sender_options);
4461
Steve Antondcc3c022017-12-22 16:02:54 -08004462 return media_description_options;
4463}
4464
Steve Anton5c72e712018-12-10 14:25:30 -08004465// Returns the ContentInfo at mline index |i|, or null if none exists.
4466static const ContentInfo* GetContentByIndex(
4467 const SessionDescriptionInterface* sdesc,
4468 size_t i) {
4469 if (!sdesc) {
4470 return nullptr;
4471 }
4472 const ContentInfos& contents = sdesc->description()->contents();
4473 return (i < contents.size() ? &contents[i] : nullptr);
4474}
4475
Steve Antondcc3c022017-12-22 16:02:54 -08004476void PeerConnection::GetOptionsForUnifiedPlanOffer(
4477 const RTCOfferAnswerOptions& offer_answer_options,
4478 cricket::MediaSessionOptions* session_options) {
4479 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4480 // Offers) and 5.2.2 (Subsequent Offers).
4481 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4482 const ContentInfos& local_contents =
4483 (local_description() ? local_description()->description()->contents()
4484 : ContentInfos());
4485 const ContentInfos& remote_contents =
4486 (remote_description() ? remote_description()->description()->contents()
4487 : ContentInfos());
4488 // The mline indices that can be recycled. New transceivers should reuse these
4489 // slots first.
4490 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004491 // First, go through each media section that exists in either the local or
4492 // remote description and generate a media section in this offer for the
4493 // associated transceiver. If a media section can be recycled, generate a
4494 // default, rejected media section here that can be later overwritten.
4495 for (size_t i = 0;
4496 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4497 // Either |local_content| or |remote_content| is non-null.
4498 const ContentInfo* local_content =
4499 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004500 const ContentInfo* current_local_content =
4501 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004502 const ContentInfo* remote_content =
4503 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004504 const ContentInfo* current_remote_content =
4505 GetContentByIndex(current_remote_description(), i);
4506 bool had_been_rejected =
4507 (current_local_content && current_local_content->rejected) ||
4508 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004509 const std::string& mid =
4510 (local_content ? local_content->name : remote_content->name);
4511 cricket::MediaType media_type =
4512 (local_content ? local_content->media_description()->type()
4513 : remote_content->media_description()->type());
4514 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4515 media_type == cricket::MEDIA_TYPE_VIDEO) {
4516 auto transceiver = GetAssociatedTransceiver(mid);
4517 RTC_CHECK(transceiver);
4518 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004519 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004520 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004521 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004522 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4523 RtpTransceiverDirection::kInactive,
4524 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004525 recycleable_mline_indices.push(i);
4526 } else {
4527 session_options->media_description_options.push_back(
4528 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4529 // CreateOffer shouldn't really cause any state changes in
4530 // PeerConnection, but we need a way to match new transceivers to new
4531 // media sections in SetLocalDescription and JSEP specifies this is done
4532 // by recording the index of the media section generated for the
4533 // transceiver in the offer.
4534 transceiver->internal()->set_mline_index(i);
4535 }
4536 } else {
4537 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004538 RTC_CHECK(GetDataMid());
4539 if (had_been_rejected || mid != *GetDataMid()) {
4540 session_options->media_description_options.push_back(
4541 GetMediaDescriptionOptionsForRejectedData(mid));
4542 } else {
4543 session_options->media_description_options.push_back(
4544 GetMediaDescriptionOptionsForActiveData(mid));
4545 }
Steve Antondcc3c022017-12-22 16:02:54 -08004546 }
4547 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004548
Steve Antondcc3c022017-12-22 16:02:54 -08004549 // Next, look for transceivers that are newly added (that is, are not stopped
4550 // and not associated). Reuse media sections marked as recyclable first,
4551 // otherwise append to the end of the offer. New media sections should be
4552 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004553 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004554 if (transceiver->mid() || transceiver->stopped()) {
4555 continue;
4556 }
4557 size_t mline_index;
4558 if (!recycleable_mline_indices.empty()) {
4559 mline_index = recycleable_mline_indices.front();
4560 recycleable_mline_indices.pop();
4561 session_options->media_description_options[mline_index] =
4562 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004563 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004564 } else {
4565 mline_index = session_options->media_description_options.size();
4566 session_options->media_description_options.push_back(
4567 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004568 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004569 }
4570 // See comment above for why CreateOffer changes the transceiver's state.
4571 transceiver->internal()->set_mline_index(mline_index);
4572 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004573 // Lastly, add a m-section if we have local data channels and an m section
4574 // does not already exist.
4575 if (!GetDataMid() && HasDataChannels()) {
4576 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004577 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004578 }
Steve Antondcc3c022017-12-22 16:02:54 -08004579}
4580
4581void PeerConnection::GetOptionsForAnswer(
4582 const RTCOfferAnswerOptions& offer_answer_options,
4583 cricket::MediaSessionOptions* session_options) {
4584 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4585
4586 if (IsUnifiedPlan()) {
4587 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4588 } else {
4589 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4590 }
4591
Steve Antonfa2260d2017-12-28 16:38:23 -08004592 // Intentionally unset the data channel type for RTP data channel. Otherwise
4593 // the RTP data channels would be successfully negotiated by default and the
4594 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4595 // We want to leave RTP data channels broken, so people won't try to use them.
4596 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4597 session_options->data_channel_type = data_channel_type();
4598 }
4599
Steve Antondcc3c022017-12-22 16:02:54 -08004600 // Apply ICE renomination flag.
4601 for (auto& options : session_options->media_description_options) {
4602 options.transport_options.enable_ice_renomination =
4603 configuration_.enable_ice_renomination;
4604 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004605
4606 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004607 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004608 session_options->pooled_ice_credentials =
4609 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4610 RTC_FROM_HERE,
4611 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4612 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004613}
4614
Steve Antondcc3c022017-12-22 16:02:54 -08004615void PeerConnection::GetOptionsForPlanBAnswer(
4616 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004617 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004618 // Figure out transceiver directional preferences.
4619 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4620 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4621
4622 // By default, generate sendrecv/recvonly m= sections. The direction is also
4623 // restricted by the direction in the offer.
4624 bool recv_audio = true;
4625 bool recv_video = true;
4626
4627 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004628 if (offer_answer_options.offer_to_receive_audio !=
4629 RTCOfferAnswerOptions::kUndefined) {
4630 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004631 }
Steve Antondcc3c022017-12-22 16:02:54 -08004632 if (offer_answer_options.offer_to_receive_video !=
4633 RTCOfferAnswerOptions::kUndefined) {
4634 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004635 }
4636
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004637 absl::optional<size_t> audio_index;
4638 absl::optional<size_t> video_index;
4639 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004640
4641 // Generate m= sections that match those in the offer.
4642 // Note that mediasession.cc will handle intersection our preferred
4643 // direction with the offered direction.
4644 GenerateMediaDescriptionOptions(
4645 remote_description(),
4646 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4647 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4648 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004649
4650 cricket::MediaDescriptionOptions* audio_media_description_options =
4651 !audio_index ? nullptr
4652 : &session_options->media_description_options[*audio_index];
4653 cricket::MediaDescriptionOptions* video_media_description_options =
4654 !video_index ? nullptr
4655 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004656
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004657 AddPlanBRtpSenderOptions(GetSendersInternal(),
4658 audio_media_description_options,
4659 video_media_description_options,
4660 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004661}
zhihuangaf388472016-11-02 16:49:48 -07004662
Steve Antondcc3c022017-12-22 16:02:54 -08004663void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4664 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4665 cricket::MediaSessionOptions* session_options) {
4666 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4667 // Answers) and 5.3.2 (Subsequent Answers).
4668 RTC_DCHECK(remote_description());
4669 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4670 for (const ContentInfo& content :
4671 remote_description()->description()->contents()) {
4672 cricket::MediaType media_type = content.media_description()->type();
4673 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4674 media_type == cricket::MEDIA_TYPE_VIDEO) {
4675 auto transceiver = GetAssociatedTransceiver(content.name);
4676 RTC_CHECK(transceiver);
4677 session_options->media_description_options.push_back(
4678 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4679 } else {
4680 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004681 // Reject all data sections if data channels are disabled.
4682 // Reject a data section if it has already been rejected.
4683 // Reject all data sections except for the first one.
4684 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4685 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004686 session_options->media_description_options.push_back(
4687 GetMediaDescriptionOptionsForRejectedData(content.name));
4688 } else {
4689 session_options->media_description_options.push_back(
4690 GetMediaDescriptionOptionsForActiveData(content.name));
4691 }
Steve Antondcc3c022017-12-22 16:02:54 -08004692 }
4693 }
htaa2a49d92016-03-04 02:51:39 -08004694}
4695
zhihuang1c378ed2017-08-17 14:10:50 -07004696void PeerConnection::GenerateMediaDescriptionOptions(
4697 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004698 RtpTransceiverDirection audio_direction,
4699 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004700 absl::optional<size_t>* audio_index,
4701 absl::optional<size_t>* video_index,
4702 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004703 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004704 for (const cricket::ContentInfo& content :
4705 session_desc->description()->contents()) {
4706 if (IsAudioContent(&content)) {
4707 // If we already have an audio m= section, reject this extra one.
4708 if (*audio_index) {
4709 session_options->media_description_options.push_back(
4710 cricket::MediaDescriptionOptions(
4711 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004712 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004713 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004714 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004715 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004716 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4717 content.name, audio_direction,
4718 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004719 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004720 }
4721 } else if (IsVideoContent(&content)) {
4722 // If we already have an video m= section, reject this extra one.
4723 if (*video_index) {
4724 session_options->media_description_options.push_back(
4725 cricket::MediaDescriptionOptions(
4726 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004727 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004728 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004729 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004730 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004731 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4732 content.name, video_direction,
4733 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004734 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004735 }
4736 } else {
4737 RTC_DCHECK(IsDataContent(&content));
4738 // If we already have an data m= section, reject this extra one.
4739 if (*data_index) {
4740 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004741 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004742 } else {
4743 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004744 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004745 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004746 }
4747 }
htaa2a49d92016-03-04 02:51:39 -08004748 }
deadbeefab9b2d12015-10-14 11:33:11 -07004749}
4750
Steve Antonfa2260d2017-12-28 16:38:23 -08004751cricket::MediaDescriptionOptions
4752PeerConnection::GetMediaDescriptionOptionsForActiveData(
4753 const std::string& mid) const {
4754 // Direction for data sections is meaningless, but legacy endpoints might
4755 // expect sendrecv.
4756 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4757 RtpTransceiverDirection::kSendRecv,
4758 /*stopped=*/false);
4759 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4760 return options;
4761}
4762
4763cricket::MediaDescriptionOptions
4764PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4765 const std::string& mid) const {
4766 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4767 RtpTransceiverDirection::kInactive,
4768 /*stopped=*/true);
4769 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4770 return options;
4771}
4772
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004773absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004774 switch (data_channel_type_) {
4775 case cricket::DCT_RTP:
4776 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004777 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004778 }
4779 return rtp_data_channel_->content_name();
4780 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004781 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004782 case cricket::DCT_MEDIA_TRANSPORT:
4783 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004784 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004785 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004786 }
4787}
4788
Steve Anton4171afb2017-11-20 10:20:22 -08004789void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4790 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4791 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004792 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004793}
4794
Steve Anton4171afb2017-11-20 10:20:22 -08004795void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004796 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004797 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004798 cricket::MediaType media_type,
4799 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004800 RTC_DCHECK(!IsUnifiedPlan());
4801
Steve Anton4171afb2017-11-20 10:20:22 -08004802 std::vector<RtpSenderInfo>* current_senders =
4803 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004804
Steve Anton4171afb2017-11-20 10:20:22 -08004805 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004806 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004807 for (auto sender_it = current_senders->begin();
4808 sender_it != current_senders->end();
4809 /* incremented manually */) {
4810 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004811 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004812 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004813 std::string params_stream_id;
4814 if (params) {
4815 params_stream_id =
4816 (!params->first_stream_id().empty() ? params->first_stream_id()
4817 : kDefaultStreamId);
4818 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004819 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004820 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004821 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004822 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004823 sender_exists) {
4824 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004825 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004826 OnRemoteSenderRemoved(info, media_type);
4827 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004828 }
4829 }
4830
Steve Anton4171afb2017-11-20 10:20:22 -08004831 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004832 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004833 if (!params.has_ssrcs()) {
4834 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4835 // sender, this means it is coming from a Unified Plan endpoint,so we just
4836 // create a default.
4837 default_sender_needed = true;
4838 break;
4839 }
4840
Seth Hampson845e8782018-03-02 11:34:10 -08004841 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004842 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004843 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4844 // not supported in Plan B, we just take the first here and create the
4845 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004846 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004847 (!params.first_stream_id().empty() ? params.first_stream_id()
4848 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004849 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004850 uint32_t ssrc = params.first_ssrc();
4851
4852 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004853 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004854 if (!stream) {
4855 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004856 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004857 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004858 remote_streams_->AddStream(stream);
4859 new_streams->AddStream(stream);
4860 }
4861
Steve Anton4171afb2017-11-20 10:20:22 -08004862 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004863 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004864 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004865 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004866 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004867 }
4868 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004869
Steve Anton4171afb2017-11-20 10:20:22 -08004870 // Add default sender if necessary.
4871 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004872 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004873 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004874 if (!default_stream) {
4875 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004876 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004877 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004878 remote_streams_->AddStream(default_stream);
4879 new_streams->AddStream(default_stream);
4880 }
Steve Anton4171afb2017-11-20 10:20:22 -08004881 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4882 ? kDefaultAudioSenderId
4883 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004884 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004885 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004886 if (!default_sender_info) {
4887 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004888 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004889 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004890 }
4891 }
deadbeefab9b2d12015-10-14 11:33:11 -07004892}
4893
Steve Anton4171afb2017-11-20 10:20:22 -08004894void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4895 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004896 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4897 << " receiver for track_id=" << sender_info.sender_id
4898 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004899
Steve Anton3d954a62018-04-02 11:27:23 -07004900 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004901 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004902 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004903 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004904 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004905 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004906 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004907 }
4908}
4909
Steve Anton4171afb2017-11-20 10:20:22 -08004910void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4911 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004912 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4913 << " receiver for track_id=" << sender_info.sender_id
4914 << " and stream_id=" << sender_info.stream_id;
4915
Seth Hampson845e8782018-03-02 11:34:10 -08004916 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004917
Henrik Boström933d8b02017-10-10 10:05:16 -07004918 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004919 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004920 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4921 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004922 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004923 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004924 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004925 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004926 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004927 }
4928 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004929 // Stopping or destroying a VideoRtpReceiver will end the
4930 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004931 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004932 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004933 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004934 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004935 // There's no guarantee the track is still available, e.g. the track may
4936 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004937 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004938 }
4939 } else {
nisseede5da42017-01-12 05:15:36 -08004940 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004941 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004942 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004943 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004944 }
deadbeefab9b2d12015-10-14 11:33:11 -07004945}
4946
4947void PeerConnection::UpdateEndedRemoteMediaStreams() {
4948 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4949 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4950 MediaStreamInterface* stream = remote_streams_->at(i);
4951 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4952 streams_to_remove.push_back(stream);
4953 }
4954 }
4955
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004956 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004957 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004958 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004959 }
4960}
4961
Steve Anton4171afb2017-11-20 10:20:22 -08004962void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004963 const std::vector<cricket::StreamParams>& streams,
4964 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004965 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004966
Seth Hampson845e8782018-03-02 11:34:10 -08004967 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004968 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004969 for (auto sender_it = current_senders->begin();
4970 sender_it != current_senders->end();
4971 /* incremented manually */) {
4972 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004973 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004974 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4975 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004976 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004977 OnLocalSenderRemoved(info, media_type);
4978 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004979 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004980 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004981 }
4982 }
4983
Steve Anton4171afb2017-11-20 10:20:22 -08004984 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004985 for (const cricket::StreamParams& params : streams) {
4986 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004987 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004988 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004989 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004990 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004991 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004992 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004993 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004994 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004995 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004996 }
4997 }
4998}
4999
Steve Anton4171afb2017-11-20 10:20:22 -08005000void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5001 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005002 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005003 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005004 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005005 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5006 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005007 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005008 return;
5009 }
5010
deadbeeffac06552015-11-25 11:26:01 -08005011 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005012 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005013 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005014 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005015 }
deadbeeffac06552015-11-25 11:26:01 -08005016
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005017 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005018 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005019}
5020
Steve Anton4171afb2017-11-20 10:20:22 -08005021void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5022 cricket::MediaType media_type) {
5023 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005024 if (!sender) {
5025 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005026 // SessionDescriptions has been renegotiated.
5027 return;
5028 }
deadbeeffac06552015-11-25 11:26:01 -08005029
5030 // A sender has been removed from the SessionDescription but it's still
5031 // associated with the PeerConnection. This only occurs if the SDP doesn't
5032 // match with the calls to CreateSender, AddStream and RemoveStream.
5033 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005034 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005035 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005036 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005037 }
deadbeeffac06552015-11-25 11:26:01 -08005038
Steve Anton4171afb2017-11-20 10:20:22 -08005039 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005040}
5041
5042void PeerConnection::UpdateLocalRtpDataChannels(
5043 const cricket::StreamParamsVec& streams) {
5044 std::vector<std::string> existing_channels;
5045
5046 // Find new and active data channels.
5047 for (const cricket::StreamParams& params : streams) {
5048 // |it->sync_label| is actually the data channel label. The reason is that
5049 // we use the same naming of data channels as we do for
5050 // MediaStreams and Tracks.
5051 // For MediaStreams, the sync_label is the MediaStream label and the
5052 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005053 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005054 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005055 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005056 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005057 continue;
5058 }
5059 // Set the SSRC the data channel should use for sending.
5060 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5061 existing_channels.push_back(data_channel_it->first);
5062 }
5063
5064 UpdateClosingRtpDataChannels(existing_channels, true);
5065}
5066
5067void PeerConnection::UpdateRemoteRtpDataChannels(
5068 const cricket::StreamParamsVec& streams) {
5069 std::vector<std::string> existing_channels;
5070
5071 // Find new and active data channels.
5072 for (const cricket::StreamParams& params : streams) {
5073 // The data channel label is either the mslabel or the SSRC if the mslabel
5074 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005075 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005076 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005077 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005078 auto data_channel_it = rtp_data_channels_.find(label);
5079 if (data_channel_it == rtp_data_channels_.end()) {
5080 // This is a new data channel.
5081 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5082 } else {
5083 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5084 }
5085 existing_channels.push_back(label);
5086 }
5087
5088 UpdateClosingRtpDataChannels(existing_channels, false);
5089}
5090
5091void PeerConnection::UpdateClosingRtpDataChannels(
5092 const std::vector<std::string>& active_channels,
5093 bool is_local_update) {
5094 auto it = rtp_data_channels_.begin();
5095 while (it != rtp_data_channels_.end()) {
5096 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005097 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005098 ++it;
5099 continue;
5100 }
5101
5102 if (is_local_update) {
5103 data_channel->SetSendSsrc(0);
5104 } else {
5105 data_channel->RemotePeerRequestClose();
5106 }
5107
5108 if (data_channel->state() == DataChannel::kClosed) {
5109 rtp_data_channels_.erase(it);
5110 it = rtp_data_channels_.begin();
5111 } else {
5112 ++it;
5113 }
5114 }
5115}
5116
5117void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5118 uint32_t remote_ssrc) {
5119 rtc::scoped_refptr<DataChannel> channel(
5120 InternalCreateDataChannel(label, nullptr));
5121 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005122 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005123 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005124 return;
5125 }
5126 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005127 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5128 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005129 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005130}
5131
5132rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5133 const std::string& label,
5134 const InternalDataChannelInit* config) {
5135 if (IsClosed()) {
5136 return nullptr;
5137 }
Steve Anton75737c02017-11-06 10:37:17 -08005138 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005140 << "InternalCreateDataChannel: Data is not supported in this call.";
5141 return nullptr;
5142 }
5143 InternalDataChannelInit new_config =
5144 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005145 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005146 if (new_config.id < 0) {
5147 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005148 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005149 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005150 RTC_LOG(LS_ERROR)
5151 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005152 return nullptr;
5153 }
5154 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005155 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005156 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005157 return nullptr;
5158 }
5159 }
5160
Steve Anton75737c02017-11-06 10:37:17 -08005161 rtc::scoped_refptr<DataChannel> channel(
5162 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005163 if (!channel) {
5164 sid_allocator_.ReleaseSid(new_config.id);
5165 return nullptr;
5166 }
5167
5168 if (channel->data_channel_type() == cricket::DCT_RTP) {
5169 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005170 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5171 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005172 return nullptr;
5173 }
5174 rtp_data_channels_[channel->label()] = channel;
5175 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005176 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005177 sctp_data_channels_.push_back(channel);
5178 channel->SignalClosed.connect(this,
5179 &PeerConnection::OnSctpDataChannelClosed);
5180 }
5181
Steve Anton2d8609c2018-01-23 16:38:46 -08005182 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005183 return channel;
5184}
5185
5186bool PeerConnection::HasDataChannels() const {
5187 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5188}
5189
5190void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005191 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005192 for (const auto& channel : sctp_data_channels_) {
5193 if (channel->id() < 0) {
5194 int sid;
5195 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005196 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5197 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005198 continue;
5199 }
5200 channel->SetSctpSid(sid);
5201 }
5202 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005203 // Since closing modifies the list of channels, we have to do the actual
5204 // closing outside the loop.
5205 for (const auto& channel : channels_to_close) {
5206 channel->CloseAbruptly();
5207 }
deadbeefab9b2d12015-10-14 11:33:11 -07005208}
5209
5210void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005211 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005212 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5213 ++it) {
5214 if (it->get() == channel) {
5215 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005216 // After the closing procedure is done, it's safe to use this ID for
5217 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005218 sid_allocator_.ReleaseSid(channel->id());
5219 }
deadbeefbd292462015-12-14 18:15:29 -08005220 // Since this method is triggered by a signal from the DataChannel,
5221 // we can't free it directly here; we need to free it asynchronously.
5222 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005223 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005224 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5225 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005226 return;
5227 }
5228 }
5229}
5230
deadbeefab9b2d12015-10-14 11:33:11 -07005231void PeerConnection::OnDataChannelDestroyed() {
5232 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5233 // DataChannel may callback to us and try to modify the list.
5234 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5235 temp_rtp_dcs.swap(rtp_data_channels_);
5236 for (const auto& kv : temp_rtp_dcs) {
5237 kv.second->OnTransportChannelDestroyed();
5238 }
5239
5240 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5241 temp_sctp_dcs.swap(sctp_data_channels_);
5242 for (const auto& channel : temp_sctp_dcs) {
5243 channel->OnTransportChannelDestroyed();
5244 }
5245}
5246
5247void PeerConnection::OnDataChannelOpenMessage(
5248 const std::string& label,
5249 const InternalDataChannelInit& config) {
5250 rtc::scoped_refptr<DataChannel> channel(
5251 InternalCreateDataChannel(label, &config));
5252 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005253 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005254 return;
5255 }
5256
deadbeefa601f5c2016-06-06 14:27:39 -07005257 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5258 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005259 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005260 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005261}
5262
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005263bool PeerConnection::HandleOpenMessage_s(
5264 const cricket::ReceiveDataParams& params,
5265 const rtc::CopyOnWriteBuffer& buffer) {
5266 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5267 // Received OPEN message; parse and signal that a new data channel should
5268 // be created.
5269 std::string label;
5270 InternalDataChannelInit config;
5271 config.id = params.ssrc;
5272 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5273 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5274 << params.ssrc;
5275 return true;
5276 }
5277 config.open_handshake_role = InternalDataChannelInit::kAcker;
5278 OnDataChannelOpenMessage(label, config);
5279 return true;
5280 }
5281 return false;
5282}
5283
Steve Anton4171afb2017-11-20 10:20:22 -08005284rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5285PeerConnection::GetAudioTransceiver() const {
5286 // This method only works with Plan B SDP, where there is a single
5287 // audio/video transceiver.
5288 RTC_DCHECK(!IsUnifiedPlan());
5289 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005290 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005291 return transceiver;
5292 }
5293 }
5294 RTC_NOTREACHED();
5295 return nullptr;
5296}
5297
5298rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5299PeerConnection::GetVideoTransceiver() const {
5300 // This method only works with Plan B SDP, where there is a single
5301 // audio/video transceiver.
5302 RTC_DCHECK(!IsUnifiedPlan());
5303 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005304 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005305 return transceiver;
5306 }
5307 }
5308 RTC_NOTREACHED();
5309 return nullptr;
5310}
5311
5312// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5313// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005314bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005315 switch (type) {
5316 case cricket::MEDIA_TYPE_AUDIO:
5317 return !GetAudioTransceiver()->internal()->senders().empty();
5318 case cricket::MEDIA_TYPE_VIDEO:
5319 return !GetVideoTransceiver()->internal()->senders().empty();
5320 case cricket::MEDIA_TYPE_DATA:
5321 return false;
5322 }
5323 RTC_NOTREACHED();
5324 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005325}
5326
Steve Anton4171afb2017-11-20 10:20:22 -08005327rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5328PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005329 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005330 for (auto sender : transceiver->internal()->senders()) {
5331 if (sender->track() == track) {
5332 return sender;
5333 }
5334 }
5335 }
5336 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005337}
5338
Steve Anton4171afb2017-11-20 10:20:22 -08005339rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5340PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005341 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005342 for (auto sender : transceiver->internal()->senders()) {
5343 if (sender->id() == sender_id) {
5344 return sender;
5345 }
5346 }
5347 }
5348 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005349}
5350
Steve Anton4171afb2017-11-20 10:20:22 -08005351rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5352PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005353 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005354 for (auto receiver : transceiver->internal()->receivers()) {
5355 if (receiver->id() == receiver_id) {
5356 return receiver;
5357 }
5358 }
5359 }
5360 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005361}
5362
Steve Anton4171afb2017-11-20 10:20:22 -08005363std::vector<PeerConnection::RtpSenderInfo>*
5364PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5365 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5366 media_type == cricket::MEDIA_TYPE_VIDEO);
5367 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5368 ? &remote_audio_sender_infos_
5369 : &remote_video_sender_infos_;
5370}
5371
5372std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005373 cricket::MediaType media_type) {
5374 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5375 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005376 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5377 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005378}
5379
Steve Anton4171afb2017-11-20 10:20:22 -08005380const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5381 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005382 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005383 const std::string sender_id) const {
5384 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005385 if (sender_info.stream_id == stream_id &&
5386 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005387 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005388 }
5389 }
5390 return nullptr;
5391}
5392
5393DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5394 for (const auto& channel : sctp_data_channels_) {
5395 if (channel->id() == sid) {
5396 return channel;
5397 }
5398 }
5399 return nullptr;
5400}
5401
Karl Wibergfb3be392019-03-22 14:13:22 +01005402PeerConnection::InitializePortAllocatorResult
5403PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005404 const cricket::ServerAddresses& stun_servers,
5405 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005406 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005407 RTC_DCHECK_RUN_ON(network_thread());
5408
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005409 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005410 // To handle both internal and externally created port allocator, we will
5411 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005412 int port_allocator_flags = port_allocator_->flags();
5413 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5414 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5415 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005416 // If the disable-IPv6 flag was specified, we'll not override it
5417 // by experiment.
5418 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005419 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005420 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5421 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005422 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423 }
5424
zhihuangb09b3f92017-03-07 14:40:51 -08005425 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005426 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005427 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005428 }
5429
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005430 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005431 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005432 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005433 }
5434
honghaiz60347052016-05-31 18:29:12 -07005435 if (configuration.candidate_network_policy ==
5436 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005437 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005438 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005439 }
5440
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005441 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005442 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005443 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5444 }
5445
Karl Wibergfb3be392019-03-22 14:13:22 +01005446 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005447 // No step delay is used while allocating ports.
5448 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005449 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005450 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005451 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005452
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005453 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005454 for (auto& turn_server : turn_servers_copy) {
5455 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005456 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005457 // Call this last since it may create pooled allocator sessions using the
5458 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005459 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005460 stun_servers, std::move(turn_servers_copy),
5461 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5462 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005463 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005464
5465 InitializePortAllocatorResult res;
5466 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5467 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005468}
5469
deadbeef91dd5672016-05-18 16:55:30 -07005470bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005471 const cricket::ServerAddresses& stun_servers,
5472 const std::vector<cricket::RelayServerConfig>& turn_servers,
5473 IceTransportsType type,
5474 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005475 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005476 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005477 absl::optional<int> stun_candidate_keepalive_interval,
5478 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005479 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005480 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005481 // According to JSEP, after setLocalDescription, changing the candidate pool
5482 // size is not allowed, and changing the set of ICE servers will not result
5483 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005484 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005485 port_allocator_->FreezeCandidatePool();
5486 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005487 // Add the custom tls turn servers if they exist.
5488 auto turn_servers_copy = turn_servers;
5489 for (auto& turn_server : turn_servers_copy) {
5490 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5491 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005492 // Call this last since it may create pooled allocator sessions using the
5493 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005494 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005495 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5496 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005497}
5498
Steve Antonba818672017-11-06 10:21:57 -08005499cricket::ChannelManager* PeerConnection::channel_manager() const {
5500 return factory_->channel_manager();
5501}
5502
Elad Alon99c3fe52017-10-13 16:29:40 +02005503bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005504 std::unique_ptr<RtcEventLogOutput> output,
5505 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005506 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005507 if (!event_log_) {
5508 return false;
5509 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005510 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005511}
5512
5513void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005514 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005515 if (event_log_) {
5516 event_log_->StopLogging();
5517 }
ivoc14d5dbe2016-07-04 07:06:55 -07005518}
nisseeaabdf62017-05-05 02:23:02 -07005519
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005520cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005521 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005522 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005523 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005524 if (channel && channel->content_name() == content_name) {
5525 return channel;
5526 }
Steve Anton75737c02017-11-06 10:37:17 -08005527 }
5528 if (rtp_data_channel() &&
5529 rtp_data_channel()->content_name() == content_name) {
5530 return rtp_data_channel();
5531 }
5532 return nullptr;
5533}
5534
5535bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005536 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005537 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005538 RTC_LOG(LS_INFO)
5539 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005540 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005541 return false;
5542 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005543 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005544 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005545 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005546 return false;
5547 }
5548
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005549 absl::optional<rtc::SSLRole> dtls_role;
5550 if (sctp_mid_) {
5551 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5552 } else if (is_caller_) {
5553 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5554 }
Zhi Huange830e682018-03-30 10:48:35 -07005555 if (dtls_role) {
5556 *role = *dtls_role;
5557 return true;
5558 }
5559 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005560}
5561
5562bool PeerConnection::GetSslRole(const std::string& content_name,
5563 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005564 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005565 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005566 RTC_LOG(LS_INFO)
5567 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005568 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005569 return false;
5570 }
5571
Zhi Huange830e682018-03-30 10:48:35 -07005572 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5573 if (dtls_role) {
5574 *role = *dtls_role;
5575 return true;
5576 }
5577 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005578}
5579
Steve Antonf8470812017-12-04 10:46:21 -08005580void PeerConnection::SetSessionError(SessionError error,
5581 const std::string& error_desc) {
5582 RTC_DCHECK_RUN_ON(signaling_thread());
5583 if (error != session_error_) {
5584 session_error_ = error;
5585 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005586 }
5587}
5588
Zhi Huange830e682018-03-30 10:48:35 -07005589RTCError PeerConnection::UpdateSessionState(
5590 SdpType type,
5591 cricket::ContentSource source,
5592 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005593 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005594
5595 // If there's already a pending error then no state transition should happen.
5596 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005597 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005598
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005599 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005600 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005601 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005602 }
5603
5604 // Update the signaling state according to the specified state machine (see
5605 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005606 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005607 ChangeSignalingState(source == cricket::CS_LOCAL
5608 ? PeerConnectionInterface::kHaveLocalOffer
5609 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005610 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005611 ChangeSignalingState(source == cricket::CS_LOCAL
5612 ? PeerConnectionInterface::kHaveLocalPrAnswer
5613 : PeerConnectionInterface::kHaveRemotePrAnswer);
5614 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005615 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005616 ChangeSignalingState(PeerConnectionInterface::kStable);
5617 }
5618
5619 // Update internal objects according to the session description's media
5620 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005621 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005622 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005623 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005624 }
5625
Steve Anton8a006912017-12-04 15:25:56 -08005626 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005627}
5628
Steve Anton8a006912017-12-04 15:25:56 -08005629RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005630 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005631 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005632 const SessionDescriptionInterface* sdesc =
5633 (source == cricket::CS_LOCAL ? local_description()
5634 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005635 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005636
5637 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005638 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005639 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005640 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005641 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005642 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005643 continue;
5644 }
5645 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005646 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005647 if (!content_desc) {
5648 continue;
5649 }
5650 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005651 bool success = (source == cricket::CS_LOCAL)
5652 ? channel->SetLocalContent(content_desc, type, &error)
5653 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005654 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005656 }
5657 }
5658
5659 // If using the RtpDataChannel, push down the new SDP section for it too.
5660 if (rtp_data_channel_) {
5661 const ContentInfo* data_content =
5662 cricket::GetFirstDataContent(sdesc->description());
5663 if (data_content && !data_content->rejected) {
5664 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005665 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005666 if (data_desc) {
5667 std::string error;
5668 bool success =
5669 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005670 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005671 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005672 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005674 }
Steve Anton75737c02017-11-06 10:37:17 -08005675 }
5676 }
5677 }
Steve Antoned10bd92017-12-05 10:52:59 -08005678
Steve Anton75737c02017-11-06 10:37:17 -08005679 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5680 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005681 if (sctp_transport_ && local_description() && remote_description()) {
5682 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5683 local_description()->description());
5684 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5685 remote_description()->description());
5686 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005687 int max_message_size;
5688 // A remote max message size of zero means "any size supported".
5689 // We configure the connection with our own max message size.
5690 if (remote_sctp_description->max_message_size() == 0) {
5691 max_message_size = local_sctp_description->max_message_size();
5692 } else {
5693 max_message_size =
5694 std::min(local_sctp_description->max_message_size(),
5695 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005696 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005697 sctp_transport_->Start(local_sctp_description->port(),
5698 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005699 }
Steve Anton75737c02017-11-06 10:37:17 -08005700 }
Steve Antoned10bd92017-12-05 10:52:59 -08005701
Steve Anton8a006912017-12-04 15:25:56 -08005702 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005703}
5704
Steve Anton8a006912017-12-04 15:25:56 -08005705RTCError PeerConnection::PushdownTransportDescription(
5706 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005707 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005708 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005709
Zhi Huange830e682018-03-30 10:48:35 -07005710 if (source == cricket::CS_LOCAL) {
5711 const SessionDescriptionInterface* sdesc = local_description();
5712 RTC_DCHECK(sdesc);
5713 return transport_controller_->SetLocalDescription(type,
5714 sdesc->description());
5715 } else {
5716 const SessionDescriptionInterface* sdesc = remote_description();
5717 RTC_DCHECK(sdesc);
5718 return transport_controller_->SetRemoteDescription(type,
5719 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005720 }
Steve Anton75737c02017-11-06 10:37:17 -08005721}
5722
5723bool PeerConnection::GetTransportDescription(
5724 const SessionDescription* description,
5725 const std::string& content_name,
5726 cricket::TransportDescription* tdesc) {
5727 if (!description || !tdesc) {
5728 return false;
5729 }
5730 const TransportInfo* transport_info =
5731 description->GetTransportInfoByName(content_name);
5732 if (!transport_info) {
5733 return false;
5734 }
5735 *tdesc = transport_info->description;
5736 return true;
5737}
5738
Steve Anton75737c02017-11-06 10:37:17 -08005739cricket::IceConfig PeerConnection::ParseIceConfig(
5740 const PeerConnectionInterface::RTCConfiguration& config) const {
5741 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005742 switch (config.continual_gathering_policy) {
5743 case PeerConnectionInterface::GATHER_ONCE:
5744 gathering_policy = cricket::GATHER_ONCE;
5745 break;
5746 case PeerConnectionInterface::GATHER_CONTINUALLY:
5747 gathering_policy = cricket::GATHER_CONTINUALLY;
5748 break;
5749 default:
5750 RTC_NOTREACHED();
5751 gathering_policy = cricket::GATHER_ONCE;
5752 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005753
Steve Anton75737c02017-11-06 10:37:17 -08005754 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005755 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5756 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005757 ice_config.prioritize_most_likely_candidate_pairs =
5758 config.prioritize_most_likely_ice_candidate_pairs;
5759 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005760 RTCConfigurationToIceConfigOptionalInt(
5761 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005762 ice_config.continual_gathering_policy = gathering_policy;
5763 ice_config.presume_writable_when_fully_relayed =
5764 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005765 ice_config.ice_check_interval_strong_connectivity =
5766 config.ice_check_interval_strong_connectivity;
5767 ice_config.ice_check_interval_weak_connectivity =
5768 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005769 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005770 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5771 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005772 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005773 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005774 ice_config.regather_all_networks_interval_range =
5775 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005776 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005777 return ice_config;
5778}
5779
Steve Anton75737c02017-11-06 10:37:17 -08005780bool PeerConnection::SendData(const cricket::SendDataParams& params,
5781 const rtc::CopyOnWriteBuffer& payload,
5782 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005783 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005784 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5785 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5786 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005787 return false;
5788 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005789 if (media_transport_) {
5790 SendDataParams send_params;
5791 send_params.type = ToWebrtcDataMessageType(params.type);
5792 send_params.ordered = params.ordered;
5793 if (params.max_rtx_count >= 0) {
5794 send_params.max_rtx_count = params.max_rtx_count;
5795 } else if (params.max_rtx_ms >= 0) {
5796 send_params.max_rtx_ms = params.max_rtx_ms;
5797 }
5798 return media_transport_->SendData(params.sid, send_params, payload).ok();
5799 }
Steve Anton75737c02017-11-06 10:37:17 -08005800 return rtp_data_channel_
5801 ? rtp_data_channel_->SendData(params, payload, result)
5802 : network_thread()->Invoke<bool>(
5803 RTC_FROM_HERE,
5804 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005805 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005806}
5807
5808bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005809 RTC_DCHECK_RUN_ON(signaling_thread());
5810 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005811 // Don't log an error here, because DataChannels are expected to call
5812 // ConnectDataChannel in this state. It's the only way to initially tell
5813 // whether or not the underlying transport is ready.
5814 return false;
5815 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005816 if (media_transport_) {
5817 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5818 &DataChannel::OnChannelReady);
5819 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5820 &DataChannel::OnDataReceived);
5821 SignalMediaTransportChannelClosing_s.connect(
5822 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5823 SignalMediaTransportChannelClosed_s.connect(
5824 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5825 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005826 rtp_data_channel_->SignalReadyToSendData.connect(
5827 webrtc_data_channel, &DataChannel::OnChannelReady);
5828 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5829 &DataChannel::OnDataReceived);
5830 } else {
5831 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5832 &DataChannel::OnChannelReady);
5833 SignalSctpDataReceived.connect(webrtc_data_channel,
5834 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005835 SignalSctpClosingProcedureStartedRemotely.connect(
5836 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5837 SignalSctpClosingProcedureComplete.connect(
5838 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005839 }
5840 return true;
5841}
5842
5843void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005844 RTC_DCHECK_RUN_ON(signaling_thread());
5845 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005846 RTC_LOG(LS_ERROR)
5847 << "DisconnectDataChannel called when rtp_data_channel_ and "
5848 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005849 return;
5850 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005851 if (media_transport_) {
5852 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5853 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5854 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5855 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5856 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005857 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5858 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5859 } else {
5860 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5861 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005862 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5863 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005864 }
5865}
5866
5867void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005868 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005869 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005870 return;
5871 }
Steve Anton75737c02017-11-06 10:37:17 -08005872 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005873 RTC_LOG(LS_ERROR)
5874 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005875 return;
5876 }
5877 network_thread()->Invoke<void>(
5878 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005879 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005880}
5881
5882void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005883 if (media_transport_) {
5884 media_transport_->CloseChannel(sid);
5885 return;
5886 }
Steve Anton75737c02017-11-06 10:37:17 -08005887 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005888 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005889 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005890 return;
5891 }
5892 network_thread()->Invoke<void>(
5893 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005894 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005895}
5896
5897bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005898 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005899 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005900 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005901 sctp_ready_to_send_data_;
5902}
5903
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005904void PeerConnection::OnDataReceived(int channel_id,
5905 DataMessageType type,
5906 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005907 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005908 cricket::ReceiveDataParams params;
5909 params.sid = channel_id;
5910 params.type = ToCricketDataMessageType(type);
5911 media_transport_invoker_->AsyncInvoke<void>(
5912 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5913 RTC_DCHECK_RUN_ON(signaling_thread());
5914 if (!HandleOpenMessage_s(params, buffer)) {
5915 SignalMediaTransportReceivedData_s(params, buffer);
5916 }
5917 });
5918}
5919
5920void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005921 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005922 media_transport_invoker_->AsyncInvoke<void>(
5923 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5924 RTC_DCHECK_RUN_ON(signaling_thread());
5925 SignalMediaTransportChannelClosing_s(channel_id);
5926 });
5927}
5928
5929void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005930 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005931 media_transport_invoker_->AsyncInvoke<void>(
5932 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5933 RTC_DCHECK_RUN_ON(signaling_thread());
5934 SignalMediaTransportChannelClosed_s(channel_id);
5935 });
5936}
5937
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005938absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005939 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005940 if (sctp_mid_ && transport_controller_) {
5941 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5942 if (dtls_transport) {
5943 return dtls_transport->transport_name();
5944 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005945 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005946 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005947 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005948}
5949
Qingsi Wang72a43a12018-02-20 16:03:18 -08005950cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5951 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005952 network_thread()->Invoke<void>(
5953 RTC_FROM_HERE,
5954 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5955 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005956 return candidate_states_list;
5957}
5958
Steve Anton5dfde182018-02-06 10:34:40 -08005959std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5960 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005961 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005962 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005963 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005964 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005965 if (channel) {
5966 transport_names_by_mid[channel->content_name()] =
5967 channel->transport_name();
5968 }
Steve Anton75737c02017-11-06 10:37:17 -08005969 }
Steve Anton5dfde182018-02-06 10:34:40 -08005970 if (rtp_data_channel_) {
5971 transport_names_by_mid[rtp_data_channel_->content_name()] =
5972 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005973 }
5974 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005975 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005976 RTC_DCHECK(transport_name);
5977 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005978 }
Steve Anton5dfde182018-02-06 10:34:40 -08005979 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005980}
5981
Steve Anton5dfde182018-02-06 10:34:40 -08005982std::map<std::string, cricket::TransportStats>
5983PeerConnection::GetTransportStatsByNames(
5984 const std::set<std::string>& transport_names) {
5985 if (!network_thread()->IsCurrent()) {
5986 return network_thread()
5987 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5988 RTC_FROM_HERE,
5989 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005990 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005991 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005992 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5993 for (const std::string& transport_name : transport_names) {
5994 cricket::TransportStats transport_stats;
5995 bool success =
5996 transport_controller_->GetStats(transport_name, &transport_stats);
5997 if (success) {
5998 transport_stats_by_name[transport_name] = std::move(transport_stats);
5999 } else {
6000 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6001 << transport_name;
6002 }
6003 }
6004 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006005}
6006
6007bool PeerConnection::GetLocalCertificate(
6008 const std::string& transport_name,
6009 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006010 if (!certificate) {
6011 return false;
6012 }
6013 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6014 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006015}
6016
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006017std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006018 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006019 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006020}
6021
6022cricket::DataChannelType PeerConnection::data_channel_type() const {
6023 return data_channel_type_;
6024}
6025
6026bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006027 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006028 return pending_ice_restarts_.find(content_name) !=
6029 pending_ice_restarts_.end();
6030}
6031
Steve Anton75737c02017-11-06 10:37:17 -08006032bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6033 return transport_controller_->NeedsIceRestart(content_name);
6034}
6035
6036void PeerConnection::OnCertificateReady(
6037 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6038 transport_controller_->SetLocalCertificate(certificate);
6039}
6040
6041void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006042 SetSessionError(SessionError::kTransport,
6043 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006044}
6045
Alex Loiko9289eda2018-11-23 16:18:59 +00006046void PeerConnection::OnTransportControllerConnectionState(
6047 cricket::IceConnectionState state) {
6048 switch (state) {
6049 case cricket::kIceConnectionConnecting:
6050 // If the current state is Connected or Completed, then there were
6051 // writable channels but now there are not, so the next state must
6052 // be Disconnected.
6053 // kIceConnectionConnecting is currently used as the default,
6054 // un-connected state by the TransportController, so its only use is
6055 // detecting disconnections.
6056 if (ice_connection_state_ ==
6057 PeerConnectionInterface::kIceConnectionConnected ||
6058 ice_connection_state_ ==
6059 PeerConnectionInterface::kIceConnectionCompleted) {
6060 SetIceConnectionState(
6061 PeerConnectionInterface::kIceConnectionDisconnected);
6062 }
6063 break;
6064 case cricket::kIceConnectionFailed:
6065 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6066 break;
6067 case cricket::kIceConnectionConnected:
6068 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6069 "all transports are writable.";
6070 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6071 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6072 break;
6073 case cricket::kIceConnectionCompleted:
6074 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6075 "all transports are complete.";
6076 if (ice_connection_state_ !=
6077 PeerConnectionInterface::kIceConnectionConnected) {
6078 // If jumping directly from "checking" to "connected",
6079 // signal "connected" first.
6080 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6081 }
6082 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6083 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6084 ReportTransportStats();
6085 break;
6086 default:
6087 RTC_NOTREACHED();
6088 }
6089}
6090
Steve Anton75737c02017-11-06 10:37:17 -08006091void PeerConnection::OnTransportControllerCandidatesGathered(
6092 const std::string& transport_name,
6093 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006094 int sdp_mline_index;
6095 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006096 RTC_LOG(LS_ERROR)
6097 << "OnTransportControllerCandidatesGathered: content name "
6098 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006099 return;
6100 }
6101
6102 for (cricket::Candidates::const_iterator citer = candidates.begin();
6103 citer != candidates.end(); ++citer) {
6104 // Use transport_name as the candidate media id.
6105 std::unique_ptr<JsepIceCandidate> candidate(
6106 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6107 if (local_description()) {
6108 mutable_local_description()->AddCandidate(candidate.get());
6109 }
6110 OnIceCandidate(std::move(candidate));
6111 }
6112}
6113
6114void PeerConnection::OnTransportControllerCandidatesRemoved(
6115 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006116 // Sanity check.
6117 for (const cricket::Candidate& candidate : candidates) {
6118 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006119 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006120 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006121 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006122 return;
6123 }
6124 }
6125
6126 if (local_description()) {
6127 mutable_local_description()->RemoveCandidates(candidates);
6128 }
6129 OnIceCandidatesRemoved(candidates);
6130}
6131
6132void PeerConnection::OnTransportControllerDtlsHandshakeError(
6133 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006134 RTC_HISTOGRAM_ENUMERATION(
6135 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6136 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006137}
6138
Steve Antoned10bd92017-12-05 10:52:59 -08006139void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006140 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006141 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006142 if (channel && !channel->enabled()) {
6143 channel->Enable(true);
6144 }
Steve Anton75737c02017-11-06 10:37:17 -08006145 }
6146
Steve Anton4171afb2017-11-20 10:20:22 -08006147 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006148 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006149 }
Steve Anton75737c02017-11-06 10:37:17 -08006150}
6151
6152// Returns the media index for a local ice candidate given the content name.
6153bool PeerConnection::GetLocalCandidateMediaIndex(
6154 const std::string& content_name,
6155 int* sdp_mline_index) {
6156 if (!local_description() || !sdp_mline_index) {
6157 return false;
6158 }
6159
6160 bool content_found = false;
6161 const ContentInfos& contents = local_description()->description()->contents();
6162 for (size_t index = 0; index < contents.size(); ++index) {
6163 if (contents[index].name == content_name) {
6164 *sdp_mline_index = static_cast<int>(index);
6165 content_found = true;
6166 break;
6167 }
6168 }
6169 return content_found;
6170}
6171
6172bool PeerConnection::UseCandidatesInSessionDescription(
6173 const SessionDescriptionInterface* remote_desc) {
6174 if (!remote_desc) {
6175 return true;
6176 }
6177 bool ret = true;
6178
6179 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6180 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6181 for (size_t n = 0; n < candidates->count(); ++n) {
6182 const IceCandidateInterface* candidate = candidates->at(n);
6183 bool valid = false;
6184 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6185 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006186 RTC_LOG(LS_INFO)
6187 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006188 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006189 }
6190 continue;
6191 }
6192 ret = UseCandidate(candidate);
6193 if (!ret) {
6194 break;
6195 }
6196 }
6197 }
6198 return ret;
6199}
6200
6201bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006202 RTCErrorOr<const cricket::ContentInfo*> result =
6203 FindContentInfo(remote_description(), candidate);
6204 if (!result.ok()) {
6205 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6206 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006207 return false;
6208 }
Steve Anton75737c02017-11-06 10:37:17 -08006209 std::vector<cricket::Candidate> candidates;
6210 candidates.push_back(candidate->candidate());
6211 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006212 RTCError error = transport_controller_->AddRemoteCandidates(
6213 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006214 if (error.ok()) {
6215 // Candidates successfully submitted for checking.
6216 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6217 ice_connection_state_ ==
6218 PeerConnectionInterface::kIceConnectionDisconnected) {
6219 // If state is New, then the session has just gotten its first remote ICE
6220 // candidates, so go to Checking.
6221 // If state is Disconnected, the session is re-using old candidates or
6222 // receiving additional ones, so go to Checking.
6223 // If state is Connected, stay Connected.
6224 // TODO(bemasc): If state is Connected, and the new candidates are for a
6225 // newly added transport, then the state actually _should_ move to
6226 // checking. Add a way to distinguish that case.
6227 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6228 }
6229 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006230 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006231 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
6233 return true;
6234}
6235
Guido Urdaneta41633172019-05-23 20:12:29 +02006236RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6237 const SessionDescriptionInterface* description,
6238 const IceCandidateInterface* candidate) {
6239 if (candidate->sdp_mline_index() >= 0) {
6240 size_t mediacontent_index =
6241 static_cast<size_t>(candidate->sdp_mline_index());
6242 size_t content_size = description->description()->contents().size();
6243 if (mediacontent_index < content_size) {
6244 return &description->description()->contents()[mediacontent_index];
6245 } else {
6246 return RTCError(RTCErrorType::INVALID_RANGE,
6247 "Media line index (" +
6248 rtc::ToString(candidate->sdp_mline_index()) +
6249 ") out of range (number of mlines: " +
6250 rtc::ToString(content_size) + ").");
6251 }
6252 } else if (!candidate->sdp_mid().empty()) {
6253 auto& contents = description->description()->contents();
6254 auto it = absl::c_find_if(
6255 contents, [candidate](const cricket::ContentInfo& content_info) {
6256 return content_info.mid() == candidate->sdp_mid();
6257 });
6258 if (it == contents.end()) {
6259 return RTCError(
6260 RTCErrorType::INVALID_PARAMETER,
6261 "Mid " + candidate->sdp_mid() +
6262 " specified but no media section with that mid found.");
6263 } else {
6264 return &*it;
6265 }
6266 }
6267
6268 return RTCError(RTCErrorType::INVALID_PARAMETER,
6269 "Neither sdp_mline_index nor sdp_mid specified.");
6270}
6271
Steve Anton75737c02017-11-06 10:37:17 -08006272void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006273 // Destroy video channel first since it may have a pointer to the
6274 // voice channel.
6275 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006276 if (!video_info || video_info->rejected) {
6277 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006278 }
6279
Steve Anton6fec8802017-12-04 10:37:29 -08006280 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6281 if (!audio_info || audio_info->rejected) {
6282 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006283 }
6284
6285 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6286 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006287 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006288 }
6289}
6290
Steve Antondcc3c022017-12-22 16:02:54 -08006291RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6292 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006293 const cricket::ContentGroup* bundle_group = nullptr;
6294 if (configuration_.bundle_policy ==
6295 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006296 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006297 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6299 "max-bundle configured but session description "
6300 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006301 }
6302 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006303 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006304}
6305
6306RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006307 // Creating the media channels. Transports should already have been created
6308 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006309 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006310 if (voice && !voice->rejected &&
6311 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006312 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006313 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006314 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6315 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006316 }
6317 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6318 }
6319
Steve Antondcc3c022017-12-22 16:02:54 -08006320 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006321 if (video && !video->rejected &&
6322 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006323 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006324 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006325 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6326 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006327 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006328 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006329 }
6330
Steve Antondcc3c022017-12-22 16:02:54 -08006331 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006332 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006333 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006334 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006335 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6336 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006337 }
6338 }
6339
Steve Anton8a006912017-12-04 15:25:56 -08006340 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006341}
6342
Steve Anton4171afb2017-11-20 10:20:22 -08006343// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006344cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006345 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006346 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006347 MediaTransportConfig media_transport_config =
6348 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006349
Steve Anton75737c02017-11-06 10:37:17 -08006350 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006351 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006352 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6353 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006354 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006355 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006356 }
Steve Anton75737c02017-11-06 10:37:17 -08006357 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6358 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006359 voice_channel->SignalSentPacket.connect(this,
6360 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006361 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006362
Steve Antoneda6ccd2017-12-04 10:21:55 -08006363 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006364}
6365
Steve Anton4171afb2017-11-20 10:20:22 -08006366// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006367cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006368 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006369 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006370 MediaTransportConfig media_transport_config =
6371 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006372
Steve Anton75737c02017-11-06 10:37:17 -08006373 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006374 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006375 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6376 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006377 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006378 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006379 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006380 }
Steve Anton75737c02017-11-06 10:37:17 -08006381 video_channel->SignalDtlsSrtpSetupFailure.connect(
6382 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006383 video_channel->SignalSentPacket.connect(this,
6384 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006385 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006386
Steve Antoneda6ccd2017-12-04 10:21:55 -08006387 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006388}
6389
Zhi Huange830e682018-03-30 10:48:35 -07006390bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006391 switch (data_channel_type_) {
6392 case cricket::DCT_MEDIA_TRANSPORT:
6393 if (network_thread()->Invoke<bool>(
6394 RTC_FROM_HERE,
6395 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6396 this, mid))) {
6397 for (const auto& channel : sctp_data_channels_) {
6398 channel->OnTransportChannelCreated();
6399 }
6400 return true;
6401 }
Steve Anton75737c02017-11-06 10:37:17 -08006402 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006403 case cricket::DCT_SCTP:
6404 if (!sctp_factory_) {
6405 RTC_LOG(LS_ERROR)
6406 << "Trying to create SCTP transport, but didn't compile with "
6407 "SCTP support (HAVE_SCTP)";
6408 return false;
6409 }
6410 if (!network_thread()->Invoke<bool>(
6411 RTC_FROM_HERE,
6412 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6413 return false;
6414 }
6415 for (const auto& channel : sctp_data_channels_) {
6416 channel->OnTransportChannelCreated();
6417 }
6418 return true;
6419 case cricket::DCT_RTP:
6420 default:
6421 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6422 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6423 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006424 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006425 if (!rtp_data_channel_) {
6426 return false;
6427 }
6428 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6429 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6430 rtp_data_channel_->SignalSentPacket.connect(
6431 this, &PeerConnection::OnSentPacket_w);
6432 rtp_data_channel_->SetRtpTransport(rtp_transport);
6433 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006434 }
6435
Steve Anton75737c02017-11-06 10:37:17 -08006436 return true;
6437}
6438
6439Call::Stats PeerConnection::GetCallStats() {
6440 if (!worker_thread()->IsCurrent()) {
6441 return worker_thread()->Invoke<Call::Stats>(
6442 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6443 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006444 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006445 if (call_) {
6446 return call_->GetStats();
6447 } else {
6448 return Call::Stats();
6449 }
6450}
6451
Zhi Huange830e682018-03-30 10:48:35 -07006452bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006453 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006454 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006455 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6456 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006457 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006458 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006459 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006460 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6461 sctp_factory_->CreateSctpTransport(dtls_transport);
6462 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006463 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006464 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006465 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006466 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006467 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006468 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6469 // another thread. Would be nice if there was a helper class similar to
6470 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6471 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006472 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006473 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006474 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006475 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006476 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006477 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6478 std::move(cricket_sctp_transport));
6479 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006480 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006481}
6482
6483void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006484 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006485 sctp_transport_->Clear();
6486 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006487 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006488 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006489}
6490
6491void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006492 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006493 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006494 // Note: Cannot use rtc::Bind here because it will grab a reference to
6495 // PeerConnection and potentially cause PeerConnection to live longer than
6496 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6497 // be destroyed before PeerConnection is destroyed, and at that point all
6498 // pending tasks will be cleared.
6499 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6500 OnSctpTransportReadyToSendData_s(true);
6501 });
6502}
6503
6504void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006505 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006506 sctp_ready_to_send_data_ = ready;
6507 SignalSctpReadyToSendData(ready);
6508}
6509
6510void PeerConnection::OnSctpTransportDataReceived_n(
6511 const cricket::ReceiveDataParams& params,
6512 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006513 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006514 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006515 // Note: Cannot use rtc::Bind here because it will grab a reference to
6516 // PeerConnection and potentially cause PeerConnection to live longer than
6517 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6518 // be destroyed before PeerConnection is destroyed, and at that point all
6519 // pending tasks will be cleared.
6520 sctp_invoker_->AsyncInvoke<void>(
6521 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6522 OnSctpTransportDataReceived_s(params, payload);
6523 });
6524}
6525
6526void PeerConnection::OnSctpTransportDataReceived_s(
6527 const cricket::ReceiveDataParams& params,
6528 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006529 RTC_DCHECK_RUN_ON(signaling_thread());
6530 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006531 SignalSctpDataReceived(params, payload);
6532 }
6533}
6534
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006535void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006536 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006537 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006538 sctp_invoker_->AsyncInvoke<void>(
6539 RTC_FROM_HERE, signaling_thread(),
6540 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006541 &SignalSctpClosingProcedureStartedRemotely, sid));
6542}
6543
6544void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006545 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006546 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006547 sctp_invoker_->AsyncInvoke<void>(
6548 RTC_FROM_HERE, signaling_thread(),
6549 rtc::Bind(&sigslot::signal1<int>::operator(),
6550 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006551}
6552
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006553bool PeerConnection::SetupMediaTransportForDataChannels_n(
6554 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006555 media_transport_ =
6556 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006557 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006558 RTC_LOG(LS_ERROR)
6559 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006560 return false;
6561 }
6562
6563 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6564 media_transport_->SetDataSink(this);
6565 media_transport_data_mid_ = mid;
6566 transport_controller_->SignalMediaTransportStateChanged.connect(
6567 this, &PeerConnection::OnMediaTransportStateChanged_n);
6568 // Check the initial state right away, in case transport is already writable.
6569 OnMediaTransportStateChanged_n();
6570 return true;
6571}
6572
6573void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6574 if (!media_transport_) {
6575 return;
6576 }
6577 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6578 media_transport_data_mid_.reset();
6579 media_transport_->SetDataSink(nullptr);
6580 media_transport_invoker_ = nullptr;
6581 media_transport_ = nullptr;
6582}
6583
6584void PeerConnection::OnMediaTransportStateChanged_n() {
6585 if (!media_transport_data_mid_ ||
6586 transport_controller_->GetMediaTransportState(
6587 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6588 return;
6589 }
6590 media_transport_invoker_->AsyncInvoke<void>(
6591 RTC_FROM_HERE, signaling_thread(), [this] {
6592 RTC_DCHECK_RUN_ON(signaling_thread());
6593 media_transport_ready_to_send_data_ = true;
6594 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6595 });
6596}
6597
Steve Anton75737c02017-11-06 10:37:17 -08006598// Returns false if bundle is enabled and rtcp_mux is disabled.
6599bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6600 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6601 if (!bundle_enabled)
6602 return true;
6603
6604 const cricket::ContentGroup* bundle_group =
6605 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6606 RTC_DCHECK(bundle_group != NULL);
6607
6608 const cricket::ContentInfos& contents = desc->contents();
6609 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6610 citer != contents.end(); ++citer) {
6611 const cricket::ContentInfo* content = (&*citer);
6612 RTC_DCHECK(content != NULL);
6613 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006614 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006615 if (!HasRtcpMuxEnabled(content))
6616 return false;
6617 }
6618 }
6619 // RTCP-MUX is enabled in all the contents.
6620 return true;
6621}
6622
6623bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006624 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006625}
6626
Steve Anton06817cd2018-12-18 15:55:30 -08006627static RTCError ValidateMids(const cricket::SessionDescription& description) {
6628 std::set<std::string> mids;
6629 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006630 if (content.name.empty()) {
6631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6632 "A media section is missing a MID attribute.");
6633 }
Steve Anton06817cd2018-12-18 15:55:30 -08006634 if (!mids.insert(content.name).second) {
6635 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6636 "Duplicate a=mid value '" + content.name + "'.");
6637 }
6638 }
6639 return RTCError::OK();
6640}
6641
Steve Anton8a006912017-12-04 15:25:56 -08006642RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006643 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006644 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006645 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006646 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006647 }
6648
6649 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652
Steve Anton3828c062017-12-06 10:34:51 -08006653 SdpType type = sdesc->GetType();
6654 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6655 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006656 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006657 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006658 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006659 }
6660
Steve Anton06817cd2018-12-18 15:55:30 -08006661 RTCError error = ValidateMids(*sdesc->description());
6662 if (!error.ok()) {
6663 return error;
6664 }
6665
Steve Anton75737c02017-11-06 10:37:17 -08006666 // Verify crypto settings.
6667 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006668 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6669 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006670 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006671 if (!crypto_error.ok()) {
6672 return crypto_error;
6673 }
Steve Anton75737c02017-11-06 10:37:17 -08006674 }
6675
6676 // Verify ice-ufrag and ice-pwd.
6677 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006678 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6679 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006680 }
6681
6682 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006683 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6684 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006685 }
6686
6687 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6688 // m-lines that do not rtcp-mux enabled.
6689
6690 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006691 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006692 // With an answer we want to compare the new answer session description with
6693 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006694 const cricket::SessionDescription* offer_desc =
6695 (source == cricket::CS_LOCAL) ? remote_description()->description()
6696 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006697 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6698 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6699 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6701 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006702 }
6703 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006704 // The re-offers should respect the order of m= sections in current
6705 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006706 // With a re-offer, either the current local or current remote descriptions
6707 // could be the most up to date, so we would like to check against both of
6708 // them if they exist. It could be the case that one of them has a 0 port
6709 // for a media section, but the other does not. This is important to check
6710 // against in the case that we are recycling an m= section.
6711 const cricket::SessionDescription* current_desc = nullptr;
6712 const cricket::SessionDescription* secondary_current_desc = nullptr;
6713 if (local_description()) {
6714 current_desc = local_description()->description();
6715 if (remote_description()) {
6716 secondary_current_desc = remote_description()->description();
6717 }
6718 } else if (remote_description()) {
6719 current_desc = remote_description()->description();
6720 }
Steve Anton75737c02017-11-06 10:37:17 -08006721 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006722 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6723 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006724 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6725 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006726 }
6727 }
6728
Steve Antonba42e992018-04-09 14:10:01 -07006729 if (IsUnifiedPlan()) {
6730 // Ensure that each audio and video media section has at most one
6731 // "StreamParams". This will return an error if receiving a session
6732 // description from a "Plan B" endpoint which adds multiple tracks of the
6733 // same type. With Unified Plan, there can only be at most one track per
6734 // media section.
6735 for (const ContentInfo& content : sdesc->description()->contents()) {
6736 const MediaContentDescription& desc = *content.description;
6737 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6738 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6739 desc.streams().size() > 1u) {
6740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6741 "Media section has more than one track specified "
6742 "with a=ssrc lines which is not supported with "
6743 "Unified Plan.");
6744 }
6745 }
6746 }
6747
Steve Anton8a006912017-12-04 15:25:56 -08006748 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006749}
6750
Steve Anton3828c062017-12-06 10:34:51 -08006751bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006752 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006753 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006754 return (state == PeerConnectionInterface::kStable) ||
6755 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006756 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006757 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006758 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6759 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6760 }
6761}
6762
Steve Anton3828c062017-12-06 10:34:51 -08006763bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006764 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006765 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006766 return (state == PeerConnectionInterface::kStable) ||
6767 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006768 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006769 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006770 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6771 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6772 }
6773}
6774
Steve Antonf8470812017-12-04 10:46:21 -08006775const char* PeerConnection::SessionErrorToString(SessionError error) const {
6776 switch (error) {
6777 case SessionError::kNone:
6778 return "ERROR_NONE";
6779 case SessionError::kContent:
6780 return "ERROR_CONTENT";
6781 case SessionError::kTransport:
6782 return "ERROR_TRANSPORT";
6783 }
6784 RTC_NOTREACHED();
6785 return "";
6786}
6787
Steve Anton75737c02017-11-06 10:37:17 -08006788std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006789 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006790 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6791 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006792 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006793}
6794
Steve Anton8e20f172018-03-06 10:55:04 -08006795void PeerConnection::ReportSdpFormatReceived(
6796 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006797 int num_audio_mlines = 0;
6798 int num_video_mlines = 0;
6799 int num_audio_tracks = 0;
6800 int num_video_tracks = 0;
6801 for (const ContentInfo& content : remote_offer.description()->contents()) {
6802 cricket::MediaType media_type = content.media_description()->type();
6803 int num_tracks = std::max(
6804 1, static_cast<int>(content.media_description()->streams().size()));
6805 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6806 num_audio_mlines += 1;
6807 num_audio_tracks += num_tracks;
6808 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6809 num_video_mlines += 1;
6810 num_video_tracks += num_tracks;
6811 }
6812 }
6813 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6814 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6815 format = kSdpFormatReceivedComplexUnifiedPlan;
6816 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6817 format = kSdpFormatReceivedComplexPlanB;
6818 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6819 format = kSdpFormatReceivedSimple;
6820 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006821 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6822 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006823}
6824
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006825void PeerConnection::NoteUsageEvent(UsageEvent event) {
6826 RTC_DCHECK_RUN_ON(signaling_thread());
6827 usage_event_accumulator_ |= static_cast<int>(event);
6828}
6829
6830void PeerConnection::ReportUsagePattern() const {
6831 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006832 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6833 usage_event_accumulator_,
6834 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006835 const int bad_bits =
6836 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6837 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6838 const int good_bits =
6839 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6840 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6841 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6842 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6843 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006844 // If called after close(), we can't report, because observer may have
6845 // been deallocated, and therefore pointer is null. Write to log instead.
6846 if (observer_) {
6847 Observer()->OnInterestingUsage(usage_event_accumulator_);
6848 } else {
6849 RTC_LOG(LS_INFO) << "Interesting usage signature "
6850 << usage_event_accumulator_
6851 << " observed after observer shutdown";
6852 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006853 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006854}
6855
Steve Anton0ffaaa22018-02-23 10:31:30 -08006856void PeerConnection::ReportNegotiatedSdpSemantics(
6857 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006858 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006859 switch (answer.description()->msid_signaling()) {
6860 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006861 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006862 break;
6863 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006864 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006865 break;
6866 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006867 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006868 break;
6869 case cricket::kMsidSignalingMediaSection |
6870 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006871 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006872 break;
6873 default:
6874 RTC_NOTREACHED();
6875 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006876 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6877 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006878}
6879
Steve Anton75737c02017-11-06 10:37:17 -08006880// We need to check the local/remote description for the Transport instead of
6881// the session, because a new Transport added during renegotiation may have
6882// them unset while the session has them set from the previous negotiation.
6883// Not doing so may trigger the auto generation of transport description and
6884// mess up DTLS identity information, ICE credential, etc.
6885bool PeerConnection::ReadyToUseRemoteCandidate(
6886 const IceCandidateInterface* candidate,
6887 const SessionDescriptionInterface* remote_desc,
6888 bool* valid) {
6889 *valid = true;
6890
6891 const SessionDescriptionInterface* current_remote_desc =
6892 remote_desc ? remote_desc : remote_description();
6893
6894 if (!current_remote_desc) {
6895 return false;
6896 }
6897
Guido Urdaneta41633172019-05-23 20:12:29 +02006898 RTCErrorOr<const cricket::ContentInfo*> result =
6899 FindContentInfo(current_remote_desc, candidate);
6900 if (!result.ok()) {
6901 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6902 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006903
6904 *valid = false;
6905 return false;
6906 }
6907
Guido Urdaneta41633172019-05-23 20:12:29 +02006908 std::string transport_name = GetTransportName(result.value()->name);
6909 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006910}
6911
6912bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006913 return !configuration_.use_datagram_transport &&
6914 (dtls_enabled_ ||
6915 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006916}
6917
6918void PeerConnection::OnTransportControllerGatheringState(
6919 cricket::IceGatheringState state) {
6920 RTC_DCHECK(signaling_thread()->IsCurrent());
6921 if (state == cricket::kIceGatheringGathering) {
6922 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6923 } else if (state == cricket::kIceGatheringComplete) {
6924 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6925 }
6926}
6927
6928void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006929 std::map<std::string, std::set<cricket::MediaType>>
6930 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006931 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006932 if (transceiver->internal()->channel()) {
6933 const std::string& transport_name =
6934 transceiver->internal()->channel()->transport_name();
6935 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006936 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006937 }
Steve Anton75737c02017-11-06 10:37:17 -08006938 }
6939 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006940 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6941 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006942 }
Zhi Huange830e682018-03-30 10:48:35 -07006943
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006944 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006945 if (transport_name) {
6946 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006947 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006948 }
Zhi Huange830e682018-03-30 10:48:35 -07006949
Steve Antonc7b964c2018-02-01 14:39:45 -08006950 for (const auto& entry : media_types_by_transport_name) {
6951 const std::string& transport_name = entry.first;
6952 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006953 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006954 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006955 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006956 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006957 }
6958 }
6959}
6960// Walk through the ConnectionInfos to gather best connection usage
6961// for IPv4 and IPv6.
6962void PeerConnection::ReportBestConnectionState(
6963 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006964 for (const cricket::TransportChannelStats& channel_stats :
6965 stats.channel_stats) {
6966 for (const cricket::ConnectionInfo& connection_info :
6967 channel_stats.connection_infos) {
6968 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006969 continue;
6970 }
6971
Steve Antonc7b964c2018-02-01 14:39:45 -08006972 const cricket::Candidate& local = connection_info.local_candidate;
6973 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006974
6975 // Increment the counter for IceCandidatePairType.
6976 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6977 (local.type() == RELAY_PORT_TYPE &&
6978 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006979 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6980 GetIceCandidatePairCounter(local, remote),
6981 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006982 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006983 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6984 GetIceCandidatePairCounter(local, remote),
6985 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006986 } else {
6987 RTC_CHECK(0);
6988 }
Steve Anton75737c02017-11-06 10:37:17 -08006989
6990 // Increment the counter for IP type.
6991 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006992 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6993 kBestConnections_IPv4,
6994 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006995 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006996 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6997 kBestConnections_IPv6,
6998 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006999 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007000 RTC_CHECK(!local.address().hostname().empty() &&
7001 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007002 }
7003
7004 return;
7005 }
7006 }
7007}
7008
7009void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007010 const cricket::TransportStats& stats,
7011 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007012 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7013 return;
7014 }
7015
7016 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7017 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7018 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7019 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7020 return;
7021 }
7022
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007023 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7024 for (cricket::MediaType media_type : media_types) {
7025 switch (media_type) {
7026 case cricket::MEDIA_TYPE_AUDIO:
7027 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7028 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7029 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7030 break;
7031 case cricket::MEDIA_TYPE_VIDEO:
7032 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7033 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7034 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7035 break;
7036 case cricket::MEDIA_TYPE_DATA:
7037 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7038 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7039 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7040 break;
7041 default:
7042 RTC_NOTREACHED();
7043 continue;
7044 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007045 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007046 }
7047
7048 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7049 for (cricket::MediaType media_type : media_types) {
7050 switch (media_type) {
7051 case cricket::MEDIA_TYPE_AUDIO:
7052 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7053 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7054 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7055 break;
7056 case cricket::MEDIA_TYPE_VIDEO:
7057 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7058 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7059 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7060 break;
7061 case cricket::MEDIA_TYPE_DATA:
7062 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7063 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7064 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7065 break;
7066 default:
7067 RTC_NOTREACHED();
7068 continue;
7069 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007070 }
Steve Anton75737c02017-11-06 10:37:17 -08007071 }
7072}
7073
7074void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007075 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007076 RTC_DCHECK(call_);
7077 call_->OnSentPacket(sent_packet);
7078}
7079
7080const std::string PeerConnection::GetTransportName(
7081 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007082 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007083 if (channel) {
7084 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007085 }
Steve Anton6fec8802017-12-04 10:37:29 -08007086 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007087 RTC_DCHECK(sctp_mid_);
7088 if (content_name == *sctp_mid_) {
7089 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007090 }
7091 }
7092 // Return an empty string if failed to retrieve the transport name.
7093 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007094}
7095
Steve Anton6fec8802017-12-04 10:37:29 -08007096void PeerConnection::DestroyTransceiverChannel(
7097 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7098 transceiver) {
7099 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007100
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007101 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007102 if (channel) {
7103 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007104 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007105 }
7106}
7107
7108void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007109 if (rtp_data_channel_) {
7110 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007111 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007112 rtp_data_channel_ = nullptr;
7113 }
7114
7115 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7116 // grab a reference to this PeerConnection. If this is called from the
7117 // PeerConnection destructor, the RefCountedObject vtable will have already
7118 // been destroyed (since it is a subclass of PeerConnection) and using
7119 // rtc::Bind will cause "Pure virtual function called" error to appear.
7120
7121 if (sctp_transport_) {
7122 OnDataChannelDestroyed();
7123 network_thread()->Invoke<void>(RTC_FROM_HERE,
7124 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007125 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007126 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007127
7128 if (media_transport_) {
7129 OnDataChannelDestroyed();
7130 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7131 RTC_DCHECK_RUN_ON(network_thread());
7132 TeardownMediaTransportForDataChannels_n();
7133 });
7134 }
Steve Anton6fec8802017-12-04 10:37:29 -08007135}
7136
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007137void PeerConnection::DestroyChannelInterface(
7138 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007139 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007140 switch (channel->media_type()) {
7141 case cricket::MEDIA_TYPE_AUDIO:
7142 channel_manager()->DestroyVoiceChannel(
7143 static_cast<cricket::VoiceChannel*>(channel));
7144 break;
7145 case cricket::MEDIA_TYPE_VIDEO:
7146 channel_manager()->DestroyVideoChannel(
7147 static_cast<cricket::VideoChannel*>(channel));
7148 break;
7149 case cricket::MEDIA_TYPE_DATA:
7150 channel_manager()->DestroyRtpDataChannel(
7151 static_cast<cricket::RtpDataChannel*>(channel));
7152 break;
7153 default:
7154 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7155 break;
7156 }
Zhi Huange830e682018-03-30 10:48:35 -07007157}
Steve Anton6fec8802017-12-04 10:37:29 -08007158
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007159bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007160 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007161 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007162 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007163 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007164 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007165 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007166 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007167 auto base_channel = GetChannel(mid);
7168 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007169 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007170 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007171 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007172 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007173 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007174
Karl Wiberg5966c502019-02-21 23:55:09 +01007175 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007176 // Only pass media transport to call object if media transport is used
7177 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007178 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007179 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007180
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007181 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007182}
7183
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007184void PeerConnection::OnSetStreams() {
7185 RTC_DCHECK_RUN_ON(signaling_thread());
7186 if (IsUnifiedPlan())
7187 UpdateNegotiationNeeded();
7188}
7189
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007190PeerConnectionObserver* PeerConnection::Observer() const {
7191 // In earlier production code, the pointer was not cleared on close,
7192 // which might have led to undefined behavior if the observer was not
7193 // deallocated, or strange crashes if it was.
7194 // We use CHECK in order to catch such behavior if it exists.
7195 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7196 RTC_CHECK(observer_);
7197 return observer_;
7198}
7199
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007200CryptoOptions PeerConnection::GetCryptoOptions() {
7201 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7202 // after it has been removed.
7203 return configuration_.crypto_options.has_value()
7204 ? *configuration_.crypto_options
7205 : factory_->options().crypto_options;
7206}
7207
Harald Alvestrand89061872018-01-02 14:08:34 +01007208void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007209 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007210 if (stats_collector_) {
7211 stats_collector_->ClearCachedStatsReport();
7212 }
7213}
7214
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007215void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007216 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7217 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007218}
7219
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007220void PeerConnection::UpdateNegotiationNeeded() {
7221 RTC_DCHECK_RUN_ON(signaling_thread());
7222 if (!IsUnifiedPlan()) {
7223 Observer()->OnRenegotiationNeeded();
7224 return;
7225 }
7226
7227 // If connection's [[IsClosed]] slot is true, abort these steps.
7228 if (IsClosed())
7229 return;
7230
7231 // If connection's signaling state is not "stable", abort these steps.
7232 if (signaling_state() != kStable)
7233 return;
7234
7235 // NOTE
7236 // The negotiation-needed flag will be updated once the state transitions to
7237 // "stable", as part of the steps for setting an RTCSessionDescription.
7238
7239 // If the result of checking if negotiation is needed is false, clear the
7240 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7241 // to false, and abort these steps.
7242 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7243 if (!is_negotiation_needed) {
7244 is_negotiation_needed_ = false;
7245 return;
7246 }
7247
7248 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7249 // steps.
7250 if (is_negotiation_needed_)
7251 return;
7252
7253 // Set connection's [[NegotiationNeeded]] slot to true.
7254 is_negotiation_needed_ = true;
7255
7256 // Queue a task that runs the following steps:
7257 // If connection's [[IsClosed]] slot is true, abort these steps.
7258 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7259 // Fire an event named negotiationneeded at connection.
7260 Observer()->OnRenegotiationNeeded();
7261}
7262
7263bool PeerConnection::CheckIfNegotiationIsNeeded() {
7264 RTC_DCHECK_RUN_ON(signaling_thread());
7265 // 1. If any implementation-specific negotiation is required, as described at
7266 // the start of this section, return true.
7267
7268 // 2. Let description be connection.[[CurrentLocalDescription]].
7269 const SessionDescriptionInterface* description = current_local_description();
7270 if (!description)
7271 return true;
7272
7273 // 3. If connection has created any RTCDataChannels, and no m= section in
7274 // description has been negotiated yet for data, return true.
7275 if (!sctp_data_channels_.empty()) {
7276 if (!cricket::GetFirstDataContent(description->description()->contents()))
7277 return true;
7278 }
7279
7280 // 4. For each transceiver in connection's set of transceivers, perform the
7281 // following checks:
7282 for (const auto& transceiver : transceivers_) {
7283 const ContentInfo* current_local_msection =
7284 FindTransceiverMSection(transceiver.get(), description);
7285
7286 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7287 transceiver.get(), current_remote_description());
7288
7289 // 4.3 If transceiver is stopped and is associated with an m= section,
7290 // but the associated m= section is not yet rejected in
7291 // connection.[[CurrentLocalDescription]] or
7292 // connection.[[CurrentRemoteDescription]], return true.
7293 if (transceiver->stopped()) {
7294 if (current_local_msection && !current_local_msection->rejected &&
7295 ((current_remote_msection && !current_remote_msection->rejected) ||
7296 !current_remote_msection)) {
7297 return true;
7298 }
7299 continue;
7300 }
7301
7302 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7303 // section in description, return true.
7304 if (!current_local_msection)
7305 return true;
7306
7307 const MediaContentDescription* current_local_media_description =
7308 current_local_msection->media_description();
7309 // 4.2 If transceiver isn't stopped and is associated with an m= section
7310 // in description then perform the following checks:
7311
7312 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7313 // associated m= section in description either doesn't contain a single
7314 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7315 // m= section, or the MSID values themselves, differ from what is in
7316 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7317 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7318 if (current_local_media_description->streams().size() == 0)
7319 return true;
7320
7321 std::vector<std::string> msection_msids;
7322 for (const auto& stream : current_local_media_description->streams()) {
7323 for (const std::string& msid : stream.stream_ids())
7324 msection_msids.push_back(msid);
7325 }
7326
7327 std::vector<std::string> transceiver_msids =
7328 transceiver->sender()->stream_ids();
7329 if (msection_msids.size() != transceiver_msids.size())
7330 return true;
7331
7332 absl::c_sort(transceiver_msids);
7333 absl::c_sort(msection_msids);
7334 if (transceiver_msids != msection_msids)
7335 return true;
7336 }
7337
7338 // 4.2.2 If description is of type "offer", and the direction of the
7339 // associated m= section in neither connection.[[CurrentLocalDescription]]
7340 // nor connection.[[CurrentRemoteDescription]] matches
7341 // transceiver.[[Direction]], return true.
7342 if (description->GetType() == SdpType::kOffer) {
7343 if (!current_remote_description())
7344 return true;
7345
7346 if (!current_remote_msection)
7347 return true;
7348
7349 RtpTransceiverDirection current_local_direction =
7350 current_local_media_description->direction();
7351 RtpTransceiverDirection current_remote_direction =
7352 current_remote_msection->media_description()->direction();
7353 if (transceiver->direction() != current_local_direction &&
7354 transceiver->direction() !=
7355 RtpTransceiverDirectionReversed(current_remote_direction)) {
7356 return true;
7357 }
7358 }
7359
7360 // 4.2.3 If description is of type "answer", and the direction of the
7361 // associated m= section in the description does not match
7362 // transceiver.[[Direction]] intersected with the offered direction (as
7363 // described in [JSEP] (section 5.3.1.)), return true.
7364 if (description->GetType() == SdpType::kAnswer) {
7365 if (!remote_description())
7366 return true;
7367
7368 const ContentInfo* offered_remote_msection =
7369 FindTransceiverMSection(transceiver.get(), remote_description());
7370
7371 RtpTransceiverDirection offered_direction =
7372 offered_remote_msection
7373 ? offered_remote_msection->media_description()->direction()
7374 : RtpTransceiverDirection::kInactive;
7375
7376 if (current_local_media_description->direction() !=
7377 (RtpTransceiverDirectionIntersection(
7378 transceiver->direction(),
7379 RtpTransceiverDirectionReversed(offered_direction)))) {
7380 return true;
7381 }
7382 }
7383 }
7384
7385 // If all the preceding checks were performed and true was not returned,
7386 // nothing remains to be negotiated; return false.
7387 return false;
7388}
7389
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007390} // namespace webrtc