blob: 781b3a551a872f6e3d23b90156660e9ee56db69d [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// Get the SCTP port out of a SessionDescription.
560// Return -1 if not found.
561int GetSctpPort(const SessionDescription* session_description) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +0200562 const cricket::SctpDataContentDescription* data_desc =
563 GetFirstSctpDataContentDescription(session_description);
Steve Antonb1c1de12017-12-21 15:14:30 -0800564 RTC_DCHECK(data_desc);
565 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800566 return -1;
567 }
Harald Alvestrand5fc28b12019-05-13 13:36:16 +0200568 return data_desc->port();
Steve Anton75737c02017-11-06 10:37:17 -0800569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800663void ReportSimulcastApiVersion(const char* name,
664 const SessionDescription& session) {
665 bool has_legacy = false;
666 bool has_spec_compliant = false;
667 for (const ContentInfo& content : session.contents()) {
668 if (!content.description) {
669 continue;
670 }
671 has_spec_compliant |= content.description->HasSimulcast();
672 for (const StreamParams& sp : content.description->streams()) {
673 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
674 }
675 }
676
677 if (has_legacy) {
678 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
679 kSimulcastApiVersionMax);
680 }
681 if (has_spec_compliant) {
682 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
683 kSimulcastApiVersionMax);
684 }
685 if (!has_legacy && !has_spec_compliant) {
686 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
687 kSimulcastApiVersionMax);
688 }
689}
690
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200691const ContentInfo* FindTransceiverMSection(
692 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
693 const SessionDescriptionInterface* session_description) {
694 return transceiver->mid()
695 ? session_description->description()->GetContentByName(
696 *transceiver->mid())
697 : nullptr;
698}
699
Steve Anton75737c02017-11-06 10:37:17 -0800700} // namespace
701
Henrik Boström31638672017-11-23 17:48:32 +0100702// Upon completion, posts a task to execute the callback of the
703// SetSessionDescriptionObserver asynchronously on the same thread. At this
704// point, the state of the peer connection might no longer reflect the effects
705// of the SetRemoteDescription operation, as the peer connection could have been
706// modified during the post.
707// TODO(hbos): Remove this class once we remove the version of
708// PeerConnectionInterface::SetRemoteDescription() that takes a
709// SetSessionDescriptionObserver as an argument.
710class PeerConnection::SetRemoteDescriptionObserverAdapter
711 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
712 public:
713 SetRemoteDescriptionObserverAdapter(
714 rtc::scoped_refptr<PeerConnection> pc,
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
716 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
717
718 // SetRemoteDescriptionObserverInterface implementation.
719 void OnSetRemoteDescriptionComplete(RTCError error) override {
720 if (error.ok())
721 pc_->PostSetSessionDescriptionSuccess(wrapper_);
722 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100723 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100724 }
725
726 private:
727 rtc::scoped_refptr<PeerConnection> pc_;
728 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
729};
730
deadbeef293e9262017-01-11 12:28:30 -0800731bool PeerConnectionInterface::RTCConfiguration::operator==(
732 const PeerConnectionInterface::RTCConfiguration& o) const {
733 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800735 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000736 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700737 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800738 BundlePolicy bundle_policy;
739 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700740 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
741 int ice_candidate_pool_size;
742 bool disable_ipv6;
743 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700744 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100745 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700746 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200747 absl::optional<int> screencast_min_bitrate;
748 absl::optional<bool> combined_audio_video_bwe;
749 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800750 TcpCandidatePolicy tcp_candidate_policy;
751 CandidateNetworkPolicy candidate_network_policy;
752 int audio_jitter_buffer_max_packets;
753 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100754 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100755 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800756 int ice_connection_receiving_timeout;
757 int ice_backup_candidate_pair_ping_interval;
758 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800759 bool prioritize_most_likely_ice_candidate_pairs;
760 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800761 bool prune_turn_ports;
762 bool presume_writable_when_fully_relayed;
763 bool enable_ice_renomination;
764 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200765 absl::optional<int> ice_check_interval_strong_connectivity;
766 absl::optional<int> ice_check_interval_weak_connectivity;
767 absl::optional<int> ice_check_min_interval;
768 absl::optional<int> ice_unwritable_timeout;
769 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800770 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200771 absl::optional<int> stun_candidate_keepalive_interval;
772 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200773 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800774 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700776 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700777 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700778 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700779 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100780 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800781 };
782 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
783 "Did you add something to RTCConfiguration and forget to "
784 "update operator==?");
785 return type == o.type && servers == o.servers &&
786 bundle_policy == o.bundle_policy &&
787 rtcp_mux_policy == o.rtcp_mux_policy &&
788 tcp_candidate_policy == o.tcp_candidate_policy &&
789 candidate_network_policy == o.candidate_network_policy &&
790 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
791 audio_jitter_buffer_fast_accelerate ==
792 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100793 audio_jitter_buffer_min_delay_ms ==
794 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100795 audio_jitter_buffer_enable_rtx_handling ==
796 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800797 ice_connection_receiving_timeout ==
798 o.ice_connection_receiving_timeout &&
799 ice_backup_candidate_pair_ping_interval ==
800 o.ice_backup_candidate_pair_ping_interval &&
801 continual_gathering_policy == o.continual_gathering_policy &&
802 certificates == o.certificates &&
803 prioritize_most_likely_ice_candidate_pairs ==
804 o.prioritize_most_likely_ice_candidate_pairs &&
805 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800806 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700807 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100808 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800809 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800810 screencast_min_bitrate == o.screencast_min_bitrate &&
811 combined_audio_video_bwe == o.combined_audio_video_bwe &&
812 enable_dtls_srtp == o.enable_dtls_srtp &&
813 ice_candidate_pool_size == o.ice_candidate_pool_size &&
814 prune_turn_ports == o.prune_turn_ports &&
815 presume_writable_when_fully_relayed ==
816 o.presume_writable_when_fully_relayed &&
817 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800818 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800819 ice_check_interval_strong_connectivity ==
820 o.ice_check_interval_strong_connectivity &&
821 ice_check_interval_weak_connectivity ==
822 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700823 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700824 ice_unwritable_timeout == o.ice_unwritable_timeout &&
825 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800826 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800827 stun_candidate_keepalive_interval ==
828 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200829 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800830 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800831 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700832 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700833 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700834 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700835 use_media_transport_for_data_channels ==
836 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100837 crypto_options == o.crypto_options &&
838 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800839}
840
841bool PeerConnectionInterface::RTCConfiguration::operator!=(
842 const PeerConnectionInterface::RTCConfiguration& o) const {
843 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800844}
845
zhihuang8f65cdf2016-05-06 18:40:30 -0700846// Generate a RTCP CNAME when a PeerConnection is created.
847std::string GenerateRtcpCname() {
848 std::string cname;
849 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800851 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700852 }
853 return cname;
854}
855
zhihuang1c378ed2017-08-17 14:10:50 -0700856bool ValidateOfferAnswerOptions(
857 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
858 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
859 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700860}
861
zhihuang1c378ed2017-08-17 14:10:50 -0700862// From |rtc_options|, fill parts of |session_options| shared by all generated
863// m= sections (in other words, nothing that involves a map/array).
864void ExtractSharedMediaSessionOptions(
865 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
866 cricket::MediaSessionOptions* session_options) {
867 session_options->vad_enabled = rtc_options.voice_activity_detection;
868 session_options->bundle_enabled = rtc_options.use_rtp_mux;
869}
zhihuanga77e6bb2017-08-14 18:17:48 -0700870
zhihuang38ede132017-06-15 12:52:32 -0700871PeerConnection::PeerConnection(PeerConnectionFactory* factory,
872 std::unique_ptr<RtcEventLog> event_log,
873 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700875 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100876 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700877 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700878 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700879 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100880 call_(std::move(call)),
881 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882
883PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800885 RTC_DCHECK_RUN_ON(signaling_thread());
886
Steve Anton8af21862017-12-15 11:20:13 -0800887 // Need to stop transceivers before destroying the stats collector because
888 // AudioRtpSender has a reference to the StatsCollector it will update when
889 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100890 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800891 transceiver->Stop();
892 }
Steve Anton4171afb2017-11-20 10:20:22 -0800893
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800895 if (stats_collector_) {
896 stats_collector_->WaitForPendingRequest();
897 stats_collector_ = nullptr;
898 }
Steve Anton75737c02017-11-06 10:37:17 -0800899
Steve Anton8af21862017-12-15 11:20:13 -0800900 // Don't destroy BaseChannels until after stats has been cleaned up so that
901 // the last stats request can still read from the channels.
902 DestroyAllChannels();
903
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800905
906 webrtc_session_desc_factory_.reset();
907 sctp_invoker_.reset();
908 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800909 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800910 transport_controller_.reset();
911
deadbeef91dd5672016-05-18 16:55:30 -0700912 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100913 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
914 RTC_DCHECK_RUN_ON(network_thread());
915 port_allocator_.reset();
916 });
eladalon248fd4f2017-09-06 05:18:15 -0700917 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700918 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100919 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700920 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800921 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700922 event_log_.reset();
923 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924}
925
Steve Anton8af21862017-12-15 11:20:13 -0800926void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800927 // Destroy video channels first since they may have a pointer to a voice
928 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100929 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800930 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800931 DestroyTransceiverChannel(transceiver);
932 }
933 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100934 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800935 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800936 DestroyTransceiverChannel(transceiver);
937 }
938 }
939 DestroyDataChannel();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000943 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700944 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100945 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100946 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100947 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700948
949 RTCError config_error = ValidateConfiguration(configuration);
950 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700952 return false;
953 }
954
Benjamin Wrightcab58882018-05-02 15:12:47 -0700955 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_ERROR)
957 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100958 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800959 return false;
960 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200961
Benjamin Wrightcab58882018-05-02 15:12:47 -0700962 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800963 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100964 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100965 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800966 return false;
967 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700968
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700970 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700971 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700972 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800973
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200974 cricket::ServerAddresses stun_servers;
975 std::vector<cricket::RelayServerConfig> turn_servers;
976
977 RTCErrorType parse_error =
978 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
979 if (parse_error != RTCErrorType::NONE) {
980 return false;
981 }
982
deadbeef91dd5672016-05-18 16:55:30 -0700983 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700984 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100985 const auto pa_result =
986 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200987 RTC_FROM_HERE,
988 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100989 stun_servers, turn_servers, configuration));
990
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200991 // If initialization was successful, note if STUN or TURN servers
992 // were supplied.
993 if (!stun_servers.empty()) {
994 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
995 }
996 if (!turn_servers.empty()) {
997 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001000 // Send information about IPv4/IPv6 status.
1001 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001002 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001003 address_family = kPeerConnection_IPv6;
1004 } else {
1005 address_family = kPeerConnection_IPv4;
1006 }
1007 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1008 kPeerConnectionAddressFamilyCounter_Max);
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1011
Steve Anton75737c02017-11-06 10:37:17 -08001012 // RFC 3264: The numeric value of the session id and version in the
1013 // o line MUST be representable with a "64 bit signed integer".
1014 // Due to this constraint session id |session_id_| is max limited to
1015 // LLONG_MAX.
1016 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001017 JsepTransportController::Config config;
1018 config.redetermine_role_on_ice_restart =
1019 configuration.redetermine_role_on_ice_restart;
1020 config.ssl_max_version = factory_->options().ssl_max_version;
1021 config.disable_encryption = options.disable_encryption;
1022 config.bundle_policy = configuration.bundle_policy;
1023 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001024 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1025 // stub.
1026 config.crypto_options = configuration.crypto_options.has_value()
1027 ? *configuration.crypto_options
1028 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001029 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001030 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001031#if defined(ENABLE_EXTERNAL_AUTH)
1032 config.enable_external_auth = true;
1033#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001034 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001035
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001036 if (configuration.use_media_transport ||
1037 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001038 if (!factory_->media_transport_factory()) {
1039 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001040 << "PeerConnecton is initialized with use_media_transport = true or "
1041 << "use_media_transport_for_data_channels = true "
1042 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001043 return false;
1044 }
1045
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001046 if (configuration.use_media_transport ||
1047 configuration.use_media_transport_for_data_channels) {
1048 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1049 // RTP media transport is introduced. But until then, we require SDES to
1050 // be enabled.
1051 if (configuration.enable_dtls_srtp.has_value() &&
1052 configuration.enable_dtls_srtp.value()) {
1053 RTC_LOG(LS_WARNING)
1054 << "When media transport is used, SDES must be enabled. Set "
1055 "configuration.enable_dtls_srtp to false. use_media_transport="
1056 << configuration.use_media_transport
1057 << ", use_media_transport_for_data_channels="
1058 << configuration.use_media_transport_for_data_channels;
1059 return false;
1060 }
1061 }
1062
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001063 config.use_media_transport_for_media = configuration.use_media_transport;
1064 config.use_media_transport_for_data_channels =
1065 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001066 config.media_transport_factory = factory_->media_transport_factory();
1067 }
1068
Zhi Huange830e682018-03-30 10:48:35 -07001069 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001070 signaling_thread(), network_thread(), port_allocator_.get(),
1071 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001072 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001073 this, &PeerConnection::OnTransportControllerConnectionState);
1074 transport_controller_->SignalStandardizedIceConnectionState.connect(
1075 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001076 transport_controller_->SignalConnectionState.connect(
1077 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001078 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001079 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001081 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001082 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001083 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1084 transport_controller_->SignalDtlsHandshakeError.connect(
1085 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1086
1087 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001088
deadbeefab9b2d12015-10-14 11:33:11 -07001089 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001090 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091
Steve Antonba818672017-11-06 10:21:57 -08001092 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001093 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001094
Steve Anton75737c02017-11-06 10:37:17 -08001095 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1096 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1097 if (!configuration.certificates.empty()) {
1098 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1099 // just picking the first one. The decision should be made based on the DTLS
1100 // handshake. The DTLS negotiations need to know about all certificates.
1101 certificate = configuration.certificates[0];
1102 }
1103
Steve Antond25da372017-11-06 14:50:29 -08001104 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001105
1106 if (options.disable_encryption) {
1107 dtls_enabled_ = false;
1108 } else {
1109 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001110 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001111 // |configuration| can override the default |dtls_enabled_| value.
1112 if (configuration.enable_dtls_srtp) {
1113 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1114 }
1115 }
1116
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001117 if (configuration.use_media_transport_for_data_channels) {
1118 if (configuration.enable_rtp_data_channel) {
1119 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1120 "use_media_transport_for_data_channels are "
1121 "incompatible and cannot both be set to true";
1122 return false;
1123 }
1124 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1125 } else if (configuration.enable_rtp_data_channel) {
1126 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1127 // set. It takes precendence over the disable_sctp_data_channels
1128 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001129 data_channel_type_ = cricket::DCT_RTP;
1130 } else {
1131 // DTLS has to be enabled to use SCTP.
1132 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1133 data_channel_type_ = cricket::DCT_SCTP;
1134 }
1135 }
1136
1137 video_options_.screencast_min_bitrate_kbps =
1138 configuration.screencast_min_bitrate;
1139 audio_options_.combined_audio_video_bwe =
1140 configuration.combined_audio_video_bwe;
1141
1142 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001143 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001144
1145 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001146 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001147
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001148 audio_options_.audio_jitter_buffer_min_delay_ms =
1149 configuration.audio_jitter_buffer_min_delay_ms;
1150
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001151 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1152 configuration.audio_jitter_buffer_enable_rtx_handling;
1153
Steve Anton75737c02017-11-06 10:37:17 -08001154 // Whether the certificate generator/certificate is null or not determines
1155 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1156 // the right instructions by clearing the variables if needed.
1157 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001158 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001159 certificate = nullptr;
1160 } else if (certificate) {
1161 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001162 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001163 }
1164
1165 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1166 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001167 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001168 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1169 this, &PeerConnection::OnCertificateReady);
1170
1171 if (options.disable_encryption) {
1172 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1173 }
1174
1175 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001176 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001177 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178
Steve Anton4171afb2017-11-20 10:20:22 -08001179 // Add default audio/video transceivers for Plan B SDP.
1180 if (!IsUnifiedPlan()) {
1181 transceivers_.push_back(
1182 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1183 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1184 transceivers_.push_back(
1185 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1186 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1187 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001188 int delay_ms =
1189 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001190 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1191 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001192
1193 if (dependencies.video_bitrate_allocator_factory) {
1194 video_bitrate_allocator_factory_ =
1195 std::move(dependencies.video_bitrate_allocator_factory);
1196 } else {
1197 video_bitrate_allocator_factory_ =
1198 CreateBuiltinVideoBitrateAllocatorFactory();
1199 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 return true;
1201}
1202
Steve Anton038834f2017-07-14 15:59:59 -07001203RTCError PeerConnection::ValidateConfiguration(
1204 const RTCConfiguration& config) const {
1205 if (config.ice_regather_interval_range &&
1206 config.continual_gathering_policy == GATHER_ONCE) {
1207 return RTCError(RTCErrorType::INVALID_PARAMETER,
1208 "ice_regather_interval_range specified but continual "
1209 "gathering policy is GATHER_ONCE");
1210 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001211 auto result =
1212 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1213 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001214}
1215
Yves Gerey665174f2018-06-19 15:03:05 +02001216rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001217 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001218 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1219 "Plan SdpSemantics. Please use GetSenders "
1220 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001221 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222}
1223
Yves Gerey665174f2018-06-19 15:03:05 +02001224rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001225 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001226 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1227 "Plan SdpSemantics. Please use GetReceivers "
1228 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001229 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230}
1231
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001232bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001233 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001234 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1235 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001236 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001237 if (IsClosed()) {
1238 return false;
1239 }
deadbeefab9b2d12015-10-14 11:33:11 -07001240 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 return false;
1242 }
deadbeefab9b2d12015-10-14 11:33:11 -07001243
1244 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001245 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1246 observer->SignalAudioTrackAdded.connect(this,
1247 &PeerConnection::OnAudioTrackAdded);
1248 observer->SignalAudioTrackRemoved.connect(
1249 this, &PeerConnection::OnAudioTrackRemoved);
1250 observer->SignalVideoTrackAdded.connect(this,
1251 &PeerConnection::OnVideoTrackAdded);
1252 observer->SignalVideoTrackRemoved.connect(
1253 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001254 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001255
deadbeefab9b2d12015-10-14 11:33:11 -07001256 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001257 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001258 }
1259 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001260 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001261 }
1262
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001263 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001264 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 return true;
1266}
1267
1268void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001269 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001270 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1271 "Plan SdpSemantics. Please use RemoveTrack "
1272 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001273 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001274 if (!IsClosed()) {
1275 for (const auto& track : local_stream->GetAudioTracks()) {
1276 RemoveAudioTrack(track.get(), local_stream);
1277 }
1278 for (const auto& track : local_stream->GetVideoTracks()) {
1279 RemoveVideoTrack(track.get(), local_stream);
1280 }
deadbeefab9b2d12015-10-14 11:33:11 -07001281 }
deadbeefab9b2d12015-10-14 11:33:11 -07001282 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001283 stream_observers_.erase(
1284 std::remove_if(
1285 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001286 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001287 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001288 }),
1289 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001290
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 if (IsClosed()) {
1292 return;
1293 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001294 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295}
1296
Steve Anton2d6c76a2018-01-05 17:10:52 -08001297RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001298 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001299 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001300 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001301 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (!track) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1304 }
1305 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1306 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1308 "Track has invalid kind: " + track->kind());
1309 }
Steve Antonf9381f02017-12-14 10:23:57 -08001310 if (IsClosed()) {
1311 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1312 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001315 LOG_AND_RETURN_ERROR(
1316 RTCErrorType::INVALID_PARAMETER,
1317 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001318 }
Steve Antonf9381f02017-12-14 10:23:57 -08001319 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001320 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1321 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001322 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001323 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001324 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001325 }
1326 return sender_or_error;
1327}
deadbeefe1f9d832016-01-14 15:35:42 -08001328
Steve Antonf9381f02017-12-14 10:23:57 -08001329RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1330PeerConnection::AddTrackPlanB(
1331 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001332 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001333 if (stream_ids.size() > 1u) {
1334 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1335 "AddTrack with more than one stream is not "
1336 "supported with Plan B semantics.");
1337 }
1338 std::vector<std::string> adjusted_stream_ids = stream_ids;
1339 if (adjusted_stream_ids.empty()) {
1340 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1341 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001342 cricket::MediaType media_type =
1343 (track->kind() == MediaStreamTrackInterface::kAudioKind
1344 ? cricket::MEDIA_TYPE_AUDIO
1345 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001346 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001347 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001348 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001349 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001350 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001351 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001352 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001353 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001354 if (sender_info) {
1355 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001356 }
Steve Antonf9381f02017-12-14 10:23:57 -08001357 } else {
1358 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001359 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001360 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001361 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001362 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001363 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001364 if (sender_info) {
1365 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001366 }
deadbeefe1f9d832016-01-14 15:35:42 -08001367 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001368 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001369}
deadbeefe1f9d832016-01-14 15:35:42 -08001370
Steve Antonf9381f02017-12-14 10:23:57 -08001371RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1372PeerConnection::AddTrackUnifiedPlan(
1373 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001374 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001375 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1376 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001377 RTC_LOG(LS_INFO) << "Reusing an existing "
1378 << cricket::MediaTypeToString(transceiver->media_type())
1379 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001380 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001381 transceiver->internal()->set_direction(
1382 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001384 transceiver->internal()->set_direction(
1385 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001386 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001387 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001388 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001389 } else {
1390 cricket::MediaType media_type =
1391 (track->kind() == MediaStreamTrackInterface::kAudioKind
1392 ? cricket::MEDIA_TYPE_AUDIO
1393 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001394 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1395 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001396 std::string sender_id = track->id();
1397 // Avoid creating a sender with an existing ID by generating a random ID.
1398 // This can happen if this is the second time AddTrack has created a sender
1399 // for this track.
1400 if (FindSenderById(sender_id)) {
1401 sender_id = rtc::CreateRandomUuid();
1402 }
Florent Castelli892acf02018-10-01 22:47:20 +02001403 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1405 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001406 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001407 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001408 }
Steve Antonf9381f02017-12-14 10:23:57 -08001409 return transceiver->sender();
1410}
1411
1412rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1413PeerConnection::FindFirstTransceiverForAddedTrack(
1414 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1415 RTC_DCHECK(track);
1416 for (auto transceiver : transceivers_) {
1417 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001418 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001419 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001420 !transceiver->internal()->has_ever_been_used_to_send() &&
1421 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001422 return transceiver;
1423 }
1424 }
1425 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001426}
1427
1428bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1429 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001430 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001431}
1432
Steve Anton24db5732018-07-23 10:27:33 -07001433RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001434 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001435 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001436 if (!sender) {
1437 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1438 }
deadbeefe1f9d832016-01-14 15:35:42 -08001439 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001440 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1441 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001442 }
Steve Antonf9381f02017-12-14 10:23:57 -08001443 if (IsUnifiedPlan()) {
1444 auto transceiver = FindTransceiverBySender(sender);
1445 if (!transceiver || !sender->track()) {
1446 return RTCError::OK();
1447 }
1448 sender->SetTrack(nullptr);
1449 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001450 transceiver->internal()->set_direction(
1451 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001452 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001453 transceiver->internal()->set_direction(
1454 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001455 }
Steve Anton4171afb2017-11-20 10:20:22 -08001456 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001457 bool removed;
1458 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1459 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1460 } else {
1461 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1462 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1463 }
1464 if (!removed) {
1465 LOG_AND_RETURN_ERROR(
1466 RTCErrorType::INVALID_PARAMETER,
1467 "Couldn't find sender " + sender->id() + " to remove.");
1468 }
Steve Anton4171afb2017-11-20 10:20:22 -08001469 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001470 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001471 return RTCError::OK();
1472}
1473
1474rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1475PeerConnection::FindTransceiverBySender(
1476 rtc::scoped_refptr<RtpSenderInterface> sender) {
1477 for (auto transceiver : transceivers_) {
1478 if (transceiver->sender() == sender) {
1479 return transceiver;
1480 }
1481 }
1482 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001483}
1484
Steve Anton9158ef62017-11-27 13:01:52 -08001485RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1486PeerConnection::AddTransceiver(
1487 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1488 return AddTransceiver(track, RtpTransceiverInit());
1489}
1490
1491RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1492PeerConnection::AddTransceiver(
1493 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1494 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001495 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001496 RTC_CHECK(IsUnifiedPlan())
1497 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001498 if (!track) {
1499 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1500 }
1501 cricket::MediaType media_type;
1502 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1503 media_type = cricket::MEDIA_TYPE_AUDIO;
1504 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1505 media_type = cricket::MEDIA_TYPE_VIDEO;
1506 } else {
1507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1508 "Track kind is not audio or video");
1509 }
1510 return AddTransceiver(media_type, track, init);
1511}
1512
1513RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1514PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1515 return AddTransceiver(media_type, RtpTransceiverInit());
1516}
1517
1518RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1519PeerConnection::AddTransceiver(cricket::MediaType media_type,
1520 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001521 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001522 RTC_CHECK(IsUnifiedPlan())
1523 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001524 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1525 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1527 "media type is not audio or video");
1528 }
1529 return AddTransceiver(media_type, nullptr, init);
1530}
1531
1532RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1533PeerConnection::AddTransceiver(
1534 cricket::MediaType media_type,
1535 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001536 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001537 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001538 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1539 media_type == cricket::MEDIA_TYPE_VIDEO));
1540 if (track) {
1541 RTC_DCHECK_EQ(media_type,
1542 (track->kind() == MediaStreamTrackInterface::kAudioKind
1543 ? cricket::MEDIA_TYPE_AUDIO
1544 : cricket::MEDIA_TYPE_VIDEO));
1545 }
1546
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001547 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1548 init.send_encodings.size(), 0, 7, 8);
1549
Amit Hilbuchaa584152019-02-06 17:09:52 -08001550 size_t num_rids = absl::c_count_if(init.send_encodings,
1551 [](const RtpEncodingParameters& encoding) {
1552 return !encoding.rid.empty();
1553 });
1554 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001555 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001556 RTCErrorType::INVALID_PARAMETER,
1557 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001558 }
1559
Amit Hilbuchf4770402019-04-08 14:11:57 -07001560 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1561 [](const RtpEncodingParameters& encoding) {
1562 return !IsLegalRsidName(encoding.rid);
1563 })) {
1564 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1565 "Invalid RID value provided.");
1566 }
1567
Amit Hilbuchaa584152019-02-06 17:09:52 -08001568 if (absl::c_any_of(init.send_encodings,
1569 [](const RtpEncodingParameters& encoding) {
1570 return encoding.ssrc.has_value();
1571 })) {
1572 LOG_AND_RETURN_ERROR(
1573 RTCErrorType::UNSUPPORTED_PARAMETER,
1574 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001575 }
1576
1577 RtpParameters parameters;
1578 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001579
1580 // Encodings are dropped from the tail if too many are provided.
1581 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1582 parameters.encodings.erase(
1583 parameters.encodings.begin() + kMaxSimulcastStreams,
1584 parameters.encodings.end());
1585 }
1586
1587 // Single RID should be removed.
1588 if (parameters.encodings.size() == 1 &&
1589 !parameters.encodings[0].rid.empty()) {
1590 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1591 parameters.encodings[0].rid.clear();
1592 }
1593
1594 // If RIDs were not provided, they are generated for simulcast scenario.
1595 if (parameters.encodings.size() > 1 && num_rids == 0) {
1596 rtc::UniqueStringGenerator rid_generator;
1597 for (RtpEncodingParameters& encoding : parameters.encodings) {
1598 encoding.rid = rid_generator();
1599 }
1600 }
1601
Florent Castelli892acf02018-10-01 22:47:20 +02001602 if (UnimplementedRtpParameterHasValue(parameters)) {
1603 LOG_AND_RETURN_ERROR(
1604 RTCErrorType::UNSUPPORTED_PARAMETER,
1605 "Attempted to set an unimplemented parameter of RtpParameters.");
1606 }
Steve Anton9158ef62017-11-27 13:01:52 -08001607
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001608 auto result = cricket::CheckRtpParametersValues(parameters);
1609 if (!result.ok()) {
1610 LOG_AND_RETURN_ERROR(result.type(), result.message());
1611 }
1612
Steve Anton3d954a62018-04-02 11:27:23 -07001613 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1614 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001615 // Set the sender ID equal to the track ID if the track is specified unless
1616 // that sender ID is already in use.
1617 std::string sender_id =
1618 (track && !FindSenderById(track->id()) ? track->id()
1619 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001620 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001621 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001622 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1623 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1624 transceiver->internal()->set_direction(init.direction);
1625
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001626 if (update_negotiation_needed) {
1627 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001628 }
Steve Antonf9381f02017-12-14 10:23:57 -08001629
1630 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1631}
1632
Steve Anton02ee47c2018-01-10 16:26:06 -08001633rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1634PeerConnection::CreateSender(
1635 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001636 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001637 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001638 const std::vector<std::string>& stream_ids,
1639 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001640 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001641 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001642 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1643 RTC_DCHECK(!track ||
1644 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1645 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1646 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001647 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001648 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001649 } else {
1650 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1651 RTC_DCHECK(!track ||
1652 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1653 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001654 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001655 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001656 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001657 bool set_track_succeeded = sender->SetTrack(track);
1658 RTC_DCHECK(set_track_succeeded);
1659 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001660 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001661 return sender;
1662}
1663
1664rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1665PeerConnection::CreateReceiver(cricket::MediaType media_type,
1666 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001667 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1668 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001669 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001670 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001671 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1672 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001673 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001674 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001675 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001676 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001677 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1678 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001679 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001680 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001681 return receiver;
1682}
1683
1684rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1685PeerConnection::CreateAndAddTransceiver(
1686 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1687 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1688 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001689 // Ensure that the new sender does not have an ID that is already in use by
1690 // another sender.
1691 // Allow receiver IDs to conflict since those come from remote SDP (which
1692 // could be invalid, but should not cause a crash).
1693 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001694 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001695 signaling_thread(),
1696 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001697 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001698 transceiver->internal()->SignalNegotiationNeeded.connect(
1699 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001700 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001701}
1702
Steve Anton52d86772018-02-20 15:48:12 -08001703void PeerConnection::OnNegotiationNeeded() {
1704 RTC_DCHECK_RUN_ON(signaling_thread());
1705 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001706 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001707}
1708
deadbeeffac06552015-11-25 11:26:01 -08001709rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001710 const std::string& kind,
1711 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001712 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001713 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1714 "Plan SdpSemantics. Please use AddTransceiver "
1715 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001716 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001717 if (IsClosed()) {
1718 return nullptr;
1719 }
Steve Anton4171afb2017-11-20 10:20:22 -08001720
Seth Hampson5b4f0752018-04-02 16:31:36 -07001721 // Internally we need to have one stream with Plan B semantics, so we
1722 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001723 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001724 if (stream_id.empty()) {
1725 stream_ids.push_back(rtc::CreateRandomUuid());
1726 RTC_LOG(LS_INFO)
1727 << "No stream_id specified for sender. Generated stream ID: "
1728 << stream_ids[0];
1729 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001730 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001731 }
1732
Steve Anton4171afb2017-11-20 10:20:22 -08001733 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001734 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001735 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001736 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001737 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001738 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001739 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001740 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001741 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001742 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001743 auto video_sender =
1744 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001745 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001746 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001747 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001748 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001749 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001750 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001751 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001752 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001753 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001754
deadbeefe1f9d832016-01-14 15:35:42 -08001755 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001756}
1757
deadbeef70ab1a12015-09-28 16:53:55 -07001758std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1759 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001760 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001761 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001762 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001763 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001764 }
1765 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001766}
1767
Steve Anton4171afb2017-11-20 10:20:22 -08001768std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1769PeerConnection::GetSendersInternal() const {
1770 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1771 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001772 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001773 auto senders = transceiver->internal()->senders();
1774 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1775 }
1776 return all_senders;
1777}
1778
deadbeef70ab1a12015-09-28 16:53:55 -07001779std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1780PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001781 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001782 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001783 for (const auto& receiver : GetReceiversInternal()) {
1784 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001785 }
1786 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001787}
1788
Steve Anton4171afb2017-11-20 10:20:22 -08001789std::vector<
1790 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1791PeerConnection::GetReceiversInternal() const {
1792 std::vector<
1793 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1794 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001795 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001796 auto receivers = transceiver->internal()->receivers();
1797 all_receivers.insert(all_receivers.end(), receivers.begin(),
1798 receivers.end());
1799 }
1800 return all_receivers;
1801}
1802
Steve Anton9158ef62017-11-27 13:01:52 -08001803std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1804PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001805 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001806 RTC_CHECK(IsUnifiedPlan())
1807 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001808 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001809 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001810 all_transceivers.push_back(transceiver);
1811 }
1812 return all_transceivers;
1813}
1814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001816 MediaStreamTrackInterface* track,
1817 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001818 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001819 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001820 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001821 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 return false;
1823 }
1824
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001825 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001826 // The StatsCollector is used to tell if a track is valid because it may
1827 // remember tracks that the PeerConnection previously removed.
1828 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001829 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1830 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001831 return false;
1832 }
Steve Antonad182762018-09-05 20:22:40 +00001833 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1834 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835 return true;
1836}
1837
hbos74e1a4f2016-09-15 23:33:01 -07001838void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001839 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001840 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001841 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001842 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001843 stats_collector_->GetStatsReport(callback);
1844}
1845
Henrik Boström1df1bf82018-03-20 13:24:20 +01001846void PeerConnection::GetStats(
1847 rtc::scoped_refptr<RtpSenderInterface> selector,
1848 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1849 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001850 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001851 RTC_DCHECK(callback);
1852 RTC_DCHECK(stats_collector_);
1853 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1854 if (selector) {
1855 for (const auto& proxy_transceiver : transceivers_) {
1856 for (const auto& proxy_sender :
1857 proxy_transceiver->internal()->senders()) {
1858 if (proxy_sender == selector) {
1859 internal_sender = proxy_sender->internal();
1860 break;
1861 }
1862 }
1863 if (internal_sender)
1864 break;
1865 }
1866 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001867 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001868 // belong to the PeerConnection (in Plan B, senders can be removed from the
1869 // PeerConnection). This means that "all the stats objects representing the
1870 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1871 // produces an empty stats report.
1872 stats_collector_->GetStatsReport(internal_sender, callback);
1873}
1874
1875void PeerConnection::GetStats(
1876 rtc::scoped_refptr<RtpReceiverInterface> selector,
1877 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1878 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001879 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001880 RTC_DCHECK(callback);
1881 RTC_DCHECK(stats_collector_);
1882 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1883 if (selector) {
1884 for (const auto& proxy_transceiver : transceivers_) {
1885 for (const auto& proxy_receiver :
1886 proxy_transceiver->internal()->receivers()) {
1887 if (proxy_receiver == selector) {
1888 internal_receiver = proxy_receiver->internal();
1889 break;
1890 }
1891 }
1892 if (internal_receiver)
1893 break;
1894 }
1895 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001896 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001897 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1898 // the PeerConnection). This means that "all the stats objects representing
1899 // the selector" is an empty set. Invoking GetStatsReport() with a null
1900 // selector produces an empty stats report.
1901 stats_collector_->GetStatsReport(internal_receiver, callback);
1902}
1903
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001905 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906 return signaling_state_;
1907}
1908
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001909PeerConnectionInterface::IceConnectionState
1910PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 return ice_connection_state_;
1913}
1914
Alex Loiko9289eda2018-11-23 16:18:59 +00001915PeerConnectionInterface::IceConnectionState
1916PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001918 return standardized_ice_connection_state_;
1919}
1920
Jonas Olsson635474e2018-10-18 15:58:17 +02001921PeerConnectionInterface::PeerConnectionState
1922PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001923 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001924 return connection_state_;
1925}
1926
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927PeerConnectionInterface::IceGatheringState
1928PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001929 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 return ice_gathering_state_;
1931}
1932
Yves Gerey665174f2018-06-19 15:03:05 +02001933rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 const std::string& label,
1935 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001936 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001937 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001938
deadbeefab9b2d12015-10-14 11:33:11 -07001939 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001940
kwibergd1fe2812016-04-27 06:47:29 -07001941 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001942 if (config) {
1943 internal_config.reset(new InternalDataChannelInit(*config));
1944 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001945 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001946 InternalCreateDataChannel(label, internal_config.get()));
1947 if (!channel.get()) {
1948 return nullptr;
1949 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001951 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1952 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001953 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001954 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001955 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001956 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 return DataChannelProxy::Create(signaling_thread(), channel.get());
1958}
1959
1960void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001961 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001962 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001963 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001964
nisse7ce109a2017-01-31 00:57:56 -08001965 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001966 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001967 return;
1968 }
deadbeefab9b2d12015-10-14 11:33:11 -07001969
Steve Anton8d3444d2017-10-20 15:30:51 -07001970 if (IsClosed()) {
1971 std::string error = "CreateOffer called when PeerConnection is closed.";
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_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001975 return;
1976 }
1977
zhihuang1c378ed2017-08-17 14:10:50 -07001978 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001979 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001980 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001981 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001982 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001983 return;
1984 }
1985
Steve Anton22da89f2018-01-25 13:58:07 -08001986 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1987 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1988 if (IsUnifiedPlan()) {
1989 RTCError error = HandleLegacyOfferOptions(options);
1990 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001991 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001992 return;
1993 }
1994 }
1995
zhihuang1c378ed2017-08-17 14:10:50 -07001996 cricket::MediaSessionOptions session_options;
1997 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001998 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001999}
2000
Steve Anton22da89f2018-01-25 13:58:07 -08002001RTCError PeerConnection::HandleLegacyOfferOptions(
2002 const RTCOfferAnswerOptions& options) {
2003 RTC_DCHECK(IsUnifiedPlan());
2004
2005 if (options.offer_to_receive_audio == 0) {
2006 RemoveRecvDirectionFromReceivingTransceiversOfType(
2007 cricket::MEDIA_TYPE_AUDIO);
2008 } else if (options.offer_to_receive_audio == 1) {
2009 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2010 } else if (options.offer_to_receive_audio > 1) {
2011 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2012 "offer_to_receive_audio > 1 is not supported.");
2013 }
2014
2015 if (options.offer_to_receive_video == 0) {
2016 RemoveRecvDirectionFromReceivingTransceiversOfType(
2017 cricket::MEDIA_TYPE_VIDEO);
2018 } else if (options.offer_to_receive_video == 1) {
2019 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2020 } else if (options.offer_to_receive_video > 1) {
2021 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2022 "offer_to_receive_video > 1 is not supported.");
2023 }
2024
2025 return RTCError::OK();
2026}
2027
2028void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2029 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002030 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002031 RtpTransceiverDirection new_direction =
2032 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2033 if (new_direction != transceiver->direction()) {
2034 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2035 << " transceiver (MID="
2036 << transceiver->mid().value_or("<not set>") << ") from "
2037 << RtpTransceiverDirectionToString(
2038 transceiver->direction())
2039 << " to "
2040 << RtpTransceiverDirectionToString(new_direction)
2041 << " since CreateOffer specified offer_to_receive=0";
2042 transceiver->internal()->set_direction(new_direction);
2043 }
Steve Anton22da89f2018-01-25 13:58:07 -08002044 }
2045}
2046
2047void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2048 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002049 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002050 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002051 RTC_LOG(LS_INFO)
2052 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2053 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002054 RtpTransceiverInit init;
2055 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002056 AddTransceiver(media_type, nullptr, init,
2057 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002058 }
2059}
2060
2061std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2062PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2063 std::vector<
2064 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2065 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002066 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002067 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002068 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2069 receiving_transceivers.push_back(transceiver);
2070 }
2071 }
2072 return receiving_transceivers;
2073}
2074
htaa2a49d92016-03-04 02:51:39 -08002075void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2076 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002077 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002078 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002079 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002080 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002081 return;
2082 }
2083
Steve Antondffead82018-02-06 10:31:29 -08002084 if (!(signaling_state_ == kHaveRemoteOffer ||
2085 signaling_state_ == kHaveLocalPrAnswer)) {
2086 std::string error =
2087 "PeerConnection cannot create an answer in a state other than "
2088 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002089 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002090 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002091 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002092 return;
2093 }
2094
Steve Antondffead82018-02-06 10:31:29 -08002095 // The remote description should be set if we're in the right state.
2096 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002097
Steve Anton22da89f2018-01-25 13:58:07 -08002098 if (IsUnifiedPlan()) {
2099 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2100 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2101 "supported with Unified Plan semantics. Use the "
2102 "RtpTransceiver API instead.";
2103 }
2104 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2105 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2106 "supported with Unified Plan semantics. Use the "
2107 "RtpTransceiver API instead.";
2108 }
2109 }
2110
htaa2a49d92016-03-04 02:51:39 -08002111 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002112 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002113
Steve Antond25da372017-11-06 14:50:29 -08002114 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115}
2116
2117void PeerConnection::SetLocalDescription(
2118 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002119 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002120 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002121 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002122
Steve Anton80dd7b52018-02-16 17:08:42 -08002123 // The SetLocalDescription contract is that we take ownership of the session
2124 // description regardless of the outcome, so wrap it in a unique_ptr right
2125 // away. Ideally, SetLocalDescription's signature will be changed to take the
2126 // description as a unique_ptr argument to formalize this agreement.
2127 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2128
nisse7ce109a2017-01-31 00:57:56 -08002129 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002130 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 return;
2132 }
Steve Anton8a006912017-12-04 15:25:56 -08002133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002135 PostSetSessionDescriptionFailure(
2136 observer,
2137 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 return;
2139 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002140
Steve Anton80dd7b52018-02-16 17:08:42 -08002141 // If a session error has occurred the PeerConnection is in a possibly
2142 // inconsistent state so fail right away.
2143 if (session_error() != SessionError::kNone) {
2144 std::string error_message = GetSessionErrorMsg();
2145 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002146 PostSetSessionDescriptionFailure(
2147 observer,
2148 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002149 return;
2150 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002151
Steve Anton80dd7b52018-02-16 17:08:42 -08002152 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2153 if (!error.ok()) {
2154 std::string error_message = GetSetDescriptionErrorMessage(
2155 cricket::CS_LOCAL, desc->GetType(), error);
2156 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002157 PostSetSessionDescriptionFailure(
2158 observer,
2159 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002160 return;
2161 }
2162
2163 // Grab the description type before moving ownership to ApplyLocalDescription,
2164 // which may destroy it before returning.
2165 const SdpType type = desc->GetType();
2166
2167 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002168 // |desc| may be destroyed at this point.
2169
2170 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002171 // If ApplyLocalDescription fails, the PeerConnection could be in an
2172 // inconsistent state, so act conservatively here and set the session error
2173 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2174 SetSessionError(SessionError::kContent, error.message());
2175 std::string error_message =
2176 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2177 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002178 PostSetSessionDescriptionFailure(
2179 observer,
2180 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002181 return;
2182 }
Steve Anton8a006912017-12-04 15:25:56 -08002183 RTC_DCHECK(local_description());
2184
2185 PostSetSessionDescriptionSuccess(observer);
2186
Steve Antonad182762018-09-05 20:22:40 +00002187 // MaybeStartGathering needs to be called after posting
2188 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2189 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002190 transport_controller_->MaybeStartGathering();
2191
Steve Antona3a92c22017-12-07 10:27:41 -08002192 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002193 // TODO(deadbeef): We already had to hop to the network thread for
2194 // MaybeStartGathering...
2195 network_thread()->Invoke<void>(
2196 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2197 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002198 // Make UMA notes about what was agreed to.
2199 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002200 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002201
2202 if (IsUnifiedPlan()) {
2203 bool was_negotiation_needed = is_negotiation_needed_;
2204 UpdateNegotiationNeeded();
2205 if (signaling_state() == kStable && was_negotiation_needed &&
2206 is_negotiation_needed_) {
2207 Observer()->OnRenegotiationNeeded();
2208 }
2209 }
2210
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002211 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002212}
2213
2214RTCError PeerConnection::ApplyLocalDescription(
2215 std::unique_ptr<SessionDescriptionInterface> desc) {
2216 RTC_DCHECK_RUN_ON(signaling_thread());
2217 RTC_DCHECK(desc);
2218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 // Update stats here so that we have the most recent stats for tracks and
2220 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002221 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002222
Steve Antondcc3c022017-12-22 16:02:54 -08002223 // Take a reference to the old local description since it's used below to
2224 // compare against the new local description. When setting the new local
2225 // description, grab ownership of the replaced session description in case it
2226 // is the same as |old_local_description|, to keep it alive for the duration
2227 // of the method.
2228 const SessionDescriptionInterface* old_local_description =
2229 local_description();
2230 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002231 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002232 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002233 replaced_local_description = pending_local_description_
2234 ? std::move(pending_local_description_)
2235 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002236 current_local_description_ = std::move(desc);
2237 pending_local_description_ = nullptr;
2238 current_remote_description_ = std::move(pending_remote_description_);
2239 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002240 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002241 pending_local_description_ = std::move(desc);
2242 }
2243 // The session description to apply now must be accessed by
2244 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002245 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002246
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002247 // Report statistics about any use of simulcast.
2248 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2249 *local_description()->description());
2250
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002251 if (!is_caller_) {
2252 if (remote_description()) {
2253 // Remote description was applied first, so this PC is the callee.
2254 is_caller_ = false;
2255 } else {
2256 // Local description is applied first, so this PC is the caller.
2257 is_caller_ = true;
2258 }
2259 }
2260
Zhi Huange830e682018-03-30 10:48:35 -07002261 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2262 if (!error.ok()) {
2263 return error;
2264 }
2265
Steve Antondcc3c022017-12-22 16:02:54 -08002266 if (IsUnifiedPlan()) {
2267 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002268 cricket::CS_LOCAL, *local_description(), old_local_description,
2269 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002270 if (!error.ok()) {
2271 return error;
2272 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002273 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2274 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002275 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002276 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2277 // Note that code paths that don't set MID won't be able to use
2278 // information about DTLS transports.
2279 if (transceiver->mid()) {
2280 auto dtls_transport =
2281 LookupDtlsTransportByMidInternal(*transceiver->mid());
2282 transceiver->internal()->sender_internal()->set_transport(
2283 dtls_transport);
2284 transceiver->internal()->receiver_internal()->set_transport(
2285 dtls_transport);
2286 }
2287
Steve Antondcc3c022017-12-22 16:02:54 -08002288 const ContentInfo* content =
2289 FindMediaSectionForTransceiver(transceiver, local_description());
2290 if (!content) {
2291 continue;
2292 }
2293 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002294 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2295 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002296 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002297 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2298 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2299 // "recvonly", process the removal of a remote track for the media
2300 // description, given transceiver, removeList, and muteTracks.
2301 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2302 (transceiver->internal()->fired_direction() &&
2303 RtpTransceiverDirectionHasRecv(
2304 *transceiver->internal()->fired_direction()))) {
2305 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2306 &removed_streams);
2307 }
2308 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2309 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002310 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002311 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002312 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002313 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002314 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002315 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002316 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002317 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002318 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002319 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002320 }
2321 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002322 // Media channels will be created only when offer is set. These may use new
2323 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (type == SdpType::kOffer) {
2325 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2326 // description is applied. Restore back to old description.
2327 RTCError error = CreateChannels(*local_description()->description());
2328 if (!error.ok()) {
2329 return error;
2330 }
2331 }
Steve Antondcc3c022017-12-22 16:02:54 -08002332 // Remove unused channels if MediaContentDescription is rejected.
2333 RemoveUnusedChannels(local_description()->description());
2334 }
Steve Anton8a006912017-12-04 15:25:56 -08002335
Zhi Huange830e682018-03-30 10:48:35 -07002336 error = UpdateSessionState(type, cricket::CS_LOCAL,
2337 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002338 if (!error.ok()) {
2339 return error;
2340 }
Steve Antondcc3c022017-12-22 16:02:54 -08002341
Steve Anton8a006912017-12-04 15:25:56 -08002342 if (remote_description()) {
2343 // Now that we have a local description, we can push down remote candidates.
2344 UseCandidatesInSessionDescription(remote_description());
2345 }
2346
2347 pending_ice_restarts_.clear();
2348 if (session_error() != SessionError::kNone) {
2349 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2350 }
2351
deadbeefab9b2d12015-10-14 11:33:11 -07002352 // If setting the description decided our SSL role, allocate any necessary
2353 // SCTP sids.
2354 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002355 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002356 AllocateSctpSids(role);
2357 }
2358
Steve Antond3679212018-01-17 17:41:02 -08002359 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002360 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002361 const ContentInfo* content =
2362 FindMediaSectionForTransceiver(transceiver, local_description());
2363 if (!content) {
2364 continue;
2365 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002366 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2367 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002368 // 0 is a special value meaning "this sender has no associated send
2369 // stream". Need to call this so the sender won't attempt to configure
2370 // a no longer existing stream and run into DCHECKs in the lower
2371 // layers.
2372 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002373 } else {
2374 // Get the StreamParams from the channel which could generate SSRCs.
2375 const std::vector<StreamParams>& streams = channel->local_streams();
2376 transceiver->internal()->sender_internal()->set_stream_ids(
2377 streams[0].stream_ids());
2378 transceiver->internal()->sender_internal()->SetSsrc(
2379 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002380 }
2381 }
2382 } else {
2383 // Plan B semantics.
2384
Steve Antondcc3c022017-12-22 16:02:54 -08002385 // Update state and SSRC of local MediaStreams and DataChannels based on the
2386 // local session description.
2387 const cricket::ContentInfo* audio_content =
2388 GetFirstAudioContent(local_description()->description());
2389 if (audio_content) {
2390 if (audio_content->rejected) {
2391 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2392 } else {
2393 const cricket::AudioContentDescription* audio_desc =
2394 audio_content->media_description()->as_audio();
2395 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2396 }
deadbeeffaac4972015-11-12 15:33:07 -08002397 }
deadbeefab9b2d12015-10-14 11:33:11 -07002398
Steve Antondcc3c022017-12-22 16:02:54 -08002399 const cricket::ContentInfo* video_content =
2400 GetFirstVideoContent(local_description()->description());
2401 if (video_content) {
2402 if (video_content->rejected) {
2403 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2404 } else {
2405 const cricket::VideoContentDescription* video_desc =
2406 video_content->media_description()->as_video();
2407 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2408 }
deadbeeffaac4972015-11-12 15:33:07 -08002409 }
deadbeefab9b2d12015-10-14 11:33:11 -07002410 }
2411
2412 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002413 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002414 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002415 const cricket::RtpDataContentDescription* rtp_data_desc =
2416 data_content->media_description()->as_rtp_data();
2417 // rtp_data_desc will be null if this is an SCTP description.
2418 if (rtp_data_desc) {
2419 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002420 }
2421 }
2422
Steve Anton8a006912017-12-04 15:25:56 -08002423 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424}
2425
Steve Anton06817cd2018-12-18 15:55:30 -08002426// The SDP parser used to populate these values by default for the 'content
2427// name' if an a=mid line was absent.
2428static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2429 switch (media_type) {
2430 case cricket::MEDIA_TYPE_AUDIO:
2431 return cricket::CN_AUDIO;
2432 case cricket::MEDIA_TYPE_VIDEO:
2433 return cricket::CN_VIDEO;
2434 case cricket::MEDIA_TYPE_DATA:
2435 return cricket::CN_DATA;
2436 }
2437 RTC_NOTREACHED();
2438 return "";
2439}
2440
2441void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002442 cricket::SessionDescription* new_remote_description) {
2443 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002444 const cricket::ContentInfos& local_contents =
2445 (local_description() ? local_description()->description()->contents()
2446 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002447 const cricket::ContentInfos& remote_contents =
2448 (remote_description() ? remote_description()->description()->contents()
2449 : cricket::ContentInfos());
2450 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2451 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002452 if (!content.name.empty()) {
2453 continue;
2454 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002455 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002456 absl::string_view source_explanation;
2457 if (IsUnifiedPlan()) {
2458 if (i < local_contents.size()) {
2459 new_mid = local_contents[i].name;
2460 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002461 } else if (i < remote_contents.size()) {
2462 new_mid = remote_contents[i].name;
2463 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002464 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002465 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002466 source_explanation = "generated just now";
2467 }
2468 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002469 new_mid = std::string(
2470 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002471 source_explanation = "to match pre-existing behavior";
2472 }
Steve Antond7180cc2019-02-07 10:44:53 -08002473 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002474 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002475 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002476 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2477 << " is missing an a=mid line. Filling in the value '"
2478 << new_mid << "' " << source_explanation << ".";
2479 }
2480}
2481
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002482void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002483 SetSessionDescriptionObserver* observer,
2484 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002485 SetRemoteDescription(
2486 std::unique_ptr<SessionDescriptionInterface>(desc),
2487 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2488 new SetRemoteDescriptionObserverAdapter(this, observer)));
2489}
2490
2491void PeerConnection::SetRemoteDescription(
2492 std::unique_ptr<SessionDescriptionInterface> desc,
2493 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002494 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002495 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002496
nisse7ce109a2017-01-31 00:57:56 -08002497 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002498 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 return;
2500 }
Steve Anton8a006912017-12-04 15:25:56 -08002501
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002503 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002504 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002505 return;
2506 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002507
Steve Anton80dd7b52018-02-16 17:08:42 -08002508 // If a session error has occurred the PeerConnection is in a possibly
2509 // inconsistent state so fail right away.
2510 if (session_error() != SessionError::kNone) {
2511 std::string error_message = GetSessionErrorMsg();
2512 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2513 observer->OnSetRemoteDescriptionComplete(
2514 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2515 return;
2516 }
Steve Anton71439a62018-02-15 11:53:06 -08002517
Steve Antonba42e992018-04-09 14:10:01 -07002518 if (desc->GetType() == SdpType::kOffer) {
2519 // Report to UMA the format of the received offer.
2520 ReportSdpFormatReceived(*desc);
2521 }
2522
Steve Anton06817cd2018-12-18 15:55:30 -08002523 // Handle remote descriptions missing a=mid lines for interop with legacy end
2524 // points.
2525 FillInMissingRemoteMids(desc->description());
2526
Steve Anton80dd7b52018-02-16 17:08:42 -08002527 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002528 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002529 std::string error_message = GetSetDescriptionErrorMessage(
2530 cricket::CS_REMOTE, desc->GetType(), error);
2531 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002532 observer->OnSetRemoteDescriptionComplete(
2533 RTCError(error.type(), std::move(error_message)));
2534 return;
2535 }
Steve Anton71439a62018-02-15 11:53:06 -08002536
Steve Anton80dd7b52018-02-16 17:08:42 -08002537 // Grab the description type before moving ownership to
2538 // ApplyRemoteDescription, which may destroy it before returning.
2539 const SdpType type = desc->GetType();
2540
2541 error = ApplyRemoteDescription(std::move(desc));
2542 // |desc| may be destroyed at this point.
2543
2544 if (!error.ok()) {
2545 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2546 // inconsistent state, so act conservatively here and set the session error
2547 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2548 SetSessionError(SessionError::kContent, error.message());
2549 std::string error_message =
2550 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2551 RTC_LOG(LS_ERROR) << error_message;
2552 observer->OnSetRemoteDescriptionComplete(
2553 RTCError(error.type(), std::move(error_message)));
2554 return;
2555 }
2556 RTC_DCHECK(remote_description());
2557
2558 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002559 // TODO(deadbeef): We already had to hop to the network thread for
2560 // MaybeStartGathering...
2561 network_thread()->Invoke<void>(
2562 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2563 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002564 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002565 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002566 }
2567
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002568 if (IsUnifiedPlan()) {
2569 bool was_negotiation_needed = is_negotiation_needed_;
2570 UpdateNegotiationNeeded();
2571 if (signaling_state() == kStable && was_negotiation_needed &&
2572 is_negotiation_needed_) {
2573 Observer()->OnRenegotiationNeeded();
2574 }
2575 }
2576
Steve Anton8a006912017-12-04 15:25:56 -08002577 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002578 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002579}
2580
2581RTCError PeerConnection::ApplyRemoteDescription(
2582 std::unique_ptr<SessionDescriptionInterface> desc) {
2583 RTC_DCHECK_RUN_ON(signaling_thread());
2584 RTC_DCHECK(desc);
2585
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002586 // Update stats here so that we have the most recent stats for tracks and
2587 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002588 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002589
Steve Antondcc3c022017-12-22 16:02:54 -08002590 // Take a reference to the old remote description since it's used below to
2591 // compare against the new remote description. When setting the new remote
2592 // description, grab ownership of the replaced session description in case it
2593 // is the same as |old_remote_description|, to keep it alive for the duration
2594 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002595 const SessionDescriptionInterface* old_remote_description =
2596 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002597 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002598 SdpType type = desc->GetType();
2599 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002600 replaced_remote_description = pending_remote_description_
2601 ? std::move(pending_remote_description_)
2602 : std::move(current_remote_description_);
2603 current_remote_description_ = std::move(desc);
2604 pending_remote_description_ = nullptr;
2605 current_local_description_ = std::move(pending_local_description_);
2606 } else {
2607 replaced_remote_description = std::move(pending_remote_description_);
2608 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 }
Steve Anton8a006912017-12-04 15:25:56 -08002610 // The session description to apply now must be accessed by
2611 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002612 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002614 // Report statistics about any use of simulcast.
2615 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2616 *remote_description()->description());
2617
Zhi Huange830e682018-03-30 10:48:35 -07002618 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2619 if (!error.ok()) {
2620 return error;
2621 }
Steve Anton8a006912017-12-04 15:25:56 -08002622 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002623 if (IsUnifiedPlan()) {
2624 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002625 cricket::CS_REMOTE, *remote_description(), local_description(),
2626 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002627 if (!error.ok()) {
2628 return error;
2629 }
Steve Antondcc3c022017-12-22 16:02:54 -08002630 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002631 // Media channels will be created only when offer is set. These may use new
2632 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002633 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002634 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002635 // description is applied. Restore back to old description.
2636 RTCError error = CreateChannels(*remote_description()->description());
2637 if (!error.ok()) {
2638 return error;
2639 }
2640 }
Steve Antondcc3c022017-12-22 16:02:54 -08002641 // Remove unused channels if MediaContentDescription is rejected.
2642 RemoveUnusedChannels(remote_description()->description());
2643 }
Steve Anton8a006912017-12-04 15:25:56 -08002644
Zhi Huange830e682018-03-30 10:48:35 -07002645 // NOTE: Candidates allocation will be initiated only when
2646 // SetLocalDescription is called.
2647 error = UpdateSessionState(type, cricket::CS_REMOTE,
2648 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002649 if (!error.ok()) {
2650 return error;
2651 }
2652
2653 if (local_description() &&
2654 !UseCandidatesInSessionDescription(remote_description())) {
2655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2656 }
2657
2658 if (old_remote_description) {
2659 for (const cricket::ContentInfo& content :
2660 old_remote_description->description()->contents()) {
2661 // Check if this new SessionDescription contains new ICE ufrag and
2662 // password that indicates the remote peer requests an ICE restart.
2663 // TODO(deadbeef): When we start storing both the current and pending
2664 // remote description, this should reset pending_ice_restarts and compare
2665 // against the current description.
2666 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2667 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002668 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002669 pending_ice_restarts_.insert(content.name);
2670 }
2671 } else {
2672 // We retain all received candidates only if ICE is not restarted.
2673 // When ICE is restarted, all previous candidates belong to an old
2674 // generation and should not be kept.
2675 // TODO(deadbeef): This goes against the W3C spec which says the remote
2676 // description should only contain candidates from the last set remote
2677 // description plus any candidates added since then. We should remove
2678 // this once we're sure it won't break anything.
2679 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2680 old_remote_description, content.name, mutable_remote_description());
2681 }
2682 }
2683 }
2684
2685 if (session_error() != SessionError::kNone) {
2686 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2687 }
2688
2689 // Set the the ICE connection state to connecting since the connection may
2690 // become writable with peer reflexive candidates before any remote candidate
2691 // is signaled.
2692 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2693 // is to have a new signal the indicates a change in checking state from the
2694 // transport and expose a new checking() member from transport that can be
2695 // read to determine the current checking state. The existing SignalConnecting
2696 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002697 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002698 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002699 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2700 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2701 }
2702
deadbeefab9b2d12015-10-14 11:33:11 -07002703 // If setting the description decided our SSL role, allocate any necessary
2704 // SCTP sids.
2705 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002706 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002707 AllocateSctpSids(role);
2708 }
2709
Steve Antondcc3c022017-12-22 16:02:54 -08002710 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002711 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002712 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002713 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002714 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002715 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002716 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002717 const ContentInfo* content =
2718 FindMediaSectionForTransceiver(transceiver, remote_description());
2719 if (!content) {
2720 continue;
2721 }
2722 const MediaContentDescription* media_desc = content->media_description();
2723 RtpTransceiverDirection local_direction =
2724 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002725 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2726 // RTCSessionDescription: Set the associated remote streams given
2727 // transceiver.[[Receiver]], msids, addList, and removeList".
2728 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2729 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2730 std::vector<std::string> stream_ids;
2731 if (!media_desc->streams().empty()) {
2732 // The remote description has signaled the stream IDs.
2733 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002734 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002735 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2736 << " (" << GetStreamIdsString(stream_ids) << ").";
2737 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2738 stream_ids, &added_streams,
2739 &removed_streams);
2740 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2741 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2742 // and transceiver's current direction is neither sendrecv nor recvonly,
2743 // process the addition of a remote track for the media description.
2744 if (!transceiver->fired_direction() ||
2745 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2746 RTC_LOG(LS_INFO)
2747 << "Processing the addition of a remote track for MID="
2748 << content->name << ".";
2749 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002750 }
Steve Antondcc3c022017-12-22 16:02:54 -08002751 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002752 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2754 // removal of a remote track for the media description, given transceiver,
2755 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002756 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002757 (transceiver->fired_direction() &&
2758 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2759 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2760 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002761 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002763 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002764 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002765 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002766 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002767 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002768 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002769 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002770 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2771 if (transceiver->mid()) {
2772 auto dtls_transport =
2773 LookupDtlsTransportByMidInternal(*transceiver->mid());
2774 transceiver->internal()->sender_internal()->set_transport(
2775 dtls_transport);
2776 transceiver->internal()->receiver_internal()->set_transport(
2777 dtls_transport);
2778 }
Steve Antondcc3c022017-12-22 16:02:54 -08002779 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002780 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002781 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002782 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002783 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2784 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002785 transceiver->Stop();
2786 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002787 if (!content->rejected &&
2788 RtpTransceiverDirectionHasRecv(local_direction)) {
2789 // Set ssrc to 0 in the case of an unsignalled ssrc.
2790 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002791 if (!media_desc->streams().empty() &&
2792 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002793 ssrc = media_desc->streams()[0].first_ssrc();
2794 }
2795 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002796 }
Steve Antondcc3c022017-12-22 16:02:54 -08002797 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002798 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002799 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002801 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002802 observer->OnTrack(transceiver);
2803 observer->OnAddTrack(transceiver->receiver(),
2804 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002805 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002806 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002807 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002808 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002809 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002810 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002811 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002812 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002813 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002814 }
Steve Antondcc3c022017-12-22 16:02:54 -08002815 }
2816
Henrik Boströmfdb92012017-11-09 19:55:44 +01002817 const cricket::ContentInfo* audio_content =
2818 GetFirstAudioContent(remote_description()->description());
2819 const cricket::ContentInfo* video_content =
2820 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002821 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002822 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002823 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002824 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002825 const cricket::RtpDataContentDescription* rtp_data_desc =
2826 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002827
2828 // Check if the descriptions include streams, just in case the peer supports
2829 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002830 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002831 (audio_desc && !audio_desc->streams().empty()) ||
2832 (video_desc && !video_desc->streams().empty())) {
2833 remote_peer_supports_msid_ = true;
2834 }
deadbeefab9b2d12015-10-14 11:33:11 -07002835
2836 // We wait to signal new streams until we finish processing the description,
2837 // since only at that point will new streams have all their tracks.
2838 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2839
Steve Antondcc3c022017-12-22 16:02:54 -08002840 if (!IsUnifiedPlan()) {
2841 // TODO(steveanton): When removing RTP senders/receivers in response to a
2842 // rejected media section, there is some cleanup logic that expects the
2843 // voice/ video channel to still be set. But in this method the voice/video
2844 // channel would have been destroyed by the SetRemoteDescription caller
2845 // above so the cleanup that relies on them fails to run. The RemoveSenders
2846 // calls should be moved to right before the DestroyChannel calls to fix
2847 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002848
Steve Antondcc3c022017-12-22 16:02:54 -08002849 // Find all audio rtp streams and create corresponding remote AudioTracks
2850 // and MediaStreams.
2851 if (audio_content) {
2852 if (audio_content->rejected) {
2853 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2854 } else {
2855 bool default_audio_track_needed =
2856 !remote_peer_supports_msid_ &&
2857 RtpTransceiverDirectionHasSend(audio_desc->direction());
2858 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2859 default_audio_track_needed, audio_desc->type(),
2860 new_streams);
2861 }
deadbeeffaac4972015-11-12 15:33:07 -08002862 }
deadbeefab9b2d12015-10-14 11:33:11 -07002863
Steve Antondcc3c022017-12-22 16:02:54 -08002864 // Find all video rtp streams and create corresponding remote VideoTracks
2865 // and MediaStreams.
2866 if (video_content) {
2867 if (video_content->rejected) {
2868 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2869 } else {
2870 bool default_video_track_needed =
2871 !remote_peer_supports_msid_ &&
2872 RtpTransceiverDirectionHasSend(video_desc->direction());
2873 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2874 default_video_track_needed, video_desc->type(),
2875 new_streams);
2876 }
deadbeeffaac4972015-11-12 15:33:07 -08002877 }
deadbeefab9b2d12015-10-14 11:33:11 -07002878
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002879 // If this is an RTP data transport, update the DataChannels with the
2880 // information from the remote peer.
2881 if (rtp_data_desc) {
2882 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002883 }
deadbeefab9b2d12015-10-14 11:33:11 -07002884
Steve Antondcc3c022017-12-22 16:02:54 -08002885 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002886 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002887 for (size_t i = 0; i < new_streams->count(); ++i) {
2888 MediaStreamInterface* new_stream = new_streams->at(i);
2889 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002890 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002891 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2892 }
deadbeefab9b2d12015-10-14 11:33:11 -07002893
Steve Antondcc3c022017-12-22 16:02:54 -08002894 UpdateEndedRemoteMediaStreams();
2895 }
deadbeefab9b2d12015-10-14 11:33:11 -07002896
Steve Anton8a006912017-12-04 15:25:56 -08002897 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002898}
2899
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002900void PeerConnection::SetAssociatedRemoteStreams(
2901 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2902 const std::vector<std::string>& stream_ids,
2903 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2904 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2905 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2906 for (const std::string& stream_id : stream_ids) {
2907 rtc::scoped_refptr<MediaStreamInterface> stream =
2908 remote_streams_->find(stream_id);
2909 if (!stream) {
2910 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2911 MediaStream::Create(stream_id));
2912 remote_streams_->AddStream(stream);
2913 added_streams->push_back(stream);
2914 }
2915 media_streams.push_back(stream);
2916 }
2917 // Special case: "a=msid" missing, use random stream ID.
2918 if (media_streams.empty() &&
2919 !(remote_description()->description()->msid_signaling() &
2920 cricket::kMsidSignalingMediaSection)) {
2921 if (!missing_msid_default_stream_) {
2922 missing_msid_default_stream_ = MediaStreamProxy::Create(
2923 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2924 added_streams->push_back(missing_msid_default_stream_);
2925 }
2926 media_streams.push_back(missing_msid_default_stream_);
2927 }
2928 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2929 receiver->streams();
2930 // SetStreams() will add/remove the receiver's track to/from the streams. This
2931 // differs from the spec - the spec uses an "addList" and "removeList" to
2932 // update the stream-track relationships in a later step. We do this earlier,
2933 // changing the order of things, but the end-result is the same.
2934 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2935 // instead. https://crbug.com/webrtc/9480
2936 receiver->SetStreams(media_streams);
2937 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2938}
2939
Steve Anton0f5400a2018-07-17 14:25:36 -07002940void PeerConnection::ProcessRemovalOfRemoteTrack(
2941 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2942 transceiver,
2943 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2944 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2945 RTC_DCHECK(transceiver->mid());
2946 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2947 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002948 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002949 transceiver->internal()->receiver_internal()->streams();
2950 // This will remove the remote track from the streams.
2951 transceiver->internal()->receiver_internal()->set_stream_ids({});
2952 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002953 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2954}
2955
2956void PeerConnection::RemoveRemoteStreamsIfEmpty(
2957 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2958 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2959 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2960 // streams, see if the stream was removed by checking if this was the last
2961 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002962 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002963 if (remote_stream->GetAudioTracks().empty() &&
2964 remote_stream->GetVideoTracks().empty()) {
2965 remote_streams_->RemoveStream(remote_stream);
2966 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002967 }
2968 }
2969}
2970
Steve Antondcc3c022017-12-22 16:02:54 -08002971RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2972 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002973 const SessionDescriptionInterface& new_session,
2974 const SessionDescriptionInterface* old_local_description,
2975 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002976 RTC_DCHECK(IsUnifiedPlan());
2977
Steve Anton7464fca2018-01-19 11:10:37 -08002978 const cricket::ContentGroup* bundle_group = nullptr;
2979 if (new_session.GetType() == SdpType::kOffer) {
2980 auto bundle_group_or_error =
2981 GetEarlyBundleGroup(*new_session.description());
2982 if (!bundle_group_or_error.ok()) {
2983 return bundle_group_or_error.MoveError();
2984 }
2985 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002986 }
Steve Antondcc3c022017-12-22 16:02:54 -08002987
Steve Antondcc3c022017-12-22 16:02:54 -08002988 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002989 for (size_t i = 0; i < new_contents.size(); ++i) {
2990 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002991 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002992 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002993 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2994 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002995 const cricket::ContentInfo* old_local_content = nullptr;
2996 if (old_local_description &&
2997 i < old_local_description->description()->contents().size()) {
2998 old_local_content =
2999 &old_local_description->description()->contents()[i];
3000 }
3001 const cricket::ContentInfo* old_remote_content = nullptr;
3002 if (old_remote_description &&
3003 i < old_remote_description->description()->contents().size()) {
3004 old_remote_content =
3005 &old_remote_description->description()->contents()[i];
3006 }
Steve Antondcc3c022017-12-22 16:02:54 -08003007 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003008 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3009 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003010 if (!transceiver_or_error.ok()) {
3011 return transceiver_or_error.MoveError();
3012 }
3013 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003014 RTCError error =
3015 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3016 if (!error.ok()) {
3017 return error;
3018 }
3019 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003020 if (GetDataMid() && new_content.name != *GetDataMid()) {
3021 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003022 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3023 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003024 continue;
3025 }
3026 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3027 if (!error.ok()) {
3028 return error;
3029 }
Steve Antondcc3c022017-12-22 16:02:54 -08003030 } else {
3031 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3032 "Unknown section type.");
3033 }
3034 }
3035
3036 return RTCError::OK();
3037}
3038
3039RTCError PeerConnection::UpdateTransceiverChannel(
3040 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3041 transceiver,
3042 const cricket::ContentInfo& content,
3043 const cricket::ContentGroup* bundle_group) {
3044 RTC_DCHECK(IsUnifiedPlan());
3045 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003046 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003047 if (content.rejected) {
3048 if (channel) {
3049 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003050 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003051 }
3052 } else {
3053 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003054 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003055 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003056 } else {
Steve Anton69470252018-02-09 11:43:08 -08003057 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003058 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003059 }
3060 if (!channel) {
3061 LOG_AND_RETURN_ERROR(
3062 RTCErrorType::INTERNAL_ERROR,
3063 "Failed to create channel for mid=" + content.name);
3064 }
3065 transceiver->internal()->SetChannel(channel);
3066 }
3067 }
3068 return RTCError::OK();
3069}
3070
Steve Antonfa2260d2017-12-28 16:38:23 -08003071RTCError PeerConnection::UpdateDataChannel(
3072 cricket::ContentSource source,
3073 const cricket::ContentInfo& content,
3074 const cricket::ContentGroup* bundle_group) {
3075 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003076 // If data channels are disabled, ignore this media section. CreateAnswer
3077 // will take care of rejecting it.
3078 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003079 }
3080 if (content.rejected) {
3081 DestroyDataChannel();
3082 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003083 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003084 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003085 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3086 "Failed to create data channel.");
3087 }
3088 }
3089 if (source == cricket::CS_REMOTE) {
3090 const MediaContentDescription* data_desc = content.media_description();
3091 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3092 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3093 }
3094 }
3095 }
3096 return RTCError::OK();
3097}
3098
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003099// This method will extract any send encodings that were sent by the remote
3100// connection. This is currently only relevant for Simulcast scenario (where
3101// the number of layers may be communicated by the server).
3102static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3103 const MediaContentDescription& desc) {
3104 if (!desc.HasSimulcast()) {
3105 return {};
3106 }
3107 std::vector<RtpEncodingParameters> result;
3108 const SimulcastDescription& simulcast = desc.simulcast_description();
3109
3110 // This is a remote description, the parameters we are after should appear
3111 // as receive streams.
3112 for (const auto& alternatives : simulcast.receive_layers()) {
3113 RTC_DCHECK(!alternatives.empty());
3114 // There is currently no way to specify or choose from alternatives.
3115 // We will always use the first alternative, which is the most preferred.
3116 const SimulcastLayer& layer = alternatives[0];
3117 RtpEncodingParameters parameters;
3118 parameters.rid = layer.rid;
3119 parameters.active = !layer.is_paused;
3120 result.push_back(parameters);
3121 }
3122
3123 return result;
3124}
3125
3126static RTCError UpdateSimulcastLayerStatusInSender(
3127 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003128 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003129 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003130 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003131 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003132
3133 // The simulcast envelope cannot be changed, only the status of the streams.
3134 // So we will iterate over the send encodings rather than the layers.
3135 for (RtpEncodingParameters& encoding : parameters.encodings) {
3136 auto iter = std::find_if(layers.begin(), layers.end(),
3137 [&encoding](const SimulcastLayer& layer) {
3138 return layer.rid == encoding.rid;
3139 });
3140 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003141 if (iter == layers.end()) {
3142 disabled_layers.push_back(encoding.rid);
3143 continue;
3144 }
3145
3146 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003147 }
3148
Amit Hilbuch619b2942019-02-26 15:55:19 -08003149 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003150 if (result.ok()) {
3151 result = sender->DisableEncodingLayers(disabled_layers);
3152 }
3153
3154 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003155}
3156
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003157static bool SimulcastIsRejected(
3158 const ContentInfo* local_content,
3159 const MediaContentDescription& answer_media_desc) {
3160 bool simulcast_offered = local_content &&
3161 local_content->media_description() &&
3162 local_content->media_description()->HasSimulcast();
3163 bool simulcast_answered = answer_media_desc.HasSimulcast();
3164 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3165 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3166 return simulcast_offered && (!simulcast_answered || !rids_supported);
3167}
3168
Amit Hilbuch2297d332019-02-19 12:49:22 -08003169static RTCError DisableSimulcastInSender(
3170 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003171 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003172 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003173 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003174 return RTCError::OK();
3175 }
3176
Amit Hilbuch2297d332019-02-19 12:49:22 -08003177 std::vector<std::string> disabled_layers;
3178 std::transform(
3179 parameters.encodings.begin() + 1, parameters.encodings.end(),
3180 std::back_inserter(disabled_layers),
3181 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3182 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003183}
3184
Steve Antondcc3c022017-12-22 16:02:54 -08003185RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3186PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003187 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003188 size_t mline_index,
3189 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003190 const ContentInfo* old_local_content,
3191 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003192 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003193 // If this is an offer then the m= section might be recycled. If the m=
3194 // section is being recycled (defined as: rejected in the current local or
3195 // remote description and not rejected in new description), dissociate the
3196 // currently associated RtpTransceiver by setting its mid property to null,
3197 // and discard the mapping between the transceiver and its m= section index.
3198 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3199 old_remote_content)) {
3200 // We want to dissociate the transceiver that has the rejected mid.
3201 const std::string& old_mid =
3202 (old_local_content && old_local_content->rejected)
3203 ? old_local_content->name
3204 : old_remote_content->name;
3205 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003206 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003207 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3208 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003209 old_transceiver->internal()->set_mid(absl::nullopt);
3210 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003211 }
3212 }
3213 const MediaContentDescription* media_desc = content.media_description();
3214 auto transceiver = GetAssociatedTransceiver(content.name);
3215 if (source == cricket::CS_LOCAL) {
3216 // Find the RtpTransceiver that corresponds to this m= section, using the
3217 // mapping between transceivers and m= section indices established when
3218 // creating the offer.
3219 if (!transceiver) {
3220 transceiver = GetTransceiverByMLineIndex(mline_index);
3221 }
3222 if (!transceiver) {
3223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3224 "Unknown transceiver");
3225 }
3226 } else {
3227 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3228 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3229 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003230 // When simulcast is requested, a transceiver cannot be associated because
3231 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003232 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003233 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3234 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003235 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3236 }
3237 // If no RtpTransceiver was found in the previous step, create one with a
3238 // recvonly direction.
3239 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003240 RTC_LOG(LS_INFO) << "Adding "
3241 << cricket::MediaTypeToString(media_desc->type())
3242 << " transceiver for MID=" << content.name
3243 << " at i=" << mline_index
3244 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003245 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003246 std::vector<RtpEncodingParameters> send_encodings =
3247 GetSendEncodingsFromRemoteDescription(*media_desc);
3248 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3249 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003250 std::string receiver_id;
3251 if (!media_desc->streams().empty()) {
3252 receiver_id = media_desc->streams()[0].id;
3253 } else {
3254 receiver_id = rtc::CreateRandomUuid();
3255 }
3256 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003257 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003258 transceiver->internal()->set_direction(
3259 RtpTransceiverDirection::kRecvOnly);
3260 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003261
3262 // Check if the offer indicated simulcast but the answer rejected it.
3263 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003264 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003265 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003266 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003267 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003268 if (!error.ok()) {
3269 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3270 return std::move(error);
3271 }
3272 }
Steve Antondcc3c022017-12-22 16:02:54 -08003273 }
3274 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003275 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003276 LOG_AND_RETURN_ERROR(
3277 RTCErrorType::INVALID_PARAMETER,
3278 "Transceiver type does not match media description type.");
3279 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003280 if (media_desc->HasSimulcast()) {
3281 std::vector<SimulcastLayer> layers =
3282 source == cricket::CS_LOCAL
3283 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3284 : media_desc->simulcast_description()
3285 .receive_layers()
3286 .GetAllLayers();
3287 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003288 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003289 if (!error.ok()) {
3290 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3291 return std::move(error);
3292 }
3293 }
Steve Antondcc3c022017-12-22 16:02:54 -08003294 // Associate the found or created RtpTransceiver with the m= section by
3295 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3296 // section, and establish a mapping between the transceiver and the index of
3297 // the m= section.
3298 transceiver->internal()->set_mid(content.name);
3299 transceiver->internal()->set_mline_index(mline_index);
3300 return std::move(transceiver);
3301}
3302
3303rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3304PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3305 RTC_DCHECK(IsUnifiedPlan());
3306 for (auto transceiver : transceivers_) {
3307 if (transceiver->mid() == mid) {
3308 return transceiver;
3309 }
3310 }
3311 return nullptr;
3312}
3313
3314rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3315PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3316 RTC_DCHECK(IsUnifiedPlan());
3317 for (auto transceiver : transceivers_) {
3318 if (transceiver->internal()->mline_index() == mline_index) {
3319 return transceiver;
3320 }
3321 }
3322 return nullptr;
3323}
3324
3325rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3326PeerConnection::FindAvailableTransceiverToReceive(
3327 cricket::MediaType media_type) const {
3328 RTC_DCHECK(IsUnifiedPlan());
3329 // From JSEP section 5.10 (Applying a Remote Description):
3330 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3331 // the same type that were added to the PeerConnection by addTrack and are not
3332 // associated with any m= section and are not stopped, find the first such
3333 // RtpTransceiver.
3334 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003335 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003336 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3337 !transceiver->stopped()) {
3338 return transceiver;
3339 }
3340 }
3341 return nullptr;
3342}
3343
Steve Antoned10bd92017-12-05 10:52:59 -08003344const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3345 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3346 transceiver,
3347 const SessionDescriptionInterface* sdesc) const {
3348 RTC_DCHECK(transceiver);
3349 RTC_DCHECK(sdesc);
3350 if (IsUnifiedPlan()) {
3351 if (!transceiver->internal()->mid()) {
3352 // This transceiver is not associated with a media section yet.
3353 return nullptr;
3354 }
3355 return sdesc->description()->GetContentByName(
3356 *transceiver->internal()->mid());
3357 } else {
3358 // Plan B only allows at most one audio and one video section, so use the
3359 // first media section of that type.
3360 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003361 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003362 }
3363}
3364
deadbeef46c73892016-11-16 19:42:04 -08003365PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003366 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003367 return configuration_;
3368}
3369
deadbeef293e9262017-01-11 12:28:30 -08003370bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3371 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003372 RTC_DCHECK_RUN_ON(signaling_thread());
3373 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003374 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003375 if (IsClosed()) {
3376 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3377 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3378 }
3379
Qingsi Wanga2d60672018-04-11 16:57:45 -07003380 // According to JSEP, after setLocalDescription, changing the candidate pool
3381 // size is not allowed, and changing the set of ICE servers will not result
3382 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003383 if (local_description() && configuration.ice_candidate_pool_size !=
3384 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003385 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3386 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003387 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003388 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003389
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003390 if (local_description() &&
3391 configuration.use_media_transport != configuration_.use_media_transport) {
3392 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3393 "SetLocalDescription.";
3394 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3395 }
3396
3397 if (remote_description() &&
3398 configuration.use_media_transport != configuration_.use_media_transport) {
3399 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3400 "SetRemoteDescription.";
3401 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3402 }
3403
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003404 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003405 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 SetLocalDescription.";
3409 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3410 }
3411
3412 if (remote_description() &&
3413 configuration.use_media_transport_for_data_channels !=
3414 configuration_.use_media_transport_for_data_channels) {
3415 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3416 "after calling SetRemoteDescription.";
3417 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3418 }
3419
3420 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003421 configuration.crypto_options != configuration_.crypto_options) {
3422 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3423 "SetLocalDescription.";
3424 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3425 }
3426
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003427 if (configuration.use_media_transport_for_data_channels ||
3428 configuration.use_media_transport) {
3429 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3430 << "Media transport requires MaxBundle policy.";
3431 }
3432
deadbeef293e9262017-01-11 12:28:30 -08003433 // The simplest (and most future-compatible) way to tell if the config was
3434 // modified in an invalid way is to copy each property we do support
3435 // modifying, then use operator==. There are far more properties we don't
3436 // support modifying than those we do, and more could be added.
3437 RTCConfiguration modified_config = configuration_;
3438 modified_config.servers = configuration.servers;
3439 modified_config.type = configuration.type;
3440 modified_config.ice_candidate_pool_size =
3441 configuration.ice_candidate_pool_size;
3442 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003443 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003444 modified_config.ice_check_interval_strong_connectivity =
3445 configuration.ice_check_interval_strong_connectivity;
3446 modified_config.ice_check_interval_weak_connectivity =
3447 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003448 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3449 modified_config.ice_unwritable_min_checks =
3450 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003451 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003452 modified_config.stun_candidate_keepalive_interval =
3453 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003454 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003455 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003456 modified_config.active_reset_srtp_params =
3457 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003458 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003459 modified_config.use_media_transport_for_data_channels =
3460 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003461 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003462 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003463 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3464 }
3465
Steve Anton038834f2017-07-14 15:59:59 -07003466 // Validate the modified configuration.
3467 RTCError validate_error = ValidateConfiguration(modified_config);
3468 if (!validate_error.ok()) {
3469 return SafeSetError(std::move(validate_error), error);
3470 }
3471
deadbeef293e9262017-01-11 12:28:30 -08003472 // Note that this isn't possible through chromium, since it's an unsigned
3473 // short in WebIDL.
3474 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003475 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003476 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3477 }
3478
3479 // Parse ICE servers before hopping to network thread.
3480 cricket::ServerAddresses stun_servers;
3481 std::vector<cricket::RelayServerConfig> turn_servers;
3482 RTCErrorType parse_error =
3483 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3484 if (parse_error != RTCErrorType::NONE) {
3485 return SafeSetError(parse_error, error);
3486 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003487 // Note if STUN or TURN servers were supplied.
3488 if (!stun_servers.empty()) {
3489 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3490 }
3491 if (!turn_servers.empty()) {
3492 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3493 }
deadbeef293e9262017-01-11 12:28:30 -08003494
3495 // In theory this shouldn't fail.
3496 if (!network_thread()->Invoke<bool>(
3497 RTC_FROM_HERE,
3498 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3499 stun_servers, turn_servers, modified_config.type,
3500 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003501 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003502 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003503 modified_config.stun_candidate_keepalive_interval,
3504 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003505 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003506 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3507 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003508
deadbeefd1a38b52016-12-10 13:15:33 -08003509 // As described in JSEP, calling setConfiguration with new ICE servers or
3510 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3511 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003512 if (modified_config.servers != configuration_.servers ||
3513 modified_config.type != configuration_.type ||
3514 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003515 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003516 }
skvladd1f5fda2017-02-03 16:54:05 -08003517
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003518 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003519 transport_controller_->SetMediaTransportSettings(
3520 modified_config.use_media_transport,
3521 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003522
Zhi Huangb57e1692018-06-12 11:41:11 -07003523 if (configuration_.active_reset_srtp_params !=
3524 modified_config.active_reset_srtp_params) {
3525 transport_controller_->SetActiveResetSrtpParams(
3526 modified_config.active_reset_srtp_params);
3527 }
3528
deadbeef293e9262017-01-11 12:28:30 -08003529 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003530 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003531 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003532}
3533
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534bool PeerConnection::AddIceCandidate(
3535 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003536 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003537 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003538 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003539 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003540 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003541 return false;
3542 }
Steve Antond25da372017-11-06 14:50:29 -08003543
3544 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003545 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003546 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003547 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003548 return false;
3549 }
3550
3551 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003552 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003553 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003554 return false;
3555 }
3556
3557 bool valid = false;
3558 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3559 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003560 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003561 return false;
3562 }
3563
3564 // Add this candidate to the remote session description.
3565 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003566 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003567 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003568 return false;
3569 }
3570
3571 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003572 bool result = UseCandidate(ice_candidate);
3573 if (result) {
3574 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003575 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3576 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3577 }
3578 if (ice_candidate->candidate().address().IsPrivateIP()) {
3579 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3580 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003581 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3582 } else {
3583 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3584 }
3585 return result;
Steve Antond25da372017-11-06 14:50:29 -08003586 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003587 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003588 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003589 return true;
3590 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003591}
3592
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003593bool PeerConnection::RemoveIceCandidates(
3594 const std::vector<cricket::Candidate>& candidates) {
3595 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003596 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003597 if (IsClosed()) {
3598 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3599 return false;
3600 }
3601
Steve Antond25da372017-11-06 14:50:29 -08003602 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003603 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3604 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003605 return false;
3606 }
3607
3608 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003609 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003610 return false;
3611 }
3612
3613 size_t number_removed =
3614 mutable_remote_description()->RemoveCandidates(candidates);
3615 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003616 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003617 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003618 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003619 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003620 }
3621
3622 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003623 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3624 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003625 RTC_LOG(LS_ERROR)
3626 << "RemoveIceCandidates: Error when removing remote candidates: "
3627 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003628 }
3629 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003630}
3631
Niels Möller0c4f7be2018-05-07 14:01:37 +02003632RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003633 if (!worker_thread()->IsCurrent()) {
3634 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003635 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003636 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003637 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003638
Niels Möller0c4f7be2018-05-07 14:01:37 +02003639 const bool has_min = bitrate.min_bitrate_bps.has_value();
3640 const bool has_start = bitrate.start_bitrate_bps.has_value();
3641 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003642 if (has_min && *bitrate.min_bitrate_bps < 0) {
3643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3644 "min_bitrate_bps <= 0");
3645 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003646 if (has_start) {
3647 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003649 "start_bitrate_bps < min_bitrate_bps");
3650 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3652 "curent_bitrate_bps < 0");
3653 }
3654 }
3655 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003656 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003657 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003658 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003659 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3661 "max_bitrate_bps < min_bitrate_bps");
3662 } else if (*bitrate.max_bitrate_bps < 0) {
3663 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3664 "max_bitrate_bps < 0");
3665 }
3666 }
3667
zstein4b979802017-06-02 14:37:37 -07003668 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003669 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003670
3671 return RTCError::OK();
3672}
3673
Alex Narest78609d52017-10-20 10:37:47 +02003674void PeerConnection::SetBitrateAllocationStrategy(
3675 std::unique_ptr<rtc::BitrateAllocationStrategy>
3676 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003677 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003678 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3679 // move-capture values in lambdas.
3680 struct Task {
3681 PeerConnection* const pc;
3682 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3683 void operator()() {
3684 RTC_DCHECK_RUN_ON(pc->worker_thread());
3685 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3686 }
3687 };
3688 worker_thread()->Invoke<void>(
3689 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003690 return;
3691 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003692 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003693 RTC_DCHECK(call_.get());
3694 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3695}
3696
henrika5f6bf242017-11-01 11:06:56 +01003697void PeerConnection::SetAudioPlayout(bool playout) {
3698 if (!worker_thread()->IsCurrent()) {
3699 worker_thread()->Invoke<void>(
3700 RTC_FROM_HERE,
3701 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3702 return;
3703 }
3704 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003705 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003706 audio_state->SetPlayout(playout);
3707}
3708
3709void PeerConnection::SetAudioRecording(bool recording) {
3710 if (!worker_thread()->IsCurrent()) {
3711 worker_thread()->Invoke<void>(
3712 RTC_FROM_HERE,
3713 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3714 return;
3715 }
3716 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003717 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003718 audio_state->SetRecording(recording);
3719}
3720
Steve Anton8c0f7a72017-10-03 10:03:10 -07003721std::unique_ptr<rtc::SSLCertificate>
3722PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003723 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3724 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003725 return nullptr;
3726 }
Steve Antonf25303e2018-10-16 15:23:31 -07003727 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003728}
3729
Zhi Huang70b820f2018-01-27 14:16:15 -08003730std::unique_ptr<rtc::SSLCertChain>
3731PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003732 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003733 auto audio_transceiver = GetFirstAudioTransceiver();
3734 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003735 return nullptr;
3736 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003737 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003738 audio_transceiver->internal()->channel()->transport_name());
3739}
3740
3741rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3742PeerConnection::GetFirstAudioTransceiver() const {
3743 for (auto transceiver : transceivers_) {
3744 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3745 return transceiver;
3746 }
3747 }
3748 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003749}
3750
ivoc14d5dbe2016-07-04 07:06:55 -07003751bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3752 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003753 // TODO(eladalon): It would be better to not allow negative values into PC.
3754 const size_t max_size = (max_size_bytes < 0)
3755 ? RtcEventLog::kUnlimitedOutput
3756 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003757 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3758 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3759 output_period_ms = 5000;
3760 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003761 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003762 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003763 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003764}
3765
Bjorn Tereliusde939432017-11-20 17:38:14 +01003766bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3767 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003768 // TODO(eladalon): In C++14, this can be done with a lambda.
3769 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003770 bool operator()() {
3771 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3772 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003773 PeerConnection* const pc;
3774 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003775 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003776 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003777 return worker_thread()->Invoke<bool>(
3778 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003779}
3780
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003781bool PeerConnection::StartRtcEventLog(
3782 std::unique_ptr<RtcEventLogOutput> output) {
3783 return StartRtcEventLog(std::move(output),
3784 webrtc::RtcEventLog::kImmediateOutput);
3785}
3786
ivoc14d5dbe2016-07-04 07:06:55 -07003787void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003788 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003789 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3790}
3791
Harald Alvestrandad88c882018-11-28 16:47:46 +01003792rtc::scoped_refptr<DtlsTransportInterface>
3793PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003794 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003795 return transport_controller_->LookupDtlsTransportByMid(mid);
3796}
3797
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003798rtc::scoped_refptr<DtlsTransport>
3799PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003800 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003801 return transport_controller_->LookupDtlsTransportByMid(mid);
3802}
3803
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003804rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3805 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003806 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003807 return sctp_transport_;
3808}
3809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003810const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003811 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003812 return pending_local_description_ ? pending_local_description_.get()
3813 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003814}
3815
3816const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003817 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003818 return pending_remote_description_ ? pending_remote_description_.get()
3819 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003820}
3821
deadbeeffe4a8a42016-12-20 17:56:17 -08003822const SessionDescriptionInterface* PeerConnection::current_local_description()
3823 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003824 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003825 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003826}
3827
3828const SessionDescriptionInterface* PeerConnection::current_remote_description()
3829 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003830 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003831 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003832}
3833
3834const SessionDescriptionInterface* PeerConnection::pending_local_description()
3835 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003836 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003837 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003838}
3839
3840const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3841 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003842 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003843 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003844}
3845
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003846void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003847 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003848 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003849 // Update stats here so that we have the most recent stats for tracks and
3850 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003851 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003852
Steve Anton75737c02017-11-06 10:37:17 -08003853 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003854 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003855
Mirko Bonadei739baf02019-01-27 17:29:42 +01003856 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003857 transceiver->Stop();
3858 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003859
3860 // Ensure that all asynchronous stats requests are completed before destroying
3861 // the transport controller below.
3862 if (stats_collector_) {
3863 stats_collector_->WaitForPendingRequest();
3864 }
3865
3866 // Don't destroy BaseChannels until after stats has been cleaned up so that
3867 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003868 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003869
Qingsi Wang93a84392018-01-30 17:13:09 -08003870 // The event log is used in the transport controller, which must be outlived
3871 // by the former. CreateOffer by the peer connection is implemented
3872 // asynchronously and if the peer connection is closed without resetting the
3873 // WebRTC session description factory, the session description factory would
3874 // call the transport controller.
3875 webrtc_session_desc_factory_.reset();
3876 transport_controller_.reset();
3877
deadbeef42a42632017-03-10 15:18:00 -08003878 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003879 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3880 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003881
Steve Anton978b8762017-09-29 12:15:02 -07003882 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003883 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003884 call_.reset();
3885 // The event log must outlive call (and any other object that uses it).
3886 event_log_.reset();
3887 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003888 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003889 // The .h file says that observer can be discarded after close() returns.
3890 // Make sure this is true.
3891 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003892}
3893
Steve Antonad182762018-09-05 20:22:40 +00003894void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003895 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003896 switch (msg->message_id) {
3897 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3898 SetSessionDescriptionMsg* param =
3899 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3900 param->observer->OnSuccess();
3901 delete param;
3902 break;
3903 }
3904 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3905 SetSessionDescriptionMsg* param =
3906 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3907 param->observer->OnFailure(std::move(param->error));
3908 delete param;
3909 break;
3910 }
3911 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3912 CreateSessionDescriptionMsg* param =
3913 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3914 param->observer->OnFailure(std::move(param->error));
3915 delete param;
3916 break;
3917 }
3918 case MSG_GETSTATS: {
3919 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3920 StatsReports reports;
3921 stats_->GetStats(param->track, &reports);
3922 param->observer->OnComplete(reports);
3923 delete param;
3924 break;
3925 }
3926 case MSG_FREE_DATACHANNELS: {
3927 sctp_data_channels_to_free_.clear();
3928 break;
3929 }
3930 case MSG_REPORT_USAGE_PATTERN: {
3931 ReportUsagePattern();
3932 break;
3933 }
3934 default:
3935 RTC_NOTREACHED() << "Not implemented";
3936 break;
3937 }
3938}
3939
Steve Antonafb0bb72018-02-20 11:35:37 -08003940cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3941 RTC_DCHECK(!IsUnifiedPlan());
3942 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3943 GetAudioTransceiver()->internal()->channel());
3944 if (voice_channel) {
3945 return voice_channel->media_channel();
3946 } else {
3947 return nullptr;
3948 }
3949}
3950
3951cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3952 RTC_DCHECK(!IsUnifiedPlan());
3953 auto* video_channel = static_cast<cricket::VideoChannel*>(
3954 GetVideoTransceiver()->internal()->channel());
3955 if (video_channel) {
3956 return video_channel->media_channel();
3957 } else {
3958 return nullptr;
3959 }
3960}
3961
Steve Anton4171afb2017-11-20 10:20:22 -08003962void PeerConnection::CreateAudioReceiver(
3963 MediaStreamInterface* stream,
3964 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003965 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3966 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003967 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3968 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003969 auto* audio_receiver = new AudioRtpReceiver(
3970 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003971 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003972 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3973 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3974 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003975 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003976 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003977 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003978}
3979
Steve Anton4171afb2017-11-20 10:20:22 -08003980void PeerConnection::CreateVideoReceiver(
3981 MediaStreamInterface* stream,
3982 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003983 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3984 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003985 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3986 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003987 auto* video_receiver = new VideoRtpReceiver(
3988 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003989 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003990 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3991 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3992 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003993 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003994 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003995 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003996}
3997
deadbeef70ab1a12015-09-28 16:53:55 -07003998// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3999// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004000rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004001 const RtpSenderInfo& remote_sender_info) {
4002 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4003 if (!receiver) {
4004 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4005 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004006 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004007 }
Steve Anton4171afb2017-11-20 10:20:22 -08004008 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4009 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4010 } else {
4011 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4012 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004013 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004014}
4015
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004016void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4017 MediaStreamInterface* stream) {
4018 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004019 RTC_DCHECK(track);
4020 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004021 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004022 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004023 // We already have a sender for this track, so just change the stream_id
4024 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004025 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004026 return;
4027 }
4028
4029 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004030 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004031 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004032 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004033 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 // If the sender has already been configured in SDP, we call SetSsrc,
4035 // which will connect the sender to the underlying transport. This can
4036 // occur if a local session description that contains the ID of the sender
4037 // is set before AddStream is called. It can also occur if the local
4038 // session description is not changed and RemoveStream is called, and
4039 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004040 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004041 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004042 if (sender_info) {
4043 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004044 }
4045}
4046
4047// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4048// indefinitely, when we have unified plan SDP.
4049void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4050 MediaStreamInterface* stream) {
4051 RTC_DCHECK(!IsClosed());
4052 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004053 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004054 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4055 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004056 return;
4057 }
Steve Anton4171afb2017-11-20 10:20:22 -08004058 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004059}
4060
4061void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4062 MediaStreamInterface* stream) {
4063 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004064 RTC_DCHECK(track);
4065 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004066 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004067 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004068 // We already have a sender for this track, so just change the stream_id
4069 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004070 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004071 return;
4072 }
4073
4074 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004075 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004076 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004077 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004078 GetVideoTransceiver()->internal()->AddSender(new_sender);
4079 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004080 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004081 if (sender_info) {
4082 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004083 }
4084}
4085
4086void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4087 MediaStreamInterface* stream) {
4088 RTC_DCHECK(!IsClosed());
4089 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004090 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004091 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4092 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004093 return;
4094 }
Steve Anton4171afb2017-11-20 10:20:22 -08004095 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004096}
4097
Steve Antonba818672017-11-06 10:21:57 -08004098void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004099 if (ice_connection_state_ == new_state) {
4100 return;
4101 }
4102
deadbeefcbecd352015-09-23 11:50:27 -07004103 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004104 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004105 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004106 return;
4107 }
Steve Antonba818672017-11-06 10:21:57 -08004108
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4110 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004111 RTC_DCHECK(ice_connection_state_ !=
4112 PeerConnectionInterface::kIceConnectionClosed);
4113
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004114 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004115 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004116}
4117
Alex Loiko9289eda2018-11-23 16:18:59 +00004118void PeerConnection::SetStandardizedIceConnectionState(
4119 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004120 if (standardized_ice_connection_state_ == new_state)
4121 return;
4122 if (IsClosed())
4123 return;
4124 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004125 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004126}
4127
Jonas Olsson635474e2018-10-18 15:58:17 +02004128void PeerConnection::SetConnectionState(
4129 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004130 if (connection_state_ == new_state)
4131 return;
4132 if (IsClosed())
4133 return;
4134 connection_state_ = new_state;
4135 Observer()->OnConnectionChange(new_state);
4136}
4137
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004138void PeerConnection::OnIceGatheringChange(
4139 PeerConnectionInterface::IceGatheringState new_state) {
4140 if (IsClosed()) {
4141 return;
4142 }
4143 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004144 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004145}
4146
jbauch81bf7b02017-03-25 08:31:12 -07004147void PeerConnection::OnIceCandidate(
4148 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004149 if (IsClosed()) {
4150 return;
4151 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004152 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004153 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4154 candidate->candidate().address().IsPrivateIP()) {
4155 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4156 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004157 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4158 candidate->candidate().address().IsUnresolvedIP()) {
4159 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4160 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004161 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004162}
4163
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004164void PeerConnection::OnIceCandidatesRemoved(
4165 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004166 if (IsClosed()) {
4167 return;
4168 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004169 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004170}
4171
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004172void PeerConnection::ChangeSignalingState(
4173 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004174 if (signaling_state_ == signaling_state) {
4175 return;
4176 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004177 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4178 << GetSignalingStateString(signaling_state_)
4179 << " New state: "
4180 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004181 signaling_state_ = signaling_state;
4182 if (signaling_state == kClosed) {
4183 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004184 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004185 standardized_ice_connection_state_ =
4186 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004187 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4188 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004189 if (ice_gathering_state_ != kIceGatheringComplete) {
4190 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004191 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004192 }
4193 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004194 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004195}
4196
deadbeefeb459812015-12-15 19:24:43 -08004197void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4198 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004199 if (IsClosed()) {
4200 return;
4201 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004202 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004203 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004204}
4205
deadbeefeb459812015-12-15 19:24:43 -08004206void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4207 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004208 if (IsClosed()) {
4209 return;
4210 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004211 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004212 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004213}
4214
4215void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4216 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004217 if (IsClosed()) {
4218 return;
4219 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004220 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004221 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004222}
4223
4224void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4225 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004226 if (IsClosed()) {
4227 return;
4228 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004229 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004230 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004231}
4232
Henrik Boström31638672017-11-23 17:48:32 +01004233void PeerConnection::PostSetSessionDescriptionSuccess(
4234 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004235 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4236 signaling_thread()->Post(RTC_FROM_HERE, this,
4237 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004238}
4239
deadbeefab9b2d12015-10-14 11:33:11 -07004240void PeerConnection::PostSetSessionDescriptionFailure(
4241 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004242 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004243 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004244 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4245 msg->error = std::move(error);
4246 signaling_thread()->Post(RTC_FROM_HERE, this,
4247 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004248}
4249
4250void PeerConnection::PostCreateSessionDescriptionFailure(
4251 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004252 RTCError error) {
4253 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004254 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4255 msg->error = std::move(error);
4256 signaling_thread()->Post(RTC_FROM_HERE, this,
4257 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004258}
4259
zhihuang1c378ed2017-08-17 14:10:50 -07004260void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004261 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004262 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004263 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004264
Steve Antondcc3c022017-12-22 16:02:54 -08004265 if (IsUnifiedPlan()) {
4266 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4267 } else {
4268 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4269 }
4270
Steve Antonfa2260d2017-12-28 16:38:23 -08004271 // Intentionally unset the data channel type for RTP data channel with the
4272 // second condition. Otherwise the RTP data channels would be successfully
4273 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4274 // when building with chromium. We want to leave RTP data channels broken, so
4275 // people won't try to use them.
4276 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4277 session_options->data_channel_type = data_channel_type();
4278 }
4279
Steve Antondcc3c022017-12-22 16:02:54 -08004280 // Apply ICE restart flag and renomination flag.
4281 for (auto& options : session_options->media_description_options) {
4282 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4283 options.transport_options.enable_ice_renomination =
4284 configuration_.enable_ice_renomination;
4285 }
4286
4287 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004288 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004289 session_options->pooled_ice_credentials =
4290 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4291 RTC_FROM_HERE,
4292 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4293 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004294 session_options->offer_extmap_allow_mixed =
4295 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004296
4297 if (configuration_.enable_dtls_srtp &&
4298 !configuration_.enable_dtls_srtp.value()) {
4299 session_options->media_transport_settings =
4300 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4301 }
Steve Antondcc3c022017-12-22 16:02:54 -08004302}
4303
4304void PeerConnection::GetOptionsForPlanBOffer(
4305 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4306 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004307 // Figure out transceiver directional preferences.
4308 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4309 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4310
4311 // By default, generate sendrecv/recvonly m= sections.
4312 bool recv_audio = true;
4313 bool recv_video = true;
4314
4315 // By default, only offer a new m= section if we have media to send with it.
4316 bool offer_new_audio_description = send_audio;
4317 bool offer_new_video_description = send_video;
4318 bool offer_new_data_description = HasDataChannels();
4319
4320 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004321 if (offer_answer_options.offer_to_receive_audio !=
4322 RTCOfferAnswerOptions::kUndefined) {
4323 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004324 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004325 offer_new_audio_description ||
4326 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004327 }
Steve Antondcc3c022017-12-22 16:02:54 -08004328 if (offer_answer_options.offer_to_receive_video !=
4329 RTCOfferAnswerOptions::kUndefined) {
4330 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004331 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004332 offer_new_video_description ||
4333 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004334 }
4335
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004336 absl::optional<size_t> audio_index;
4337 absl::optional<size_t> video_index;
4338 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004339 // If a current description exists, generate m= sections in the same order,
4340 // using the first audio/video/data section that appears and rejecting
4341 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004342 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004343 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004344 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004345 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4346 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4347 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004348 }
4349
zhihuang1c378ed2017-08-17 14:10:50 -07004350 // Add audio/video/data m= sections to the end if needed.
4351 if (!audio_index && offer_new_audio_description) {
4352 session_options->media_description_options.push_back(
4353 cricket::MediaDescriptionOptions(
4354 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004355 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4356 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004357 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004358 }
zhihuang1c378ed2017-08-17 14:10:50 -07004359 if (!video_index && offer_new_video_description) {
4360 session_options->media_description_options.push_back(
4361 cricket::MediaDescriptionOptions(
4362 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004363 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4364 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004365 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004366 }
zhihuang1c378ed2017-08-17 14:10:50 -07004367 if (!data_index && offer_new_data_description) {
4368 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004369 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004370 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004371 }
4372
4373 cricket::MediaDescriptionOptions* audio_media_description_options =
4374 !audio_index ? nullptr
4375 : &session_options->media_description_options[*audio_index];
4376 cricket::MediaDescriptionOptions* video_media_description_options =
4377 !video_index ? nullptr
4378 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004379
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004380 AddPlanBRtpSenderOptions(GetSendersInternal(),
4381 audio_media_description_options,
4382 video_media_description_options,
4383 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004384}
4385
Steve Antondcc3c022017-12-22 16:02:54 -08004386static cricket::MediaDescriptionOptions
4387GetMediaDescriptionOptionsForTransceiver(
4388 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4389 transceiver,
4390 const std::string& mid) {
4391 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004392 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004393 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004394 media_description_options.codec_preferences =
4395 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004396 // This behavior is specified in JSEP. The gist is that:
4397 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4398 // sendrecv.
4399 // 2. If the MSID is included, then it must be included in any subsequent
4400 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004401 if (transceiver->stopped() ||
4402 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4403 !transceiver->internal()->has_ever_been_used_to_send())) {
4404 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004405 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004406
4407 cricket::SenderOptions sender_options;
4408 sender_options.track_id = transceiver->sender()->id();
4409 sender_options.stream_ids = transceiver->sender()->stream_ids();
4410
4411 // The following sets up RIDs and Simulcast.
4412 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004413 RtpParameters send_parameters =
4414 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004415 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4416 send_parameters.encodings.end(),
4417 [](const RtpEncodingParameters& encoding) {
4418 return !encoding.rid.empty();
4419 });
4420
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004421 std::vector<RidDescription> send_rids;
4422 SimulcastLayerList send_layers;
4423 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4424 if (encoding.rid.empty()) {
4425 continue;
4426 }
4427 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4428 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4429 }
4430
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004431 if (has_rids) {
4432 sender_options.rids = send_rids;
4433 }
4434
4435 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004436 // When RIDs are configured, we must set num_sim_layers to 0 to.
4437 // Otherwise, num_sim_layers must be 1 because either there is no
4438 // simulcast, or simulcast is acheived by munging the SDP.
4439 sender_options.num_sim_layers = has_rids ? 0 : 1;
4440 media_description_options.sender_options.push_back(sender_options);
4441
Steve Antondcc3c022017-12-22 16:02:54 -08004442 return media_description_options;
4443}
4444
Steve Anton5c72e712018-12-10 14:25:30 -08004445// Returns the ContentInfo at mline index |i|, or null if none exists.
4446static const ContentInfo* GetContentByIndex(
4447 const SessionDescriptionInterface* sdesc,
4448 size_t i) {
4449 if (!sdesc) {
4450 return nullptr;
4451 }
4452 const ContentInfos& contents = sdesc->description()->contents();
4453 return (i < contents.size() ? &contents[i] : nullptr);
4454}
4455
Steve Antondcc3c022017-12-22 16:02:54 -08004456void PeerConnection::GetOptionsForUnifiedPlanOffer(
4457 const RTCOfferAnswerOptions& offer_answer_options,
4458 cricket::MediaSessionOptions* session_options) {
4459 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4460 // Offers) and 5.2.2 (Subsequent Offers).
4461 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4462 const ContentInfos& local_contents =
4463 (local_description() ? local_description()->description()->contents()
4464 : ContentInfos());
4465 const ContentInfos& remote_contents =
4466 (remote_description() ? remote_description()->description()->contents()
4467 : ContentInfos());
4468 // The mline indices that can be recycled. New transceivers should reuse these
4469 // slots first.
4470 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004471 // First, go through each media section that exists in either the local or
4472 // remote description and generate a media section in this offer for the
4473 // associated transceiver. If a media section can be recycled, generate a
4474 // default, rejected media section here that can be later overwritten.
4475 for (size_t i = 0;
4476 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4477 // Either |local_content| or |remote_content| is non-null.
4478 const ContentInfo* local_content =
4479 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004480 const ContentInfo* current_local_content =
4481 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004482 const ContentInfo* remote_content =
4483 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004484 const ContentInfo* current_remote_content =
4485 GetContentByIndex(current_remote_description(), i);
4486 bool had_been_rejected =
4487 (current_local_content && current_local_content->rejected) ||
4488 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004489 const std::string& mid =
4490 (local_content ? local_content->name : remote_content->name);
4491 cricket::MediaType media_type =
4492 (local_content ? local_content->media_description()->type()
4493 : remote_content->media_description()->type());
4494 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4495 media_type == cricket::MEDIA_TYPE_VIDEO) {
4496 auto transceiver = GetAssociatedTransceiver(mid);
4497 RTC_CHECK(transceiver);
4498 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004499 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004500 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004501 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004502 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4503 RtpTransceiverDirection::kInactive,
4504 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004505 recycleable_mline_indices.push(i);
4506 } else {
4507 session_options->media_description_options.push_back(
4508 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4509 // CreateOffer shouldn't really cause any state changes in
4510 // PeerConnection, but we need a way to match new transceivers to new
4511 // media sections in SetLocalDescription and JSEP specifies this is done
4512 // by recording the index of the media section generated for the
4513 // transceiver in the offer.
4514 transceiver->internal()->set_mline_index(i);
4515 }
4516 } else {
4517 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004518 RTC_CHECK(GetDataMid());
4519 if (had_been_rejected || mid != *GetDataMid()) {
4520 session_options->media_description_options.push_back(
4521 GetMediaDescriptionOptionsForRejectedData(mid));
4522 } else {
4523 session_options->media_description_options.push_back(
4524 GetMediaDescriptionOptionsForActiveData(mid));
4525 }
Steve Antondcc3c022017-12-22 16:02:54 -08004526 }
4527 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004528
Steve Antondcc3c022017-12-22 16:02:54 -08004529 // Next, look for transceivers that are newly added (that is, are not stopped
4530 // and not associated). Reuse media sections marked as recyclable first,
4531 // otherwise append to the end of the offer. New media sections should be
4532 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004533 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004534 if (transceiver->mid() || transceiver->stopped()) {
4535 continue;
4536 }
4537 size_t mline_index;
4538 if (!recycleable_mline_indices.empty()) {
4539 mline_index = recycleable_mline_indices.front();
4540 recycleable_mline_indices.pop();
4541 session_options->media_description_options[mline_index] =
4542 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004543 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004544 } else {
4545 mline_index = session_options->media_description_options.size();
4546 session_options->media_description_options.push_back(
4547 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004548 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004549 }
4550 // See comment above for why CreateOffer changes the transceiver's state.
4551 transceiver->internal()->set_mline_index(mline_index);
4552 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004553 // Lastly, add a m-section if we have local data channels and an m section
4554 // does not already exist.
4555 if (!GetDataMid() && HasDataChannels()) {
4556 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004557 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004558 }
Steve Antondcc3c022017-12-22 16:02:54 -08004559}
4560
4561void PeerConnection::GetOptionsForAnswer(
4562 const RTCOfferAnswerOptions& offer_answer_options,
4563 cricket::MediaSessionOptions* session_options) {
4564 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4565
4566 if (IsUnifiedPlan()) {
4567 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4568 } else {
4569 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4570 }
4571
Steve Antonfa2260d2017-12-28 16:38:23 -08004572 // Intentionally unset the data channel type for RTP data channel. Otherwise
4573 // the RTP data channels would be successfully negotiated by default and the
4574 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4575 // We want to leave RTP data channels broken, so people won't try to use them.
4576 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4577 session_options->data_channel_type = data_channel_type();
4578 }
4579
Steve Antondcc3c022017-12-22 16:02:54 -08004580 // Apply ICE renomination flag.
4581 for (auto& options : session_options->media_description_options) {
4582 options.transport_options.enable_ice_renomination =
4583 configuration_.enable_ice_renomination;
4584 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004585
4586 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004587 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004588 session_options->pooled_ice_credentials =
4589 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4590 RTC_FROM_HERE,
4591 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4592 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004593}
4594
Steve Antondcc3c022017-12-22 16:02:54 -08004595void PeerConnection::GetOptionsForPlanBAnswer(
4596 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004597 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004598 // Figure out transceiver directional preferences.
4599 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4600 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4601
4602 // By default, generate sendrecv/recvonly m= sections. The direction is also
4603 // restricted by the direction in the offer.
4604 bool recv_audio = true;
4605 bool recv_video = true;
4606
4607 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004608 if (offer_answer_options.offer_to_receive_audio !=
4609 RTCOfferAnswerOptions::kUndefined) {
4610 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004611 }
Steve Antondcc3c022017-12-22 16:02:54 -08004612 if (offer_answer_options.offer_to_receive_video !=
4613 RTCOfferAnswerOptions::kUndefined) {
4614 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004615 }
4616
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004617 absl::optional<size_t> audio_index;
4618 absl::optional<size_t> video_index;
4619 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004620
4621 // Generate m= sections that match those in the offer.
4622 // Note that mediasession.cc will handle intersection our preferred
4623 // direction with the offered direction.
4624 GenerateMediaDescriptionOptions(
4625 remote_description(),
4626 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4627 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4628 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004629
4630 cricket::MediaDescriptionOptions* audio_media_description_options =
4631 !audio_index ? nullptr
4632 : &session_options->media_description_options[*audio_index];
4633 cricket::MediaDescriptionOptions* video_media_description_options =
4634 !video_index ? nullptr
4635 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004636
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004637 AddPlanBRtpSenderOptions(GetSendersInternal(),
4638 audio_media_description_options,
4639 video_media_description_options,
4640 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004641}
zhihuangaf388472016-11-02 16:49:48 -07004642
Steve Antondcc3c022017-12-22 16:02:54 -08004643void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4644 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4645 cricket::MediaSessionOptions* session_options) {
4646 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4647 // Answers) and 5.3.2 (Subsequent Answers).
4648 RTC_DCHECK(remote_description());
4649 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4650 for (const ContentInfo& content :
4651 remote_description()->description()->contents()) {
4652 cricket::MediaType media_type = content.media_description()->type();
4653 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4654 media_type == cricket::MEDIA_TYPE_VIDEO) {
4655 auto transceiver = GetAssociatedTransceiver(content.name);
4656 RTC_CHECK(transceiver);
4657 session_options->media_description_options.push_back(
4658 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4659 } else {
4660 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004661 // Reject all data sections if data channels are disabled.
4662 // Reject a data section if it has already been rejected.
4663 // Reject all data sections except for the first one.
4664 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4665 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004666 session_options->media_description_options.push_back(
4667 GetMediaDescriptionOptionsForRejectedData(content.name));
4668 } else {
4669 session_options->media_description_options.push_back(
4670 GetMediaDescriptionOptionsForActiveData(content.name));
4671 }
Steve Antondcc3c022017-12-22 16:02:54 -08004672 }
4673 }
htaa2a49d92016-03-04 02:51:39 -08004674}
4675
zhihuang1c378ed2017-08-17 14:10:50 -07004676void PeerConnection::GenerateMediaDescriptionOptions(
4677 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004678 RtpTransceiverDirection audio_direction,
4679 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004680 absl::optional<size_t>* audio_index,
4681 absl::optional<size_t>* video_index,
4682 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004683 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004684 for (const cricket::ContentInfo& content :
4685 session_desc->description()->contents()) {
4686 if (IsAudioContent(&content)) {
4687 // If we already have an audio m= section, reject this extra one.
4688 if (*audio_index) {
4689 session_options->media_description_options.push_back(
4690 cricket::MediaDescriptionOptions(
4691 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004692 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004693 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004694 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004695 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004696 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4697 content.name, audio_direction,
4698 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004699 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004700 }
4701 } else if (IsVideoContent(&content)) {
4702 // If we already have an video m= section, reject this extra one.
4703 if (*video_index) {
4704 session_options->media_description_options.push_back(
4705 cricket::MediaDescriptionOptions(
4706 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004707 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004708 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004709 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004710 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004711 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4712 content.name, video_direction,
4713 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004714 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004715 }
4716 } else {
4717 RTC_DCHECK(IsDataContent(&content));
4718 // If we already have an data m= section, reject this extra one.
4719 if (*data_index) {
4720 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004721 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004722 } else {
4723 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004724 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004725 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004726 }
4727 }
htaa2a49d92016-03-04 02:51:39 -08004728 }
deadbeefab9b2d12015-10-14 11:33:11 -07004729}
4730
Steve Antonfa2260d2017-12-28 16:38:23 -08004731cricket::MediaDescriptionOptions
4732PeerConnection::GetMediaDescriptionOptionsForActiveData(
4733 const std::string& mid) const {
4734 // Direction for data sections is meaningless, but legacy endpoints might
4735 // expect sendrecv.
4736 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4737 RtpTransceiverDirection::kSendRecv,
4738 /*stopped=*/false);
4739 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4740 return options;
4741}
4742
4743cricket::MediaDescriptionOptions
4744PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4745 const std::string& mid) const {
4746 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4747 RtpTransceiverDirection::kInactive,
4748 /*stopped=*/true);
4749 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4750 return options;
4751}
4752
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004753absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004754 switch (data_channel_type_) {
4755 case cricket::DCT_RTP:
4756 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004757 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004758 }
4759 return rtp_data_channel_->content_name();
4760 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004761 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004762 case cricket::DCT_MEDIA_TRANSPORT:
4763 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004764 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004765 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004766 }
4767}
4768
Steve Anton4171afb2017-11-20 10:20:22 -08004769void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4770 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4771 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004772 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004773}
4774
Steve Anton4171afb2017-11-20 10:20:22 -08004775void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004776 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004777 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004778 cricket::MediaType media_type,
4779 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004780 RTC_DCHECK(!IsUnifiedPlan());
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782 std::vector<RtpSenderInfo>* current_senders =
4783 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004784
Steve Anton4171afb2017-11-20 10:20:22 -08004785 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004786 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004787 for (auto sender_it = current_senders->begin();
4788 sender_it != current_senders->end();
4789 /* incremented manually */) {
4790 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004791 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004792 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004793 std::string params_stream_id;
4794 if (params) {
4795 params_stream_id =
4796 (!params->first_stream_id().empty() ? params->first_stream_id()
4797 : kDefaultStreamId);
4798 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004799 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004800 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004801 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004802 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004803 sender_exists) {
4804 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004805 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004806 OnRemoteSenderRemoved(info, media_type);
4807 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004808 }
4809 }
4810
Steve Anton4171afb2017-11-20 10:20:22 -08004811 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004812 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004813 if (!params.has_ssrcs()) {
4814 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4815 // sender, this means it is coming from a Unified Plan endpoint,so we just
4816 // create a default.
4817 default_sender_needed = true;
4818 break;
4819 }
4820
Seth Hampson845e8782018-03-02 11:34:10 -08004821 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004822 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004823 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4824 // not supported in Plan B, we just take the first here and create the
4825 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004826 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004827 (!params.first_stream_id().empty() ? params.first_stream_id()
4828 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004829 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004830 uint32_t ssrc = params.first_ssrc();
4831
4832 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004833 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004834 if (!stream) {
4835 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004836 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004837 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004838 remote_streams_->AddStream(stream);
4839 new_streams->AddStream(stream);
4840 }
4841
Steve Anton4171afb2017-11-20 10:20:22 -08004842 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004843 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004844 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004845 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004846 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004847 }
4848 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004849
Steve Anton4171afb2017-11-20 10:20:22 -08004850 // Add default sender if necessary.
4851 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004852 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004853 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004854 if (!default_stream) {
4855 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004856 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004857 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004858 remote_streams_->AddStream(default_stream);
4859 new_streams->AddStream(default_stream);
4860 }
Steve Anton4171afb2017-11-20 10:20:22 -08004861 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4862 ? kDefaultAudioSenderId
4863 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004864 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004865 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004866 if (!default_sender_info) {
4867 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004868 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004869 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004870 }
4871 }
deadbeefab9b2d12015-10-14 11:33:11 -07004872}
4873
Steve Anton4171afb2017-11-20 10:20:22 -08004874void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4875 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004876 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4877 << " receiver for track_id=" << sender_info.sender_id
4878 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004879
Steve Anton3d954a62018-04-02 11:27:23 -07004880 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004881 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004882 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004883 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004884 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004885 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004886 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004887 }
4888}
4889
Steve Anton4171afb2017-11-20 10:20:22 -08004890void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4891 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004892 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4893 << " receiver for track_id=" << sender_info.sender_id
4894 << " and stream_id=" << sender_info.stream_id;
4895
Seth Hampson845e8782018-03-02 11:34:10 -08004896 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004897
Henrik Boström933d8b02017-10-10 10:05:16 -07004898 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004899 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004900 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4901 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004902 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004903 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004904 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004905 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004906 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004907 }
4908 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004909 // Stopping or destroying a VideoRtpReceiver will end the
4910 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004911 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004912 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004913 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004914 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004915 // There's no guarantee the track is still available, e.g. the track may
4916 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004917 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004918 }
4919 } else {
nisseede5da42017-01-12 05:15:36 -08004920 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004921 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004922 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004923 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004924 }
deadbeefab9b2d12015-10-14 11:33:11 -07004925}
4926
4927void PeerConnection::UpdateEndedRemoteMediaStreams() {
4928 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4929 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4930 MediaStreamInterface* stream = remote_streams_->at(i);
4931 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4932 streams_to_remove.push_back(stream);
4933 }
4934 }
4935
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004936 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004937 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004938 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004939 }
4940}
4941
Steve Anton4171afb2017-11-20 10:20:22 -08004942void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004943 const std::vector<cricket::StreamParams>& streams,
4944 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004945 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004946
Seth Hampson845e8782018-03-02 11:34:10 -08004947 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004948 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004949 for (auto sender_it = current_senders->begin();
4950 sender_it != current_senders->end();
4951 /* incremented manually */) {
4952 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004953 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004954 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4955 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004956 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004957 OnLocalSenderRemoved(info, media_type);
4958 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004959 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004960 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004961 }
4962 }
4963
Steve Anton4171afb2017-11-20 10:20:22 -08004964 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004965 for (const cricket::StreamParams& params : streams) {
4966 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004967 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004968 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004969 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004970 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004971 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004972 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004973 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004974 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004975 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004976 }
4977 }
4978}
4979
Steve Anton4171afb2017-11-20 10:20:22 -08004980void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4981 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004982 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004983 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004984 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004985 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4986 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004987 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004988 return;
4989 }
4990
deadbeeffac06552015-11-25 11:26:01 -08004991 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004992 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004993 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004994 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004995 }
deadbeeffac06552015-11-25 11:26:01 -08004996
Seth Hampson5b4f0752018-04-02 16:31:36 -07004997 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004998 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004999}
5000
Steve Anton4171afb2017-11-20 10:20:22 -08005001void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5002 cricket::MediaType media_type) {
5003 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005004 if (!sender) {
5005 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005006 // SessionDescriptions has been renegotiated.
5007 return;
5008 }
deadbeeffac06552015-11-25 11:26:01 -08005009
5010 // A sender has been removed from the SessionDescription but it's still
5011 // associated with the PeerConnection. This only occurs if the SDP doesn't
5012 // match with the calls to CreateSender, AddStream and RemoveStream.
5013 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005014 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005015 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005016 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005017 }
deadbeeffac06552015-11-25 11:26:01 -08005018
Steve Anton4171afb2017-11-20 10:20:22 -08005019 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005020}
5021
5022void PeerConnection::UpdateLocalRtpDataChannels(
5023 const cricket::StreamParamsVec& streams) {
5024 std::vector<std::string> existing_channels;
5025
5026 // Find new and active data channels.
5027 for (const cricket::StreamParams& params : streams) {
5028 // |it->sync_label| is actually the data channel label. The reason is that
5029 // we use the same naming of data channels as we do for
5030 // MediaStreams and Tracks.
5031 // For MediaStreams, the sync_label is the MediaStream label and the
5032 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005033 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005034 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005035 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005037 continue;
5038 }
5039 // Set the SSRC the data channel should use for sending.
5040 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5041 existing_channels.push_back(data_channel_it->first);
5042 }
5043
5044 UpdateClosingRtpDataChannels(existing_channels, true);
5045}
5046
5047void PeerConnection::UpdateRemoteRtpDataChannels(
5048 const cricket::StreamParamsVec& streams) {
5049 std::vector<std::string> existing_channels;
5050
5051 // Find new and active data channels.
5052 for (const cricket::StreamParams& params : streams) {
5053 // The data channel label is either the mslabel or the SSRC if the mslabel
5054 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005055 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005056 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005057 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005058 auto data_channel_it = rtp_data_channels_.find(label);
5059 if (data_channel_it == rtp_data_channels_.end()) {
5060 // This is a new data channel.
5061 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5062 } else {
5063 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5064 }
5065 existing_channels.push_back(label);
5066 }
5067
5068 UpdateClosingRtpDataChannels(existing_channels, false);
5069}
5070
5071void PeerConnection::UpdateClosingRtpDataChannels(
5072 const std::vector<std::string>& active_channels,
5073 bool is_local_update) {
5074 auto it = rtp_data_channels_.begin();
5075 while (it != rtp_data_channels_.end()) {
5076 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005077 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005078 ++it;
5079 continue;
5080 }
5081
5082 if (is_local_update) {
5083 data_channel->SetSendSsrc(0);
5084 } else {
5085 data_channel->RemotePeerRequestClose();
5086 }
5087
5088 if (data_channel->state() == DataChannel::kClosed) {
5089 rtp_data_channels_.erase(it);
5090 it = rtp_data_channels_.begin();
5091 } else {
5092 ++it;
5093 }
5094 }
5095}
5096
5097void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5098 uint32_t remote_ssrc) {
5099 rtc::scoped_refptr<DataChannel> channel(
5100 InternalCreateDataChannel(label, nullptr));
5101 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005102 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005103 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005104 return;
5105 }
5106 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005107 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5108 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005109 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005110}
5111
5112rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5113 const std::string& label,
5114 const InternalDataChannelInit* config) {
5115 if (IsClosed()) {
5116 return nullptr;
5117 }
Steve Anton75737c02017-11-06 10:37:17 -08005118 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005119 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005120 << "InternalCreateDataChannel: Data is not supported in this call.";
5121 return nullptr;
5122 }
5123 InternalDataChannelInit new_config =
5124 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005125 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005126 if (new_config.id < 0) {
5127 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005128 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005129 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005130 RTC_LOG(LS_ERROR)
5131 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005132 return nullptr;
5133 }
5134 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005135 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005136 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005137 return nullptr;
5138 }
5139 }
5140
Steve Anton75737c02017-11-06 10:37:17 -08005141 rtc::scoped_refptr<DataChannel> channel(
5142 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005143 if (!channel) {
5144 sid_allocator_.ReleaseSid(new_config.id);
5145 return nullptr;
5146 }
5147
5148 if (channel->data_channel_type() == cricket::DCT_RTP) {
5149 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005150 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5151 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005152 return nullptr;
5153 }
5154 rtp_data_channels_[channel->label()] = channel;
5155 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005156 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005157 sctp_data_channels_.push_back(channel);
5158 channel->SignalClosed.connect(this,
5159 &PeerConnection::OnSctpDataChannelClosed);
5160 }
5161
Steve Anton2d8609c2018-01-23 16:38:46 -08005162 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005163 return channel;
5164}
5165
5166bool PeerConnection::HasDataChannels() const {
5167 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5168}
5169
5170void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005171 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005172 for (const auto& channel : sctp_data_channels_) {
5173 if (channel->id() < 0) {
5174 int sid;
5175 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005176 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5177 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005178 continue;
5179 }
5180 channel->SetSctpSid(sid);
5181 }
5182 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005183 // Since closing modifies the list of channels, we have to do the actual
5184 // closing outside the loop.
5185 for (const auto& channel : channels_to_close) {
5186 channel->CloseAbruptly();
5187 }
deadbeefab9b2d12015-10-14 11:33:11 -07005188}
5189
5190void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005191 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005192 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5193 ++it) {
5194 if (it->get() == channel) {
5195 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005196 // After the closing procedure is done, it's safe to use this ID for
5197 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005198 sid_allocator_.ReleaseSid(channel->id());
5199 }
deadbeefbd292462015-12-14 18:15:29 -08005200 // Since this method is triggered by a signal from the DataChannel,
5201 // we can't free it directly here; we need to free it asynchronously.
5202 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005203 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005204 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5205 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005206 return;
5207 }
5208 }
5209}
5210
deadbeefab9b2d12015-10-14 11:33:11 -07005211void PeerConnection::OnDataChannelDestroyed() {
5212 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5213 // DataChannel may callback to us and try to modify the list.
5214 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5215 temp_rtp_dcs.swap(rtp_data_channels_);
5216 for (const auto& kv : temp_rtp_dcs) {
5217 kv.second->OnTransportChannelDestroyed();
5218 }
5219
5220 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5221 temp_sctp_dcs.swap(sctp_data_channels_);
5222 for (const auto& channel : temp_sctp_dcs) {
5223 channel->OnTransportChannelDestroyed();
5224 }
5225}
5226
5227void PeerConnection::OnDataChannelOpenMessage(
5228 const std::string& label,
5229 const InternalDataChannelInit& config) {
5230 rtc::scoped_refptr<DataChannel> channel(
5231 InternalCreateDataChannel(label, &config));
5232 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005233 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005234 return;
5235 }
5236
deadbeefa601f5c2016-06-06 14:27:39 -07005237 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5238 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005239 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005240 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005241}
5242
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005243bool PeerConnection::HandleOpenMessage_s(
5244 const cricket::ReceiveDataParams& params,
5245 const rtc::CopyOnWriteBuffer& buffer) {
5246 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5247 // Received OPEN message; parse and signal that a new data channel should
5248 // be created.
5249 std::string label;
5250 InternalDataChannelInit config;
5251 config.id = params.ssrc;
5252 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5253 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5254 << params.ssrc;
5255 return true;
5256 }
5257 config.open_handshake_role = InternalDataChannelInit::kAcker;
5258 OnDataChannelOpenMessage(label, config);
5259 return true;
5260 }
5261 return false;
5262}
5263
Steve Anton4171afb2017-11-20 10:20:22 -08005264rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5265PeerConnection::GetAudioTransceiver() const {
5266 // This method only works with Plan B SDP, where there is a single
5267 // audio/video transceiver.
5268 RTC_DCHECK(!IsUnifiedPlan());
5269 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005270 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005271 return transceiver;
5272 }
5273 }
5274 RTC_NOTREACHED();
5275 return nullptr;
5276}
5277
5278rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5279PeerConnection::GetVideoTransceiver() const {
5280 // This method only works with Plan B SDP, where there is a single
5281 // audio/video transceiver.
5282 RTC_DCHECK(!IsUnifiedPlan());
5283 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005284 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005285 return transceiver;
5286 }
5287 }
5288 RTC_NOTREACHED();
5289 return nullptr;
5290}
5291
5292// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5293// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005294bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005295 switch (type) {
5296 case cricket::MEDIA_TYPE_AUDIO:
5297 return !GetAudioTransceiver()->internal()->senders().empty();
5298 case cricket::MEDIA_TYPE_VIDEO:
5299 return !GetVideoTransceiver()->internal()->senders().empty();
5300 case cricket::MEDIA_TYPE_DATA:
5301 return false;
5302 }
5303 RTC_NOTREACHED();
5304 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005305}
5306
Steve Anton4171afb2017-11-20 10:20:22 -08005307rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5308PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005309 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005310 for (auto sender : transceiver->internal()->senders()) {
5311 if (sender->track() == track) {
5312 return sender;
5313 }
5314 }
5315 }
5316 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005317}
5318
Steve Anton4171afb2017-11-20 10:20:22 -08005319rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5320PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005321 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005322 for (auto sender : transceiver->internal()->senders()) {
5323 if (sender->id() == sender_id) {
5324 return sender;
5325 }
5326 }
5327 }
5328 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005329}
5330
Steve Anton4171afb2017-11-20 10:20:22 -08005331rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5332PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005333 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005334 for (auto receiver : transceiver->internal()->receivers()) {
5335 if (receiver->id() == receiver_id) {
5336 return receiver;
5337 }
5338 }
5339 }
5340 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005341}
5342
Steve Anton4171afb2017-11-20 10:20:22 -08005343std::vector<PeerConnection::RtpSenderInfo>*
5344PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5345 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5346 media_type == cricket::MEDIA_TYPE_VIDEO);
5347 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5348 ? &remote_audio_sender_infos_
5349 : &remote_video_sender_infos_;
5350}
5351
5352std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005353 cricket::MediaType media_type) {
5354 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5355 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005356 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5357 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005358}
5359
Steve Anton4171afb2017-11-20 10:20:22 -08005360const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5361 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005362 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005363 const std::string sender_id) const {
5364 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005365 if (sender_info.stream_id == stream_id &&
5366 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005367 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005368 }
5369 }
5370 return nullptr;
5371}
5372
5373DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5374 for (const auto& channel : sctp_data_channels_) {
5375 if (channel->id() == sid) {
5376 return channel;
5377 }
5378 }
5379 return nullptr;
5380}
5381
Karl Wibergfb3be392019-03-22 14:13:22 +01005382PeerConnection::InitializePortAllocatorResult
5383PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005384 const cricket::ServerAddresses& stun_servers,
5385 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005386 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005387 RTC_DCHECK_RUN_ON(network_thread());
5388
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005389 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005390 // To handle both internal and externally created port allocator, we will
5391 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005392 int port_allocator_flags = port_allocator_->flags();
5393 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5394 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5395 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005396 // If the disable-IPv6 flag was specified, we'll not override it
5397 // by experiment.
5398 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005399 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005400 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5401 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005402 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403 }
5404
zhihuangb09b3f92017-03-07 14:40:51 -08005405 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005406 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005407 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005408 }
5409
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005410 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005411 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005412 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005413 }
5414
honghaiz60347052016-05-31 18:29:12 -07005415 if (configuration.candidate_network_policy ==
5416 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005417 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005418 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005419 }
5420
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005421 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005422 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005423 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5424 }
5425
Karl Wibergfb3be392019-03-22 14:13:22 +01005426 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005427 // No step delay is used while allocating ports.
5428 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005429 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005430 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005431 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005432
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005433 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005434 for (auto& turn_server : turn_servers_copy) {
5435 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005436 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005437 // Call this last since it may create pooled allocator sessions using the
5438 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005439 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005440 stun_servers, std::move(turn_servers_copy),
5441 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5442 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005443 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005444
5445 InitializePortAllocatorResult res;
5446 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5447 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005448}
5449
deadbeef91dd5672016-05-18 16:55:30 -07005450bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005451 const cricket::ServerAddresses& stun_servers,
5452 const std::vector<cricket::RelayServerConfig>& turn_servers,
5453 IceTransportsType type,
5454 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005455 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005456 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005457 absl::optional<int> stun_candidate_keepalive_interval,
5458 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005459 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005460 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005461 // According to JSEP, after setLocalDescription, changing the candidate pool
5462 // size is not allowed, and changing the set of ICE servers will not result
5463 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005464 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005465 port_allocator_->FreezeCandidatePool();
5466 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005467 // Add the custom tls turn servers if they exist.
5468 auto turn_servers_copy = turn_servers;
5469 for (auto& turn_server : turn_servers_copy) {
5470 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5471 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005472 // Call this last since it may create pooled allocator sessions using the
5473 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005474 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005475 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5476 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005477}
5478
Steve Antonba818672017-11-06 10:21:57 -08005479cricket::ChannelManager* PeerConnection::channel_manager() const {
5480 return factory_->channel_manager();
5481}
5482
Elad Alon99c3fe52017-10-13 16:29:40 +02005483bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005484 std::unique_ptr<RtcEventLogOutput> output,
5485 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005486 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005487 if (!event_log_) {
5488 return false;
5489 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005490 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005491}
5492
5493void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005494 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005495 if (event_log_) {
5496 event_log_->StopLogging();
5497 }
ivoc14d5dbe2016-07-04 07:06:55 -07005498}
nisseeaabdf62017-05-05 02:23:02 -07005499
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005500cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005501 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005502 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005503 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005504 if (channel && channel->content_name() == content_name) {
5505 return channel;
5506 }
Steve Anton75737c02017-11-06 10:37:17 -08005507 }
5508 if (rtp_data_channel() &&
5509 rtp_data_channel()->content_name() == content_name) {
5510 return rtp_data_channel();
5511 }
5512 return nullptr;
5513}
5514
5515bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005516 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005517 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005518 RTC_LOG(LS_INFO)
5519 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005520 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005521 return false;
5522 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005523 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005524 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005525 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005526 return false;
5527 }
5528
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005529 absl::optional<rtc::SSLRole> dtls_role;
5530 if (sctp_mid_) {
5531 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5532 } else if (is_caller_) {
5533 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5534 }
Zhi Huange830e682018-03-30 10:48:35 -07005535 if (dtls_role) {
5536 *role = *dtls_role;
5537 return true;
5538 }
5539 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005540}
5541
5542bool PeerConnection::GetSslRole(const std::string& content_name,
5543 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005544 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005545 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005546 RTC_LOG(LS_INFO)
5547 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005548 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005549 return false;
5550 }
5551
Zhi Huange830e682018-03-30 10:48:35 -07005552 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5553 if (dtls_role) {
5554 *role = *dtls_role;
5555 return true;
5556 }
5557 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005558}
5559
Steve Antonf8470812017-12-04 10:46:21 -08005560void PeerConnection::SetSessionError(SessionError error,
5561 const std::string& error_desc) {
5562 RTC_DCHECK_RUN_ON(signaling_thread());
5563 if (error != session_error_) {
5564 session_error_ = error;
5565 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005566 }
5567}
5568
Zhi Huange830e682018-03-30 10:48:35 -07005569RTCError PeerConnection::UpdateSessionState(
5570 SdpType type,
5571 cricket::ContentSource source,
5572 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005573 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005574
5575 // If there's already a pending error then no state transition should happen.
5576 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005577 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005578
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005579 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005580 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005581 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005582 }
5583
5584 // Update the signaling state according to the specified state machine (see
5585 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005586 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005587 ChangeSignalingState(source == cricket::CS_LOCAL
5588 ? PeerConnectionInterface::kHaveLocalOffer
5589 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005590 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005591 ChangeSignalingState(source == cricket::CS_LOCAL
5592 ? PeerConnectionInterface::kHaveLocalPrAnswer
5593 : PeerConnectionInterface::kHaveRemotePrAnswer);
5594 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005595 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005596 ChangeSignalingState(PeerConnectionInterface::kStable);
5597 }
5598
5599 // Update internal objects according to the session description's media
5600 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005601 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005602 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005603 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005604 }
5605
Steve Anton8a006912017-12-04 15:25:56 -08005606 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005607}
5608
Steve Anton8a006912017-12-04 15:25:56 -08005609RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005610 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005611 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005612 const SessionDescriptionInterface* sdesc =
5613 (source == cricket::CS_LOCAL ? local_description()
5614 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005615 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005616
5617 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005618 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005619 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005620 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005621 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005622 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005623 continue;
5624 }
5625 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005626 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005627 if (!content_desc) {
5628 continue;
5629 }
5630 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005631 bool success = (source == cricket::CS_LOCAL)
5632 ? channel->SetLocalContent(content_desc, type, &error)
5633 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005634 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005635 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005636 }
5637 }
5638
5639 // If using the RtpDataChannel, push down the new SDP section for it too.
5640 if (rtp_data_channel_) {
5641 const ContentInfo* data_content =
5642 cricket::GetFirstDataContent(sdesc->description());
5643 if (data_content && !data_content->rejected) {
5644 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005645 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005646 if (data_desc) {
5647 std::string error;
5648 bool success =
5649 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005650 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005651 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005652 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005653 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005654 }
Steve Anton75737c02017-11-06 10:37:17 -08005655 }
5656 }
5657 }
Steve Antoned10bd92017-12-05 10:52:59 -08005658
Steve Anton75737c02017-11-06 10:37:17 -08005659 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5660 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5661 if (sctp_transport_ && local_description() && remote_description() &&
5662 cricket::GetFirstDataContent(local_description()->description()) &&
5663 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005664 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005665 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005666 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5667 GetSctpPort(local_description()->description()),
5668 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005669 if (!success) {
5670 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5671 "Failed to push down SCTP parameters.");
5672 }
Steve Anton75737c02017-11-06 10:37:17 -08005673 }
Steve Antoned10bd92017-12-05 10:52:59 -08005674
Steve Anton8a006912017-12-04 15:25:56 -08005675 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005676}
5677
Karl Wiberg739506e2019-04-03 11:37:28 +02005678bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5679 int local_sctp_port,
5680 int remote_sctp_port) {
5681 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005682 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5683 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005684 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005685}
5686
Steve Anton8a006912017-12-04 15:25:56 -08005687RTCError PeerConnection::PushdownTransportDescription(
5688 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005689 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005690 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005691
Zhi Huange830e682018-03-30 10:48:35 -07005692 if (source == cricket::CS_LOCAL) {
5693 const SessionDescriptionInterface* sdesc = local_description();
5694 RTC_DCHECK(sdesc);
5695 return transport_controller_->SetLocalDescription(type,
5696 sdesc->description());
5697 } else {
5698 const SessionDescriptionInterface* sdesc = remote_description();
5699 RTC_DCHECK(sdesc);
5700 return transport_controller_->SetRemoteDescription(type,
5701 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005702 }
Steve Anton75737c02017-11-06 10:37:17 -08005703}
5704
5705bool PeerConnection::GetTransportDescription(
5706 const SessionDescription* description,
5707 const std::string& content_name,
5708 cricket::TransportDescription* tdesc) {
5709 if (!description || !tdesc) {
5710 return false;
5711 }
5712 const TransportInfo* transport_info =
5713 description->GetTransportInfoByName(content_name);
5714 if (!transport_info) {
5715 return false;
5716 }
5717 *tdesc = transport_info->description;
5718 return true;
5719}
5720
Steve Anton75737c02017-11-06 10:37:17 -08005721cricket::IceConfig PeerConnection::ParseIceConfig(
5722 const PeerConnectionInterface::RTCConfiguration& config) const {
5723 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005724 switch (config.continual_gathering_policy) {
5725 case PeerConnectionInterface::GATHER_ONCE:
5726 gathering_policy = cricket::GATHER_ONCE;
5727 break;
5728 case PeerConnectionInterface::GATHER_CONTINUALLY:
5729 gathering_policy = cricket::GATHER_CONTINUALLY;
5730 break;
5731 default:
5732 RTC_NOTREACHED();
5733 gathering_policy = cricket::GATHER_ONCE;
5734 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005735
Steve Anton75737c02017-11-06 10:37:17 -08005736 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005737 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5738 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005739 ice_config.prioritize_most_likely_candidate_pairs =
5740 config.prioritize_most_likely_ice_candidate_pairs;
5741 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005742 RTCConfigurationToIceConfigOptionalInt(
5743 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005744 ice_config.continual_gathering_policy = gathering_policy;
5745 ice_config.presume_writable_when_fully_relayed =
5746 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005747 ice_config.ice_check_interval_strong_connectivity =
5748 config.ice_check_interval_strong_connectivity;
5749 ice_config.ice_check_interval_weak_connectivity =
5750 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005751 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005752 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5753 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005754 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005755 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005756 ice_config.regather_all_networks_interval_range =
5757 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005758 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005759 return ice_config;
5760}
5761
Steve Anton75737c02017-11-06 10:37:17 -08005762bool PeerConnection::SendData(const cricket::SendDataParams& params,
5763 const rtc::CopyOnWriteBuffer& payload,
5764 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005765 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005766 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5767 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5768 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005769 return false;
5770 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005771 if (media_transport_) {
5772 SendDataParams send_params;
5773 send_params.type = ToWebrtcDataMessageType(params.type);
5774 send_params.ordered = params.ordered;
5775 if (params.max_rtx_count >= 0) {
5776 send_params.max_rtx_count = params.max_rtx_count;
5777 } else if (params.max_rtx_ms >= 0) {
5778 send_params.max_rtx_ms = params.max_rtx_ms;
5779 }
5780 return media_transport_->SendData(params.sid, send_params, payload).ok();
5781 }
Steve Anton75737c02017-11-06 10:37:17 -08005782 return rtp_data_channel_
5783 ? rtp_data_channel_->SendData(params, payload, result)
5784 : network_thread()->Invoke<bool>(
5785 RTC_FROM_HERE,
5786 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005787 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005788}
5789
5790bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005791 RTC_DCHECK_RUN_ON(signaling_thread());
5792 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005793 // Don't log an error here, because DataChannels are expected to call
5794 // ConnectDataChannel in this state. It's the only way to initially tell
5795 // whether or not the underlying transport is ready.
5796 return false;
5797 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005798 if (media_transport_) {
5799 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5800 &DataChannel::OnChannelReady);
5801 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5802 &DataChannel::OnDataReceived);
5803 SignalMediaTransportChannelClosing_s.connect(
5804 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5805 SignalMediaTransportChannelClosed_s.connect(
5806 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5807 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005808 rtp_data_channel_->SignalReadyToSendData.connect(
5809 webrtc_data_channel, &DataChannel::OnChannelReady);
5810 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5811 &DataChannel::OnDataReceived);
5812 } else {
5813 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5814 &DataChannel::OnChannelReady);
5815 SignalSctpDataReceived.connect(webrtc_data_channel,
5816 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005817 SignalSctpClosingProcedureStartedRemotely.connect(
5818 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5819 SignalSctpClosingProcedureComplete.connect(
5820 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005821 }
5822 return true;
5823}
5824
5825void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005826 RTC_DCHECK_RUN_ON(signaling_thread());
5827 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005828 RTC_LOG(LS_ERROR)
5829 << "DisconnectDataChannel called when rtp_data_channel_ and "
5830 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005831 return;
5832 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005833 if (media_transport_) {
5834 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5835 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5836 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5837 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5838 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005839 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5840 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5841 } else {
5842 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5843 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005844 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5845 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005846 }
5847}
5848
5849void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005850 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005851 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005852 return;
5853 }
Steve Anton75737c02017-11-06 10:37:17 -08005854 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005855 RTC_LOG(LS_ERROR)
5856 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005857 return;
5858 }
5859 network_thread()->Invoke<void>(
5860 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005861 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005862}
5863
5864void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005865 if (media_transport_) {
5866 media_transport_->CloseChannel(sid);
5867 return;
5868 }
Steve Anton75737c02017-11-06 10:37:17 -08005869 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005870 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005871 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005872 return;
5873 }
5874 network_thread()->Invoke<void>(
5875 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005876 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005877}
5878
5879bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005880 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005881 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005882 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005883 sctp_ready_to_send_data_;
5884}
5885
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005886void PeerConnection::OnDataReceived(int channel_id,
5887 DataMessageType type,
5888 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005889 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005890 cricket::ReceiveDataParams params;
5891 params.sid = channel_id;
5892 params.type = ToCricketDataMessageType(type);
5893 media_transport_invoker_->AsyncInvoke<void>(
5894 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5895 RTC_DCHECK_RUN_ON(signaling_thread());
5896 if (!HandleOpenMessage_s(params, buffer)) {
5897 SignalMediaTransportReceivedData_s(params, buffer);
5898 }
5899 });
5900}
5901
5902void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005903 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005904 media_transport_invoker_->AsyncInvoke<void>(
5905 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5906 RTC_DCHECK_RUN_ON(signaling_thread());
5907 SignalMediaTransportChannelClosing_s(channel_id);
5908 });
5909}
5910
5911void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005912 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005913 media_transport_invoker_->AsyncInvoke<void>(
5914 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5915 RTC_DCHECK_RUN_ON(signaling_thread());
5916 SignalMediaTransportChannelClosed_s(channel_id);
5917 });
5918}
5919
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005920absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005921 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005922 if (sctp_mid_ && transport_controller_) {
5923 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5924 if (dtls_transport) {
5925 return dtls_transport->transport_name();
5926 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005927 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005928 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005929 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005930}
5931
Qingsi Wang72a43a12018-02-20 16:03:18 -08005932cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5933 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005934 network_thread()->Invoke<void>(
5935 RTC_FROM_HERE,
5936 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5937 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005938 return candidate_states_list;
5939}
5940
Steve Anton5dfde182018-02-06 10:34:40 -08005941std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5942 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005943 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005944 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005945 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005946 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005947 if (channel) {
5948 transport_names_by_mid[channel->content_name()] =
5949 channel->transport_name();
5950 }
Steve Anton75737c02017-11-06 10:37:17 -08005951 }
Steve Anton5dfde182018-02-06 10:34:40 -08005952 if (rtp_data_channel_) {
5953 transport_names_by_mid[rtp_data_channel_->content_name()] =
5954 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005955 }
5956 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005957 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005958 RTC_DCHECK(transport_name);
5959 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005960 }
Steve Anton5dfde182018-02-06 10:34:40 -08005961 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005962}
5963
Steve Anton5dfde182018-02-06 10:34:40 -08005964std::map<std::string, cricket::TransportStats>
5965PeerConnection::GetTransportStatsByNames(
5966 const std::set<std::string>& transport_names) {
5967 if (!network_thread()->IsCurrent()) {
5968 return network_thread()
5969 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5970 RTC_FROM_HERE,
5971 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005972 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005973 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005974 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5975 for (const std::string& transport_name : transport_names) {
5976 cricket::TransportStats transport_stats;
5977 bool success =
5978 transport_controller_->GetStats(transport_name, &transport_stats);
5979 if (success) {
5980 transport_stats_by_name[transport_name] = std::move(transport_stats);
5981 } else {
5982 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5983 << transport_name;
5984 }
5985 }
5986 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005987}
5988
5989bool PeerConnection::GetLocalCertificate(
5990 const std::string& transport_name,
5991 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005992 if (!certificate) {
5993 return false;
5994 }
5995 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5996 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005997}
5998
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005999std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006000 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006001 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006002}
6003
6004cricket::DataChannelType PeerConnection::data_channel_type() const {
6005 return data_channel_type_;
6006}
6007
6008bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006009 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006010 return pending_ice_restarts_.find(content_name) !=
6011 pending_ice_restarts_.end();
6012}
6013
Steve Anton75737c02017-11-06 10:37:17 -08006014bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6015 return transport_controller_->NeedsIceRestart(content_name);
6016}
6017
6018void PeerConnection::OnCertificateReady(
6019 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6020 transport_controller_->SetLocalCertificate(certificate);
6021}
6022
6023void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006024 SetSessionError(SessionError::kTransport,
6025 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006026}
6027
Alex Loiko9289eda2018-11-23 16:18:59 +00006028void PeerConnection::OnTransportControllerConnectionState(
6029 cricket::IceConnectionState state) {
6030 switch (state) {
6031 case cricket::kIceConnectionConnecting:
6032 // If the current state is Connected or Completed, then there were
6033 // writable channels but now there are not, so the next state must
6034 // be Disconnected.
6035 // kIceConnectionConnecting is currently used as the default,
6036 // un-connected state by the TransportController, so its only use is
6037 // detecting disconnections.
6038 if (ice_connection_state_ ==
6039 PeerConnectionInterface::kIceConnectionConnected ||
6040 ice_connection_state_ ==
6041 PeerConnectionInterface::kIceConnectionCompleted) {
6042 SetIceConnectionState(
6043 PeerConnectionInterface::kIceConnectionDisconnected);
6044 }
6045 break;
6046 case cricket::kIceConnectionFailed:
6047 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6048 break;
6049 case cricket::kIceConnectionConnected:
6050 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6051 "all transports are writable.";
6052 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6053 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6054 break;
6055 case cricket::kIceConnectionCompleted:
6056 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6057 "all transports are complete.";
6058 if (ice_connection_state_ !=
6059 PeerConnectionInterface::kIceConnectionConnected) {
6060 // If jumping directly from "checking" to "connected",
6061 // signal "connected" first.
6062 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6063 }
6064 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6065 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6066 ReportTransportStats();
6067 break;
6068 default:
6069 RTC_NOTREACHED();
6070 }
6071}
6072
Steve Anton75737c02017-11-06 10:37:17 -08006073void PeerConnection::OnTransportControllerCandidatesGathered(
6074 const std::string& transport_name,
6075 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006076 int sdp_mline_index;
6077 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006078 RTC_LOG(LS_ERROR)
6079 << "OnTransportControllerCandidatesGathered: content name "
6080 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006081 return;
6082 }
6083
6084 for (cricket::Candidates::const_iterator citer = candidates.begin();
6085 citer != candidates.end(); ++citer) {
6086 // Use transport_name as the candidate media id.
6087 std::unique_ptr<JsepIceCandidate> candidate(
6088 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6089 if (local_description()) {
6090 mutable_local_description()->AddCandidate(candidate.get());
6091 }
6092 OnIceCandidate(std::move(candidate));
6093 }
6094}
6095
6096void PeerConnection::OnTransportControllerCandidatesRemoved(
6097 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006098 // Sanity check.
6099 for (const cricket::Candidate& candidate : candidates) {
6100 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006101 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006102 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006103 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006104 return;
6105 }
6106 }
6107
6108 if (local_description()) {
6109 mutable_local_description()->RemoveCandidates(candidates);
6110 }
6111 OnIceCandidatesRemoved(candidates);
6112}
6113
6114void PeerConnection::OnTransportControllerDtlsHandshakeError(
6115 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006116 RTC_HISTOGRAM_ENUMERATION(
6117 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6118 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006119}
6120
Steve Antoned10bd92017-12-05 10:52:59 -08006121void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006122 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006123 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006124 if (channel && !channel->enabled()) {
6125 channel->Enable(true);
6126 }
Steve Anton75737c02017-11-06 10:37:17 -08006127 }
6128
Steve Anton4171afb2017-11-20 10:20:22 -08006129 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006130 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006131 }
Steve Anton75737c02017-11-06 10:37:17 -08006132}
6133
6134// Returns the media index for a local ice candidate given the content name.
6135bool PeerConnection::GetLocalCandidateMediaIndex(
6136 const std::string& content_name,
6137 int* sdp_mline_index) {
6138 if (!local_description() || !sdp_mline_index) {
6139 return false;
6140 }
6141
6142 bool content_found = false;
6143 const ContentInfos& contents = local_description()->description()->contents();
6144 for (size_t index = 0; index < contents.size(); ++index) {
6145 if (contents[index].name == content_name) {
6146 *sdp_mline_index = static_cast<int>(index);
6147 content_found = true;
6148 break;
6149 }
6150 }
6151 return content_found;
6152}
6153
6154bool PeerConnection::UseCandidatesInSessionDescription(
6155 const SessionDescriptionInterface* remote_desc) {
6156 if (!remote_desc) {
6157 return true;
6158 }
6159 bool ret = true;
6160
6161 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6162 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6163 for (size_t n = 0; n < candidates->count(); ++n) {
6164 const IceCandidateInterface* candidate = candidates->at(n);
6165 bool valid = false;
6166 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6167 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006168 RTC_LOG(LS_INFO)
6169 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006170 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006171 }
6172 continue;
6173 }
6174 ret = UseCandidate(candidate);
6175 if (!ret) {
6176 break;
6177 }
6178 }
6179 }
6180 return ret;
6181}
6182
6183bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6184 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6185 size_t remote_content_size =
6186 remote_description()->description()->contents().size();
6187 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006188 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006189 return false;
6190 }
6191
6192 cricket::ContentInfo content =
6193 remote_description()->description()->contents()[mediacontent_index];
6194 std::vector<cricket::Candidate> candidates;
6195 candidates.push_back(candidate->candidate());
6196 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006197 RTCError error =
6198 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006199 if (error.ok()) {
6200 // Candidates successfully submitted for checking.
6201 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6202 ice_connection_state_ ==
6203 PeerConnectionInterface::kIceConnectionDisconnected) {
6204 // If state is New, then the session has just gotten its first remote ICE
6205 // candidates, so go to Checking.
6206 // If state is Disconnected, the session is re-using old candidates or
6207 // receiving additional ones, so go to Checking.
6208 // If state is Connected, stay Connected.
6209 // TODO(bemasc): If state is Connected, and the new candidates are for a
6210 // newly added transport, then the state actually _should_ move to
6211 // checking. Add a way to distinguish that case.
6212 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6213 }
6214 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006215 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006216 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006217 }
6218 return true;
6219}
6220
6221void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006222 // Destroy video channel first since it may have a pointer to the
6223 // voice channel.
6224 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006225 if (!video_info || video_info->rejected) {
6226 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006227 }
6228
Steve Anton6fec8802017-12-04 10:37:29 -08006229 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6230 if (!audio_info || audio_info->rejected) {
6231 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
6233
6234 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6235 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006236 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006237 }
6238}
6239
Steve Antondcc3c022017-12-22 16:02:54 -08006240RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6241 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006242 const cricket::ContentGroup* bundle_group = nullptr;
6243 if (configuration_.bundle_policy ==
6244 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006245 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006246 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006247 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6248 "max-bundle configured but session description "
6249 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006250 }
6251 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006252 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006253}
6254
6255RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006256 // Creating the media channels. Transports should already have been created
6257 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006258 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006259 if (voice && !voice->rejected &&
6260 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006261 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006262 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006263 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6264 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006265 }
6266 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6267 }
6268
Steve Antondcc3c022017-12-22 16:02:54 -08006269 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006270 if (video && !video->rejected &&
6271 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006272 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006273 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006274 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6275 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006276 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006277 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006278 }
6279
Steve Antondcc3c022017-12-22 16:02:54 -08006280 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006281 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006282 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006283 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006284 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6285 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006286 }
6287 }
6288
Steve Anton8a006912017-12-04 15:25:56 -08006289 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006290}
6291
Steve Anton4171afb2017-11-20 10:20:22 -08006292// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006293cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006294 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006295 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006296 MediaTransportInterface* media_transport = nullptr;
6297 if (configuration_.use_media_transport) {
6298 media_transport = GetMediaTransport(mid);
6299 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006300
Steve Anton75737c02017-11-06 10:37:17 -08006301 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006302 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006303 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006304 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006305 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006306 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006307 }
Steve Anton75737c02017-11-06 10:37:17 -08006308 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6309 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006310 voice_channel->SignalSentPacket.connect(this,
6311 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006312 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006313
Steve Antoneda6ccd2017-12-04 10:21:55 -08006314 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006315}
6316
Steve Anton4171afb2017-11-20 10:20:22 -08006317// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006318cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006319 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006320 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006321 MediaTransportInterface* media_transport = nullptr;
6322 if (configuration_.use_media_transport) {
6323 media_transport = GetMediaTransport(mid);
6324 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006325
Steve Anton75737c02017-11-06 10:37:17 -08006326 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006327 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006328 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02006329 &ssrc_generator_, video_options_, video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006330 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006331 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006332 }
Steve Anton75737c02017-11-06 10:37:17 -08006333 video_channel->SignalDtlsSrtpSetupFailure.connect(
6334 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006335 video_channel->SignalSentPacket.connect(this,
6336 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006337 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006338
Steve Antoneda6ccd2017-12-04 10:21:55 -08006339 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006340}
6341
Zhi Huange830e682018-03-30 10:48:35 -07006342bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006343 switch (data_channel_type_) {
6344 case cricket::DCT_MEDIA_TRANSPORT:
6345 if (network_thread()->Invoke<bool>(
6346 RTC_FROM_HERE,
6347 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6348 this, mid))) {
6349 for (const auto& channel : sctp_data_channels_) {
6350 channel->OnTransportChannelCreated();
6351 }
6352 return true;
6353 }
Steve Anton75737c02017-11-06 10:37:17 -08006354 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006355 case cricket::DCT_SCTP:
6356 if (!sctp_factory_) {
6357 RTC_LOG(LS_ERROR)
6358 << "Trying to create SCTP transport, but didn't compile with "
6359 "SCTP support (HAVE_SCTP)";
6360 return false;
6361 }
6362 if (!network_thread()->Invoke<bool>(
6363 RTC_FROM_HERE,
6364 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6365 return false;
6366 }
6367 for (const auto& channel : sctp_data_channels_) {
6368 channel->OnTransportChannelCreated();
6369 }
6370 return true;
6371 case cricket::DCT_RTP:
6372 default:
6373 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6374 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6375 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006376 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006377 if (!rtp_data_channel_) {
6378 return false;
6379 }
6380 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6381 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6382 rtp_data_channel_->SignalSentPacket.connect(
6383 this, &PeerConnection::OnSentPacket_w);
6384 rtp_data_channel_->SetRtpTransport(rtp_transport);
6385 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006386 }
6387
Steve Anton75737c02017-11-06 10:37:17 -08006388 return true;
6389}
6390
6391Call::Stats PeerConnection::GetCallStats() {
6392 if (!worker_thread()->IsCurrent()) {
6393 return worker_thread()->Invoke<Call::Stats>(
6394 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6395 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006396 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006397 if (call_) {
6398 return call_->GetStats();
6399 } else {
6400 return Call::Stats();
6401 }
6402}
6403
Zhi Huange830e682018-03-30 10:48:35 -07006404bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006405 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006406 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006407 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6408 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006409 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006410 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006411 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006412 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6413 sctp_factory_->CreateSctpTransport(dtls_transport);
6414 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006415 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006416 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006417 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006418 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006419 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006420 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6421 // another thread. Would be nice if there was a helper class similar to
6422 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6423 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006424 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006425 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006426 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006427 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006428 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006429 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6430 std::move(cricket_sctp_transport));
6431 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006432 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006433}
6434
6435void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006436 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006437 sctp_transport_->Clear();
6438 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006439 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006440 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006441}
6442
6443void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006444 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006445 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006446 // Note: Cannot use rtc::Bind here because it will grab a reference to
6447 // PeerConnection and potentially cause PeerConnection to live longer than
6448 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6449 // be destroyed before PeerConnection is destroyed, and at that point all
6450 // pending tasks will be cleared.
6451 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6452 OnSctpTransportReadyToSendData_s(true);
6453 });
6454}
6455
6456void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006457 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006458 sctp_ready_to_send_data_ = ready;
6459 SignalSctpReadyToSendData(ready);
6460}
6461
6462void PeerConnection::OnSctpTransportDataReceived_n(
6463 const cricket::ReceiveDataParams& params,
6464 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006465 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006466 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006467 // Note: Cannot use rtc::Bind here because it will grab a reference to
6468 // PeerConnection and potentially cause PeerConnection to live longer than
6469 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6470 // be destroyed before PeerConnection is destroyed, and at that point all
6471 // pending tasks will be cleared.
6472 sctp_invoker_->AsyncInvoke<void>(
6473 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6474 OnSctpTransportDataReceived_s(params, payload);
6475 });
6476}
6477
6478void PeerConnection::OnSctpTransportDataReceived_s(
6479 const cricket::ReceiveDataParams& params,
6480 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006481 RTC_DCHECK_RUN_ON(signaling_thread());
6482 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006483 SignalSctpDataReceived(params, payload);
6484 }
6485}
6486
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006487void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006488 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006489 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006490 sctp_invoker_->AsyncInvoke<void>(
6491 RTC_FROM_HERE, signaling_thread(),
6492 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006493 &SignalSctpClosingProcedureStartedRemotely, sid));
6494}
6495
6496void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006497 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006498 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006499 sctp_invoker_->AsyncInvoke<void>(
6500 RTC_FROM_HERE, signaling_thread(),
6501 rtc::Bind(&sigslot::signal1<int>::operator(),
6502 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006503}
6504
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006505bool PeerConnection::SetupMediaTransportForDataChannels_n(
6506 const std::string& mid) {
6507 media_transport_ = transport_controller_->GetMediaTransport(mid);
6508 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006509 RTC_LOG(LS_ERROR)
6510 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006511 return false;
6512 }
6513
6514 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6515 media_transport_->SetDataSink(this);
6516 media_transport_data_mid_ = mid;
6517 transport_controller_->SignalMediaTransportStateChanged.connect(
6518 this, &PeerConnection::OnMediaTransportStateChanged_n);
6519 // Check the initial state right away, in case transport is already writable.
6520 OnMediaTransportStateChanged_n();
6521 return true;
6522}
6523
6524void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6525 if (!media_transport_) {
6526 return;
6527 }
6528 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6529 media_transport_data_mid_.reset();
6530 media_transport_->SetDataSink(nullptr);
6531 media_transport_invoker_ = nullptr;
6532 media_transport_ = nullptr;
6533}
6534
6535void PeerConnection::OnMediaTransportStateChanged_n() {
6536 if (!media_transport_data_mid_ ||
6537 transport_controller_->GetMediaTransportState(
6538 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6539 return;
6540 }
6541 media_transport_invoker_->AsyncInvoke<void>(
6542 RTC_FROM_HERE, signaling_thread(), [this] {
6543 RTC_DCHECK_RUN_ON(signaling_thread());
6544 media_transport_ready_to_send_data_ = true;
6545 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6546 });
6547}
6548
Steve Anton75737c02017-11-06 10:37:17 -08006549// Returns false if bundle is enabled and rtcp_mux is disabled.
6550bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6551 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6552 if (!bundle_enabled)
6553 return true;
6554
6555 const cricket::ContentGroup* bundle_group =
6556 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6557 RTC_DCHECK(bundle_group != NULL);
6558
6559 const cricket::ContentInfos& contents = desc->contents();
6560 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6561 citer != contents.end(); ++citer) {
6562 const cricket::ContentInfo* content = (&*citer);
6563 RTC_DCHECK(content != NULL);
6564 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006565 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006566 if (!HasRtcpMuxEnabled(content))
6567 return false;
6568 }
6569 }
6570 // RTCP-MUX is enabled in all the contents.
6571 return true;
6572}
6573
6574bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006575 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006576}
6577
Steve Anton06817cd2018-12-18 15:55:30 -08006578static RTCError ValidateMids(const cricket::SessionDescription& description) {
6579 std::set<std::string> mids;
6580 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006581 if (content.name.empty()) {
6582 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6583 "A media section is missing a MID attribute.");
6584 }
Steve Anton06817cd2018-12-18 15:55:30 -08006585 if (!mids.insert(content.name).second) {
6586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6587 "Duplicate a=mid value '" + content.name + "'.");
6588 }
6589 }
6590 return RTCError::OK();
6591}
6592
Steve Anton8a006912017-12-04 15:25:56 -08006593RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006594 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006595 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006596 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006597 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006598 }
6599
6600 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006601 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603
Steve Anton3828c062017-12-06 10:34:51 -08006604 SdpType type = sdesc->GetType();
6605 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6606 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006607 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006608 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006609 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006610 }
6611
Steve Anton06817cd2018-12-18 15:55:30 -08006612 RTCError error = ValidateMids(*sdesc->description());
6613 if (!error.ok()) {
6614 return error;
6615 }
6616
Steve Anton75737c02017-11-06 10:37:17 -08006617 // Verify crypto settings.
6618 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006619 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6620 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006621 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006622 if (!crypto_error.ok()) {
6623 return crypto_error;
6624 }
Steve Anton75737c02017-11-06 10:37:17 -08006625 }
6626
6627 // Verify ice-ufrag and ice-pwd.
6628 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006629 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6630 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006631 }
6632
6633 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006634 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6635 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006636 }
6637
6638 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6639 // m-lines that do not rtcp-mux enabled.
6640
6641 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006642 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006643 // With an answer we want to compare the new answer session description with
6644 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006645 const cricket::SessionDescription* offer_desc =
6646 (source == cricket::CS_LOCAL) ? remote_description()->description()
6647 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006648 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6649 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6650 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6652 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006653 }
6654 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006655 // The re-offers should respect the order of m= sections in current
6656 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006657 // With a re-offer, either the current local or current remote descriptions
6658 // could be the most up to date, so we would like to check against both of
6659 // them if they exist. It could be the case that one of them has a 0 port
6660 // for a media section, but the other does not. This is important to check
6661 // against in the case that we are recycling an m= section.
6662 const cricket::SessionDescription* current_desc = nullptr;
6663 const cricket::SessionDescription* secondary_current_desc = nullptr;
6664 if (local_description()) {
6665 current_desc = local_description()->description();
6666 if (remote_description()) {
6667 secondary_current_desc = remote_description()->description();
6668 }
6669 } else if (remote_description()) {
6670 current_desc = remote_description()->description();
6671 }
Steve Anton75737c02017-11-06 10:37:17 -08006672 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006673 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6674 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6676 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006677 }
6678 }
6679
Steve Antonba42e992018-04-09 14:10:01 -07006680 if (IsUnifiedPlan()) {
6681 // Ensure that each audio and video media section has at most one
6682 // "StreamParams". This will return an error if receiving a session
6683 // description from a "Plan B" endpoint which adds multiple tracks of the
6684 // same type. With Unified Plan, there can only be at most one track per
6685 // media section.
6686 for (const ContentInfo& content : sdesc->description()->contents()) {
6687 const MediaContentDescription& desc = *content.description;
6688 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6689 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6690 desc.streams().size() > 1u) {
6691 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6692 "Media section has more than one track specified "
6693 "with a=ssrc lines which is not supported with "
6694 "Unified Plan.");
6695 }
6696 }
6697 }
6698
Steve Anton8a006912017-12-04 15:25:56 -08006699 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006700}
6701
Steve Anton3828c062017-12-06 10:34:51 -08006702bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006703 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006704 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006705 return (state == PeerConnectionInterface::kStable) ||
6706 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006707 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006708 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006709 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6710 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6711 }
6712}
6713
Steve Anton3828c062017-12-06 10:34:51 -08006714bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006715 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006716 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006717 return (state == PeerConnectionInterface::kStable) ||
6718 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006719 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006720 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006721 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6722 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6723 }
6724}
6725
Steve Antonf8470812017-12-04 10:46:21 -08006726const char* PeerConnection::SessionErrorToString(SessionError error) const {
6727 switch (error) {
6728 case SessionError::kNone:
6729 return "ERROR_NONE";
6730 case SessionError::kContent:
6731 return "ERROR_CONTENT";
6732 case SessionError::kTransport:
6733 return "ERROR_TRANSPORT";
6734 }
6735 RTC_NOTREACHED();
6736 return "";
6737}
6738
Steve Anton75737c02017-11-06 10:37:17 -08006739std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006740 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006741 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6742 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006743 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006744}
6745
Steve Anton8e20f172018-03-06 10:55:04 -08006746void PeerConnection::ReportSdpFormatReceived(
6747 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006748 int num_audio_mlines = 0;
6749 int num_video_mlines = 0;
6750 int num_audio_tracks = 0;
6751 int num_video_tracks = 0;
6752 for (const ContentInfo& content : remote_offer.description()->contents()) {
6753 cricket::MediaType media_type = content.media_description()->type();
6754 int num_tracks = std::max(
6755 1, static_cast<int>(content.media_description()->streams().size()));
6756 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6757 num_audio_mlines += 1;
6758 num_audio_tracks += num_tracks;
6759 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6760 num_video_mlines += 1;
6761 num_video_tracks += num_tracks;
6762 }
6763 }
6764 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6765 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6766 format = kSdpFormatReceivedComplexUnifiedPlan;
6767 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6768 format = kSdpFormatReceivedComplexPlanB;
6769 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6770 format = kSdpFormatReceivedSimple;
6771 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006772 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6773 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006774}
6775
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006776void PeerConnection::NoteUsageEvent(UsageEvent event) {
6777 RTC_DCHECK_RUN_ON(signaling_thread());
6778 usage_event_accumulator_ |= static_cast<int>(event);
6779}
6780
6781void PeerConnection::ReportUsagePattern() const {
6782 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006783 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6784 usage_event_accumulator_,
6785 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006786 const int bad_bits =
6787 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6788 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6789 const int good_bits =
6790 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6791 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6792 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6793 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6794 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006795 // If called after close(), we can't report, because observer may have
6796 // been deallocated, and therefore pointer is null. Write to log instead.
6797 if (observer_) {
6798 Observer()->OnInterestingUsage(usage_event_accumulator_);
6799 } else {
6800 RTC_LOG(LS_INFO) << "Interesting usage signature "
6801 << usage_event_accumulator_
6802 << " observed after observer shutdown";
6803 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006804 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006805}
6806
Steve Anton0ffaaa22018-02-23 10:31:30 -08006807void PeerConnection::ReportNegotiatedSdpSemantics(
6808 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006809 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006810 switch (answer.description()->msid_signaling()) {
6811 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006812 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006813 break;
6814 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006815 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006816 break;
6817 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006818 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006819 break;
6820 case cricket::kMsidSignalingMediaSection |
6821 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006822 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006823 break;
6824 default:
6825 RTC_NOTREACHED();
6826 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006827 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6828 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006829}
6830
Steve Anton75737c02017-11-06 10:37:17 -08006831// We need to check the local/remote description for the Transport instead of
6832// the session, because a new Transport added during renegotiation may have
6833// them unset while the session has them set from the previous negotiation.
6834// Not doing so may trigger the auto generation of transport description and
6835// mess up DTLS identity information, ICE credential, etc.
6836bool PeerConnection::ReadyToUseRemoteCandidate(
6837 const IceCandidateInterface* candidate,
6838 const SessionDescriptionInterface* remote_desc,
6839 bool* valid) {
6840 *valid = true;
6841
6842 const SessionDescriptionInterface* current_remote_desc =
6843 remote_desc ? remote_desc : remote_description();
6844
6845 if (!current_remote_desc) {
6846 return false;
6847 }
6848
6849 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6850 size_t remote_content_size =
6851 current_remote_desc->description()->contents().size();
6852 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006853 RTC_LOG(LS_ERROR)
6854 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6855 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006856
6857 *valid = false;
6858 return false;
6859 }
6860
6861 cricket::ContentInfo content =
6862 current_remote_desc->description()->contents()[mediacontent_index];
6863
6864 const std::string transport_name = GetTransportName(content.name);
6865 if (transport_name.empty()) {
6866 return false;
6867 }
Zhi Huange830e682018-03-30 10:48:35 -07006868 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006869}
6870
6871bool PeerConnection::SrtpRequired() const {
6872 return dtls_enabled_ ||
6873 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6874}
6875
6876void PeerConnection::OnTransportControllerGatheringState(
6877 cricket::IceGatheringState state) {
6878 RTC_DCHECK(signaling_thread()->IsCurrent());
6879 if (state == cricket::kIceGatheringGathering) {
6880 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6881 } else if (state == cricket::kIceGatheringComplete) {
6882 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6883 }
6884}
6885
6886void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006887 std::map<std::string, std::set<cricket::MediaType>>
6888 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006889 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006890 if (transceiver->internal()->channel()) {
6891 const std::string& transport_name =
6892 transceiver->internal()->channel()->transport_name();
6893 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006894 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006895 }
Steve Anton75737c02017-11-06 10:37:17 -08006896 }
6897 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006898 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6899 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006900 }
Zhi Huange830e682018-03-30 10:48:35 -07006901
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006902 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006903 if (transport_name) {
6904 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006905 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006906 }
Zhi Huange830e682018-03-30 10:48:35 -07006907
Steve Antonc7b964c2018-02-01 14:39:45 -08006908 for (const auto& entry : media_types_by_transport_name) {
6909 const std::string& transport_name = entry.first;
6910 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006911 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006912 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006913 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006914 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006915 }
6916 }
6917}
6918// Walk through the ConnectionInfos to gather best connection usage
6919// for IPv4 and IPv6.
6920void PeerConnection::ReportBestConnectionState(
6921 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006922 for (const cricket::TransportChannelStats& channel_stats :
6923 stats.channel_stats) {
6924 for (const cricket::ConnectionInfo& connection_info :
6925 channel_stats.connection_infos) {
6926 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006927 continue;
6928 }
6929
Steve Antonc7b964c2018-02-01 14:39:45 -08006930 const cricket::Candidate& local = connection_info.local_candidate;
6931 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006932
6933 // Increment the counter for IceCandidatePairType.
6934 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6935 (local.type() == RELAY_PORT_TYPE &&
6936 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006937 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6938 GetIceCandidatePairCounter(local, remote),
6939 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006940 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006941 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6942 GetIceCandidatePairCounter(local, remote),
6943 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006944 } else {
6945 RTC_CHECK(0);
6946 }
Steve Anton75737c02017-11-06 10:37:17 -08006947
6948 // Increment the counter for IP type.
6949 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006950 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6951 kBestConnections_IPv4,
6952 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006953 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006954 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6955 kBestConnections_IPv6,
6956 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006957 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006958 RTC_CHECK(!local.address().hostname().empty() &&
6959 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006960 }
6961
6962 return;
6963 }
6964 }
6965}
6966
6967void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006968 const cricket::TransportStats& stats,
6969 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006970 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6971 return;
6972 }
6973
6974 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6975 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6976 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6977 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6978 return;
6979 }
6980
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006981 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6982 for (cricket::MediaType media_type : media_types) {
6983 switch (media_type) {
6984 case cricket::MEDIA_TYPE_AUDIO:
6985 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6986 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6987 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6988 break;
6989 case cricket::MEDIA_TYPE_VIDEO:
6990 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6991 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6992 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6993 break;
6994 case cricket::MEDIA_TYPE_DATA:
6995 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6996 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6997 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6998 break;
6999 default:
7000 RTC_NOTREACHED();
7001 continue;
7002 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007003 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007004 }
7005
7006 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7007 for (cricket::MediaType media_type : media_types) {
7008 switch (media_type) {
7009 case cricket::MEDIA_TYPE_AUDIO:
7010 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7011 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7012 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7013 break;
7014 case cricket::MEDIA_TYPE_VIDEO:
7015 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7016 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7017 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7018 break;
7019 case cricket::MEDIA_TYPE_DATA:
7020 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7021 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7022 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7023 break;
7024 default:
7025 RTC_NOTREACHED();
7026 continue;
7027 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007028 }
Steve Anton75737c02017-11-06 10:37:17 -08007029 }
7030}
7031
7032void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007033 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007034 RTC_DCHECK(call_);
7035 call_->OnSentPacket(sent_packet);
7036}
7037
7038const std::string PeerConnection::GetTransportName(
7039 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007040 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007041 if (channel) {
7042 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007043 }
Steve Anton6fec8802017-12-04 10:37:29 -08007044 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007045 RTC_DCHECK(sctp_mid_);
7046 if (content_name == *sctp_mid_) {
7047 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007048 }
7049 }
7050 // Return an empty string if failed to retrieve the transport name.
7051 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007052}
7053
Steve Anton6fec8802017-12-04 10:37:29 -08007054void PeerConnection::DestroyTransceiverChannel(
7055 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7056 transceiver) {
7057 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007058
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007059 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007060 if (channel) {
7061 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007062 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007063 }
7064}
7065
7066void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007067 if (rtp_data_channel_) {
7068 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007069 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007070 rtp_data_channel_ = nullptr;
7071 }
7072
7073 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7074 // grab a reference to this PeerConnection. If this is called from the
7075 // PeerConnection destructor, the RefCountedObject vtable will have already
7076 // been destroyed (since it is a subclass of PeerConnection) and using
7077 // rtc::Bind will cause "Pure virtual function called" error to appear.
7078
7079 if (sctp_transport_) {
7080 OnDataChannelDestroyed();
7081 network_thread()->Invoke<void>(RTC_FROM_HERE,
7082 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007083 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007084 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007085
7086 if (media_transport_) {
7087 OnDataChannelDestroyed();
7088 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7089 RTC_DCHECK_RUN_ON(network_thread());
7090 TeardownMediaTransportForDataChannels_n();
7091 });
7092 }
Steve Anton6fec8802017-12-04 10:37:29 -08007093}
7094
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007095void PeerConnection::DestroyChannelInterface(
7096 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007097 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007098 switch (channel->media_type()) {
7099 case cricket::MEDIA_TYPE_AUDIO:
7100 channel_manager()->DestroyVoiceChannel(
7101 static_cast<cricket::VoiceChannel*>(channel));
7102 break;
7103 case cricket::MEDIA_TYPE_VIDEO:
7104 channel_manager()->DestroyVideoChannel(
7105 static_cast<cricket::VideoChannel*>(channel));
7106 break;
7107 case cricket::MEDIA_TYPE_DATA:
7108 channel_manager()->DestroyRtpDataChannel(
7109 static_cast<cricket::RtpDataChannel*>(channel));
7110 break;
7111 default:
7112 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7113 break;
7114 }
Zhi Huange830e682018-03-30 10:48:35 -07007115}
Steve Anton6fec8802017-12-04 10:37:29 -08007116
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007117bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007118 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007119 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007120 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007121 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007122 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007123 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007124 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007125 auto base_channel = GetChannel(mid);
7126 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007127 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007128 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007129 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007130 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007131 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007132
Karl Wiberg5966c502019-02-21 23:55:09 +01007133 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007134 // Only pass media transport to call object if media transport is used
7135 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007136 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007137 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007138
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007139 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007140}
7141
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007142PeerConnectionObserver* PeerConnection::Observer() const {
7143 // In earlier production code, the pointer was not cleared on close,
7144 // which might have led to undefined behavior if the observer was not
7145 // deallocated, or strange crashes if it was.
7146 // We use CHECK in order to catch such behavior if it exists.
7147 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7148 RTC_CHECK(observer_);
7149 return observer_;
7150}
7151
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007152CryptoOptions PeerConnection::GetCryptoOptions() {
7153 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7154 // after it has been removed.
7155 return configuration_.crypto_options.has_value()
7156 ? *configuration_.crypto_options
7157 : factory_->options().crypto_options;
7158}
7159
Harald Alvestrand89061872018-01-02 14:08:34 +01007160void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007161 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007162 if (stats_collector_) {
7163 stats_collector_->ClearCachedStatsReport();
7164 }
7165}
7166
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007167void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007168 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7169 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007170}
7171
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007172void PeerConnection::UpdateNegotiationNeeded() {
7173 RTC_DCHECK_RUN_ON(signaling_thread());
7174 if (!IsUnifiedPlan()) {
7175 Observer()->OnRenegotiationNeeded();
7176 return;
7177 }
7178
7179 // If connection's [[IsClosed]] slot is true, abort these steps.
7180 if (IsClosed())
7181 return;
7182
7183 // If connection's signaling state is not "stable", abort these steps.
7184 if (signaling_state() != kStable)
7185 return;
7186
7187 // NOTE
7188 // The negotiation-needed flag will be updated once the state transitions to
7189 // "stable", as part of the steps for setting an RTCSessionDescription.
7190
7191 // If the result of checking if negotiation is needed is false, clear the
7192 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7193 // to false, and abort these steps.
7194 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7195 if (!is_negotiation_needed) {
7196 is_negotiation_needed_ = false;
7197 return;
7198 }
7199
7200 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7201 // steps.
7202 if (is_negotiation_needed_)
7203 return;
7204
7205 // Set connection's [[NegotiationNeeded]] slot to true.
7206 is_negotiation_needed_ = true;
7207
7208 // Queue a task that runs the following steps:
7209 // If connection's [[IsClosed]] slot is true, abort these steps.
7210 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7211 // Fire an event named negotiationneeded at connection.
7212 Observer()->OnRenegotiationNeeded();
7213}
7214
7215bool PeerConnection::CheckIfNegotiationIsNeeded() {
7216 RTC_DCHECK_RUN_ON(signaling_thread());
7217 // 1. If any implementation-specific negotiation is required, as described at
7218 // the start of this section, return true.
7219
7220 // 2. Let description be connection.[[CurrentLocalDescription]].
7221 const SessionDescriptionInterface* description = current_local_description();
7222 if (!description)
7223 return true;
7224
7225 // 3. If connection has created any RTCDataChannels, and no m= section in
7226 // description has been negotiated yet for data, return true.
7227 if (!sctp_data_channels_.empty()) {
7228 if (!cricket::GetFirstDataContent(description->description()->contents()))
7229 return true;
7230 }
7231
7232 // 4. For each transceiver in connection's set of transceivers, perform the
7233 // following checks:
7234 for (const auto& transceiver : transceivers_) {
7235 const ContentInfo* current_local_msection =
7236 FindTransceiverMSection(transceiver.get(), description);
7237
7238 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7239 transceiver.get(), current_remote_description());
7240
7241 // 4.3 If transceiver is stopped and is associated with an m= section,
7242 // but the associated m= section is not yet rejected in
7243 // connection.[[CurrentLocalDescription]] or
7244 // connection.[[CurrentRemoteDescription]], return true.
7245 if (transceiver->stopped()) {
7246 if (current_local_msection && !current_local_msection->rejected &&
7247 ((current_remote_msection && !current_remote_msection->rejected) ||
7248 !current_remote_msection)) {
7249 return true;
7250 }
7251 continue;
7252 }
7253
7254 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7255 // section in description, return true.
7256 if (!current_local_msection)
7257 return true;
7258
7259 const MediaContentDescription* current_local_media_description =
7260 current_local_msection->media_description();
7261 // 4.2 If transceiver isn't stopped and is associated with an m= section
7262 // in description then perform the following checks:
7263
7264 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7265 // associated m= section in description either doesn't contain a single
7266 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7267 // m= section, or the MSID values themselves, differ from what is in
7268 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7269 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7270 if (current_local_media_description->streams().size() == 0)
7271 return true;
7272
7273 std::vector<std::string> msection_msids;
7274 for (const auto& stream : current_local_media_description->streams()) {
7275 for (const std::string& msid : stream.stream_ids())
7276 msection_msids.push_back(msid);
7277 }
7278
7279 std::vector<std::string> transceiver_msids =
7280 transceiver->sender()->stream_ids();
7281 if (msection_msids.size() != transceiver_msids.size())
7282 return true;
7283
7284 absl::c_sort(transceiver_msids);
7285 absl::c_sort(msection_msids);
7286 if (transceiver_msids != msection_msids)
7287 return true;
7288 }
7289
7290 // 4.2.2 If description is of type "offer", and the direction of the
7291 // associated m= section in neither connection.[[CurrentLocalDescription]]
7292 // nor connection.[[CurrentRemoteDescription]] matches
7293 // transceiver.[[Direction]], return true.
7294 if (description->GetType() == SdpType::kOffer) {
7295 if (!current_remote_description())
7296 return true;
7297
7298 if (!current_remote_msection)
7299 return true;
7300
7301 RtpTransceiverDirection current_local_direction =
7302 current_local_media_description->direction();
7303 RtpTransceiverDirection current_remote_direction =
7304 current_remote_msection->media_description()->direction();
7305 if (transceiver->direction() != current_local_direction &&
7306 transceiver->direction() !=
7307 RtpTransceiverDirectionReversed(current_remote_direction)) {
7308 return true;
7309 }
7310 }
7311
7312 // 4.2.3 If description is of type "answer", and the direction of the
7313 // associated m= section in the description does not match
7314 // transceiver.[[Direction]] intersected with the offered direction (as
7315 // described in [JSEP] (section 5.3.1.)), return true.
7316 if (description->GetType() == SdpType::kAnswer) {
7317 if (!remote_description())
7318 return true;
7319
7320 const ContentInfo* offered_remote_msection =
7321 FindTransceiverMSection(transceiver.get(), remote_description());
7322
7323 RtpTransceiverDirection offered_direction =
7324 offered_remote_msection
7325 ? offered_remote_msection->media_description()->direction()
7326 : RtpTransceiverDirection::kInactive;
7327
7328 if (current_local_media_description->direction() !=
7329 (RtpTransceiverDirectionIntersection(
7330 transceiver->direction(),
7331 RtpTransceiverDirectionReversed(offered_direction)))) {
7332 return true;
7333 }
7334 }
7335 }
7336
7337 // If all the preceding checks were performed and true was not returned,
7338 // nothing remains to be negotiated; return false.
7339 return false;
7340}
7341
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007342} // namespace webrtc