blob: b4c5fe2d9a661d374c6a2fd537d42ed71ecccc83 [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) {
Steve Anton46afbf92019-05-10 11:15:18 -0700562 const cricket::DataContentDescription* data_desc =
563 GetFirstDataContentDescription(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 }
Steve Anton46afbf92019-05-10 11:15:18 -0700568 std::string value;
569 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
570 cricket::kGoogleSctpDataCodecName);
571 for (const cricket::DataCodec& codec : data_desc->codecs()) {
572 if (!codec.Matches(match_pattern)) {
573 continue;
574 }
575 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
576 return rtc::FromString<int>(value);
577 }
578 }
579 return -1;
Steve Anton75737c02017-11-06 10:37:17 -0800580}
581
Steve Anton75737c02017-11-06 10:37:17 -0800582// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
583bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
584 const SessionDescriptionInterface* new_desc,
585 const std::string& content_name) {
586 if (!old_desc) {
587 return false;
588 }
589 const SessionDescription* new_sd = new_desc->description();
590 const SessionDescription* old_sd = old_desc->description();
591 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
592 if (!cinfo || cinfo->rejected) {
593 return false;
594 }
595 // If the content isn't rejected, check if ufrag and password has changed.
596 const cricket::TransportDescription* new_transport_desc =
597 new_sd->GetTransportDescriptionByName(content_name);
598 const cricket::TransportDescription* old_transport_desc =
599 old_sd->GetTransportDescriptionByName(content_name);
600 if (!new_transport_desc || !old_transport_desc) {
601 // No transport description exists. This is not an ICE restart.
602 return false;
603 }
604 if (cricket::IceCredentialsChanged(
605 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
606 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100607 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
608 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800609 return true;
610 }
611 return false;
612}
613
Steve Anton80dd7b52018-02-16 17:08:42 -0800614// Generates a string error message for SetLocalDescription/SetRemoteDescription
615// from an RTCError.
616std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
617 SdpType type,
618 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200619 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800620 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
621 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200622 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800623}
624
Seth Hampson5b4f0752018-04-02 16:31:36 -0700625std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
626 std::string output = "streams=[";
627 const char* separator = "";
628 for (const auto& stream_id : stream_ids) {
629 output.append(separator).append(stream_id);
630 separator = ", ";
631 }
632 output.append("]");
633 return output;
634}
635
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200636absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700637 int rtc_configuration_parameter) {
638 if (rtc_configuration_parameter ==
639 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200640 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700641 }
642 return rtc_configuration_parameter;
643}
644
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800645cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
646 switch (type) {
647 case DataMessageType::kText:
648 return cricket::DMT_TEXT;
649 case DataMessageType::kBinary:
650 return cricket::DMT_BINARY;
651 case DataMessageType::kControl:
652 return cricket::DMT_CONTROL;
653 default:
654 return cricket::DMT_NONE;
655 }
656 return cricket::DMT_NONE;
657}
658
659DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
660 switch (type) {
661 case cricket::DMT_TEXT:
662 return DataMessageType::kText;
663 case cricket::DMT_BINARY:
664 return DataMessageType::kBinary;
665 case cricket::DMT_CONTROL:
666 return DataMessageType::kControl;
667 case cricket::DMT_NONE:
668 default:
669 RTC_NOTREACHED();
670 }
671 return DataMessageType::kControl;
672}
673
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800674void ReportSimulcastApiVersion(const char* name,
675 const SessionDescription& session) {
676 bool has_legacy = false;
677 bool has_spec_compliant = false;
678 for (const ContentInfo& content : session.contents()) {
679 if (!content.description) {
680 continue;
681 }
682 has_spec_compliant |= content.description->HasSimulcast();
683 for (const StreamParams& sp : content.description->streams()) {
684 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
685 }
686 }
687
688 if (has_legacy) {
689 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
690 kSimulcastApiVersionMax);
691 }
692 if (has_spec_compliant) {
693 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
694 kSimulcastApiVersionMax);
695 }
696 if (!has_legacy && !has_spec_compliant) {
697 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
698 kSimulcastApiVersionMax);
699 }
700}
701
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200702const ContentInfo* FindTransceiverMSection(
703 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
704 const SessionDescriptionInterface* session_description) {
705 return transceiver->mid()
706 ? session_description->description()->GetContentByName(
707 *transceiver->mid())
708 : nullptr;
709}
710
Steve Anton75737c02017-11-06 10:37:17 -0800711} // namespace
712
Henrik Boström31638672017-11-23 17:48:32 +0100713// Upon completion, posts a task to execute the callback of the
714// SetSessionDescriptionObserver asynchronously on the same thread. At this
715// point, the state of the peer connection might no longer reflect the effects
716// of the SetRemoteDescription operation, as the peer connection could have been
717// modified during the post.
718// TODO(hbos): Remove this class once we remove the version of
719// PeerConnectionInterface::SetRemoteDescription() that takes a
720// SetSessionDescriptionObserver as an argument.
721class PeerConnection::SetRemoteDescriptionObserverAdapter
722 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
723 public:
724 SetRemoteDescriptionObserverAdapter(
725 rtc::scoped_refptr<PeerConnection> pc,
726 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
727 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
728
729 // SetRemoteDescriptionObserverInterface implementation.
730 void OnSetRemoteDescriptionComplete(RTCError error) override {
731 if (error.ok())
732 pc_->PostSetSessionDescriptionSuccess(wrapper_);
733 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100734 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100735 }
736
737 private:
738 rtc::scoped_refptr<PeerConnection> pc_;
739 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
740};
741
deadbeef293e9262017-01-11 12:28:30 -0800742bool PeerConnectionInterface::RTCConfiguration::operator==(
743 const PeerConnectionInterface::RTCConfiguration& o) const {
744 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800746 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000747 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700748 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800749 BundlePolicy bundle_policy;
750 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700751 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
752 int ice_candidate_pool_size;
753 bool disable_ipv6;
754 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700755 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100756 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700757 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200758 absl::optional<int> screencast_min_bitrate;
759 absl::optional<bool> combined_audio_video_bwe;
760 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800761 TcpCandidatePolicy tcp_candidate_policy;
762 CandidateNetworkPolicy candidate_network_policy;
763 int audio_jitter_buffer_max_packets;
764 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100765 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100766 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800767 int ice_connection_receiving_timeout;
768 int ice_backup_candidate_pair_ping_interval;
769 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800770 bool prioritize_most_likely_ice_candidate_pairs;
771 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800772 bool prune_turn_ports;
773 bool presume_writable_when_fully_relayed;
774 bool enable_ice_renomination;
775 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200776 absl::optional<int> ice_check_interval_strong_connectivity;
777 absl::optional<int> ice_check_interval_weak_connectivity;
778 absl::optional<int> ice_check_min_interval;
779 absl::optional<int> ice_unwritable_timeout;
780 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800781 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200782 absl::optional<int> stun_candidate_keepalive_interval;
783 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200784 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800785 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200786 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700787 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700788 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700789 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700790 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100791 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800792 };
793 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
794 "Did you add something to RTCConfiguration and forget to "
795 "update operator==?");
796 return type == o.type && servers == o.servers &&
797 bundle_policy == o.bundle_policy &&
798 rtcp_mux_policy == o.rtcp_mux_policy &&
799 tcp_candidate_policy == o.tcp_candidate_policy &&
800 candidate_network_policy == o.candidate_network_policy &&
801 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
802 audio_jitter_buffer_fast_accelerate ==
803 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100804 audio_jitter_buffer_min_delay_ms ==
805 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100806 audio_jitter_buffer_enable_rtx_handling ==
807 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800808 ice_connection_receiving_timeout ==
809 o.ice_connection_receiving_timeout &&
810 ice_backup_candidate_pair_ping_interval ==
811 o.ice_backup_candidate_pair_ping_interval &&
812 continual_gathering_policy == o.continual_gathering_policy &&
813 certificates == o.certificates &&
814 prioritize_most_likely_ice_candidate_pairs ==
815 o.prioritize_most_likely_ice_candidate_pairs &&
816 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800817 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700818 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100819 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800820 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800821 screencast_min_bitrate == o.screencast_min_bitrate &&
822 combined_audio_video_bwe == o.combined_audio_video_bwe &&
823 enable_dtls_srtp == o.enable_dtls_srtp &&
824 ice_candidate_pool_size == o.ice_candidate_pool_size &&
825 prune_turn_ports == o.prune_turn_ports &&
826 presume_writable_when_fully_relayed ==
827 o.presume_writable_when_fully_relayed &&
828 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800829 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800830 ice_check_interval_strong_connectivity ==
831 o.ice_check_interval_strong_connectivity &&
832 ice_check_interval_weak_connectivity ==
833 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700834 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700835 ice_unwritable_timeout == o.ice_unwritable_timeout &&
836 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800837 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800838 stun_candidate_keepalive_interval ==
839 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200840 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800841 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800842 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700843 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700844 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700845 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700846 use_media_transport_for_data_channels ==
847 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100848 crypto_options == o.crypto_options &&
849 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800850}
851
852bool PeerConnectionInterface::RTCConfiguration::operator!=(
853 const PeerConnectionInterface::RTCConfiguration& o) const {
854 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800855}
856
zhihuang8f65cdf2016-05-06 18:40:30 -0700857// Generate a RTCP CNAME when a PeerConnection is created.
858std::string GenerateRtcpCname() {
859 std::string cname;
860 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100861 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800862 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700863 }
864 return cname;
865}
866
zhihuang1c378ed2017-08-17 14:10:50 -0700867bool ValidateOfferAnswerOptions(
868 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
869 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
870 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700871}
872
zhihuang1c378ed2017-08-17 14:10:50 -0700873// From |rtc_options|, fill parts of |session_options| shared by all generated
874// m= sections (in other words, nothing that involves a map/array).
875void ExtractSharedMediaSessionOptions(
876 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
877 cricket::MediaSessionOptions* session_options) {
878 session_options->vad_enabled = rtc_options.voice_activity_detection;
879 session_options->bundle_enabled = rtc_options.use_rtp_mux;
880}
zhihuanga77e6bb2017-08-14 18:17:48 -0700881
zhihuang38ede132017-06-15 12:52:32 -0700882PeerConnection::PeerConnection(PeerConnectionFactory* factory,
883 std::unique_ptr<RtcEventLog> event_log,
884 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700886 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100887 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700888 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700889 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700890 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100891 call_(std::move(call)),
892 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000893
894PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100895 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800896 RTC_DCHECK_RUN_ON(signaling_thread());
897
Steve Anton8af21862017-12-15 11:20:13 -0800898 // Need to stop transceivers before destroying the stats collector because
899 // AudioRtpSender has a reference to the StatsCollector it will update when
900 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100901 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800902 transceiver->Stop();
903 }
Steve Anton4171afb2017-11-20 10:20:22 -0800904
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700905 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800906 if (stats_collector_) {
907 stats_collector_->WaitForPendingRequest();
908 stats_collector_ = nullptr;
909 }
Steve Anton75737c02017-11-06 10:37:17 -0800910
Steve Anton8af21862017-12-15 11:20:13 -0800911 // Don't destroy BaseChannels until after stats has been cleaned up so that
912 // the last stats request can still read from the channels.
913 DestroyAllChannels();
914
Mirko Bonadei675513b2017-11-09 11:09:25 +0100915 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800916
917 webrtc_session_desc_factory_.reset();
918 sctp_invoker_.reset();
919 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800920 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800921 transport_controller_.reset();
922
deadbeef91dd5672016-05-18 16:55:30 -0700923 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100924 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
925 RTC_DCHECK_RUN_ON(network_thread());
926 port_allocator_.reset();
927 });
eladalon248fd4f2017-09-06 05:18:15 -0700928 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700929 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100930 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700931 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800932 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700933 event_log_.reset();
934 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935}
936
Steve Anton8af21862017-12-15 11:20:13 -0800937void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800938 // Destroy video channels first since they may have a pointer to a voice
939 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100940 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800941 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800942 DestroyTransceiverChannel(transceiver);
943 }
944 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100945 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800946 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800947 DestroyTransceiverChannel(transceiver);
948 }
949 }
950 DestroyDataChannel();
951}
952
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000954 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700955 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100956 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100957 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100958 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700959
960 RTCError config_error = ValidateConfiguration(configuration);
961 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100962 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700963 return false;
964 }
965
Benjamin Wrightcab58882018-05-02 15:12:47 -0700966 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100967 RTC_LOG(LS_ERROR)
968 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100969 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800970 return false;
971 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200972
Benjamin Wrightcab58882018-05-02 15:12:47 -0700973 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800974 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100975 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100976 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800977 return false;
978 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700979
Benjamin Wrightcab58882018-05-02 15:12:47 -0700980 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700981 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700982 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700983 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800984
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200985 cricket::ServerAddresses stun_servers;
986 std::vector<cricket::RelayServerConfig> turn_servers;
987
988 RTCErrorType parse_error =
989 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
990 if (parse_error != RTCErrorType::NONE) {
991 return false;
992 }
993
deadbeef91dd5672016-05-18 16:55:30 -0700994 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700995 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100996 const auto pa_result =
997 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200998 RTC_FROM_HERE,
999 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001000 stun_servers, turn_servers, configuration));
1001
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001002 // If initialization was successful, note if STUN or TURN servers
1003 // were supplied.
1004 if (!stun_servers.empty()) {
1005 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1006 }
1007 if (!turn_servers.empty()) {
1008 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001011 // Send information about IPv4/IPv6 status.
1012 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001013 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001014 address_family = kPeerConnection_IPv6;
1015 } else {
1016 address_family = kPeerConnection_IPv4;
1017 }
1018 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1019 kPeerConnectionAddressFamilyCounter_Max);
1020
Zhi Huange830e682018-03-30 10:48:35 -07001021 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1022
Steve Anton75737c02017-11-06 10:37:17 -08001023 // RFC 3264: The numeric value of the session id and version in the
1024 // o line MUST be representable with a "64 bit signed integer".
1025 // Due to this constraint session id |session_id_| is max limited to
1026 // LLONG_MAX.
1027 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001028 JsepTransportController::Config config;
1029 config.redetermine_role_on_ice_restart =
1030 configuration.redetermine_role_on_ice_restart;
1031 config.ssl_max_version = factory_->options().ssl_max_version;
1032 config.disable_encryption = options.disable_encryption;
1033 config.bundle_policy = configuration.bundle_policy;
1034 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001035 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1036 // stub.
1037 config.crypto_options = configuration.crypto_options.has_value()
1038 ? *configuration.crypto_options
1039 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001040 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001041 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001042#if defined(ENABLE_EXTERNAL_AUTH)
1043 config.enable_external_auth = true;
1044#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001045 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001046
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001047 if (configuration.use_media_transport ||
1048 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001049 if (!factory_->media_transport_factory()) {
1050 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001051 << "PeerConnecton is initialized with use_media_transport = true or "
1052 << "use_media_transport_for_data_channels = true "
1053 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001054 return false;
1055 }
1056
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001057 if (configuration.use_media_transport ||
1058 configuration.use_media_transport_for_data_channels) {
1059 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1060 // RTP media transport is introduced. But until then, we require SDES to
1061 // be enabled.
1062 if (configuration.enable_dtls_srtp.has_value() &&
1063 configuration.enable_dtls_srtp.value()) {
1064 RTC_LOG(LS_WARNING)
1065 << "When media transport is used, SDES must be enabled. Set "
1066 "configuration.enable_dtls_srtp to false. use_media_transport="
1067 << configuration.use_media_transport
1068 << ", use_media_transport_for_data_channels="
1069 << configuration.use_media_transport_for_data_channels;
1070 return false;
1071 }
1072 }
1073
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001074 config.use_media_transport_for_media = configuration.use_media_transport;
1075 config.use_media_transport_for_data_channels =
1076 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001077 config.media_transport_factory = factory_->media_transport_factory();
1078 }
1079
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001081 signaling_thread(), network_thread(), port_allocator_.get(),
1082 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001083 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001084 this, &PeerConnection::OnTransportControllerConnectionState);
1085 transport_controller_->SignalStandardizedIceConnectionState.connect(
1086 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001087 transport_controller_->SignalConnectionState.connect(
1088 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001089 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001090 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001091 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001092 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001093 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001094 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1095 transport_controller_->SignalDtlsHandshakeError.connect(
1096 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1097
1098 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001099
deadbeefab9b2d12015-10-14 11:33:11 -07001100 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001101 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102
Steve Antonba818672017-11-06 10:21:57 -08001103 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001104 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001105
Steve Anton75737c02017-11-06 10:37:17 -08001106 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1107 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1108 if (!configuration.certificates.empty()) {
1109 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1110 // just picking the first one. The decision should be made based on the DTLS
1111 // handshake. The DTLS negotiations need to know about all certificates.
1112 certificate = configuration.certificates[0];
1113 }
1114
Steve Antond25da372017-11-06 14:50:29 -08001115 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001116
1117 if (options.disable_encryption) {
1118 dtls_enabled_ = false;
1119 } else {
1120 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001121 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001122 // |configuration| can override the default |dtls_enabled_| value.
1123 if (configuration.enable_dtls_srtp) {
1124 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1125 }
1126 }
1127
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001128 if (configuration.use_media_transport_for_data_channels) {
1129 if (configuration.enable_rtp_data_channel) {
1130 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1131 "use_media_transport_for_data_channels are "
1132 "incompatible and cannot both be set to true";
1133 return false;
1134 }
1135 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1136 } else if (configuration.enable_rtp_data_channel) {
1137 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1138 // set. It takes precendence over the disable_sctp_data_channels
1139 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001140 data_channel_type_ = cricket::DCT_RTP;
1141 } else {
1142 // DTLS has to be enabled to use SCTP.
1143 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1144 data_channel_type_ = cricket::DCT_SCTP;
1145 }
1146 }
1147
1148 video_options_.screencast_min_bitrate_kbps =
1149 configuration.screencast_min_bitrate;
1150 audio_options_.combined_audio_video_bwe =
1151 configuration.combined_audio_video_bwe;
1152
1153 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001154 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001155
1156 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001157 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001158
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001159 audio_options_.audio_jitter_buffer_min_delay_ms =
1160 configuration.audio_jitter_buffer_min_delay_ms;
1161
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001162 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1163 configuration.audio_jitter_buffer_enable_rtx_handling;
1164
Steve Anton75737c02017-11-06 10:37:17 -08001165 // Whether the certificate generator/certificate is null or not determines
1166 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1167 // the right instructions by clearing the variables if needed.
1168 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001169 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001170 certificate = nullptr;
1171 } else if (certificate) {
1172 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001173 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001174 }
1175
1176 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1177 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001178 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001179 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1180 this, &PeerConnection::OnCertificateReady);
1181
1182 if (options.disable_encryption) {
1183 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1184 }
1185
1186 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001187 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001188 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001189
Steve Anton4171afb2017-11-20 10:20:22 -08001190 // Add default audio/video transceivers for Plan B SDP.
1191 if (!IsUnifiedPlan()) {
1192 transceivers_.push_back(
1193 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1194 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1195 transceivers_.push_back(
1196 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1197 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1198 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001199 int delay_ms =
1200 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001201 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1202 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001203
1204 if (dependencies.video_bitrate_allocator_factory) {
1205 video_bitrate_allocator_factory_ =
1206 std::move(dependencies.video_bitrate_allocator_factory);
1207 } else {
1208 video_bitrate_allocator_factory_ =
1209 CreateBuiltinVideoBitrateAllocatorFactory();
1210 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 return true;
1212}
1213
Steve Anton038834f2017-07-14 15:59:59 -07001214RTCError PeerConnection::ValidateConfiguration(
1215 const RTCConfiguration& config) const {
1216 if (config.ice_regather_interval_range &&
1217 config.continual_gathering_policy == GATHER_ONCE) {
1218 return RTCError(RTCErrorType::INVALID_PARAMETER,
1219 "ice_regather_interval_range specified but continual "
1220 "gathering policy is GATHER_ONCE");
1221 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001222 auto result =
1223 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1224 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001225}
1226
Yves Gerey665174f2018-06-19 15:03:05 +02001227rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001228 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001229 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1230 "Plan SdpSemantics. Please use GetSenders "
1231 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001232 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233}
1234
Yves Gerey665174f2018-06-19 15:03:05 +02001235rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001236 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001237 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1238 "Plan SdpSemantics. Please use GetReceivers "
1239 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001240 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241}
1242
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001243bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001244 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001245 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1246 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001247 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001248 if (IsClosed()) {
1249 return false;
1250 }
deadbeefab9b2d12015-10-14 11:33:11 -07001251 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252 return false;
1253 }
deadbeefab9b2d12015-10-14 11:33:11 -07001254
1255 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001256 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1257 observer->SignalAudioTrackAdded.connect(this,
1258 &PeerConnection::OnAudioTrackAdded);
1259 observer->SignalAudioTrackRemoved.connect(
1260 this, &PeerConnection::OnAudioTrackRemoved);
1261 observer->SignalVideoTrackAdded.connect(this,
1262 &PeerConnection::OnVideoTrackAdded);
1263 observer->SignalVideoTrackRemoved.connect(
1264 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001265 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001266
deadbeefab9b2d12015-10-14 11:33:11 -07001267 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001268 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001269 }
1270 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001271 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001272 }
1273
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001274 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001275 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 return true;
1277}
1278
1279void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001280 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001281 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1282 "Plan SdpSemantics. Please use RemoveTrack "
1283 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001284 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001285 if (!IsClosed()) {
1286 for (const auto& track : local_stream->GetAudioTracks()) {
1287 RemoveAudioTrack(track.get(), local_stream);
1288 }
1289 for (const auto& track : local_stream->GetVideoTracks()) {
1290 RemoveVideoTrack(track.get(), local_stream);
1291 }
deadbeefab9b2d12015-10-14 11:33:11 -07001292 }
deadbeefab9b2d12015-10-14 11:33:11 -07001293 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001294 stream_observers_.erase(
1295 std::remove_if(
1296 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001297 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001298 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001299 }),
1300 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001301
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 if (IsClosed()) {
1303 return;
1304 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001305 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306}
1307
Steve Anton2d6c76a2018-01-05 17:10:52 -08001308RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001309 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001310 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001311 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001312 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001313 if (!track) {
1314 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1315 }
1316 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1317 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1319 "Track has invalid kind: " + track->kind());
1320 }
Steve Antonf9381f02017-12-14 10:23:57 -08001321 if (IsClosed()) {
1322 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1323 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001324 }
Steve Anton4171afb2017-11-20 10:20:22 -08001325 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001326 LOG_AND_RETURN_ERROR(
1327 RTCErrorType::INVALID_PARAMETER,
1328 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001329 }
Steve Antonf9381f02017-12-14 10:23:57 -08001330 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001331 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1332 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001333 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001334 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001335 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001336 }
1337 return sender_or_error;
1338}
deadbeefe1f9d832016-01-14 15:35:42 -08001339
Steve Antonf9381f02017-12-14 10:23:57 -08001340RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1341PeerConnection::AddTrackPlanB(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001343 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001344 if (stream_ids.size() > 1u) {
1345 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1346 "AddTrack with more than one stream is not "
1347 "supported with Plan B semantics.");
1348 }
1349 std::vector<std::string> adjusted_stream_ids = stream_ids;
1350 if (adjusted_stream_ids.empty()) {
1351 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1352 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001353 cricket::MediaType media_type =
1354 (track->kind() == MediaStreamTrackInterface::kAudioKind
1355 ? cricket::MEDIA_TYPE_AUDIO
1356 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001357 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001358 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001359 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001360 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001361 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001362 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001363 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001364 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001365 if (sender_info) {
1366 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001367 }
Steve Antonf9381f02017-12-14 10:23:57 -08001368 } else {
1369 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001370 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001371 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001372 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001373 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001374 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001375 if (sender_info) {
1376 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001377 }
deadbeefe1f9d832016-01-14 15:35:42 -08001378 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001379 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001380}
deadbeefe1f9d832016-01-14 15:35:42 -08001381
Steve Antonf9381f02017-12-14 10:23:57 -08001382RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1383PeerConnection::AddTrackUnifiedPlan(
1384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001385 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001386 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1387 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001388 RTC_LOG(LS_INFO) << "Reusing an existing "
1389 << cricket::MediaTypeToString(transceiver->media_type())
1390 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001391 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001392 transceiver->internal()->set_direction(
1393 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001394 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001395 transceiver->internal()->set_direction(
1396 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001397 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001399 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001400 } else {
1401 cricket::MediaType media_type =
1402 (track->kind() == MediaStreamTrackInterface::kAudioKind
1403 ? cricket::MEDIA_TYPE_AUDIO
1404 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001405 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1406 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001407 std::string sender_id = track->id();
1408 // Avoid creating a sender with an existing ID by generating a random ID.
1409 // This can happen if this is the second time AddTrack has created a sender
1410 // for this track.
1411 if (FindSenderById(sender_id)) {
1412 sender_id = rtc::CreateRandomUuid();
1413 }
Florent Castelli892acf02018-10-01 22:47:20 +02001414 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001415 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1416 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001417 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001418 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001419 }
Steve Antonf9381f02017-12-14 10:23:57 -08001420 return transceiver->sender();
1421}
1422
1423rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1424PeerConnection::FindFirstTransceiverForAddedTrack(
1425 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1426 RTC_DCHECK(track);
1427 for (auto transceiver : transceivers_) {
1428 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001429 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001430 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001431 !transceiver->internal()->has_ever_been_used_to_send() &&
1432 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001433 return transceiver;
1434 }
1435 }
1436 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001437}
1438
1439bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1440 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001441 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001442}
1443
Steve Anton24db5732018-07-23 10:27:33 -07001444RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001445 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001446 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001447 if (!sender) {
1448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1449 }
deadbeefe1f9d832016-01-14 15:35:42 -08001450 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1452 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001453 }
Steve Antonf9381f02017-12-14 10:23:57 -08001454 if (IsUnifiedPlan()) {
1455 auto transceiver = FindTransceiverBySender(sender);
1456 if (!transceiver || !sender->track()) {
1457 return RTCError::OK();
1458 }
1459 sender->SetTrack(nullptr);
1460 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001461 transceiver->internal()->set_direction(
1462 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001463 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001464 transceiver->internal()->set_direction(
1465 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001466 }
Steve Anton4171afb2017-11-20 10:20:22 -08001467 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001468 bool removed;
1469 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1470 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1471 } else {
1472 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1473 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1474 }
1475 if (!removed) {
1476 LOG_AND_RETURN_ERROR(
1477 RTCErrorType::INVALID_PARAMETER,
1478 "Couldn't find sender " + sender->id() + " to remove.");
1479 }
Steve Anton4171afb2017-11-20 10:20:22 -08001480 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001481 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001482 return RTCError::OK();
1483}
1484
1485rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1486PeerConnection::FindTransceiverBySender(
1487 rtc::scoped_refptr<RtpSenderInterface> sender) {
1488 for (auto transceiver : transceivers_) {
1489 if (transceiver->sender() == sender) {
1490 return transceiver;
1491 }
1492 }
1493 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001494}
1495
Steve Anton9158ef62017-11-27 13:01:52 -08001496RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1497PeerConnection::AddTransceiver(
1498 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1499 return AddTransceiver(track, RtpTransceiverInit());
1500}
1501
1502RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1503PeerConnection::AddTransceiver(
1504 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1505 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001506 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001507 RTC_CHECK(IsUnifiedPlan())
1508 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001509 if (!track) {
1510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1511 }
1512 cricket::MediaType media_type;
1513 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1514 media_type = cricket::MEDIA_TYPE_AUDIO;
1515 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1516 media_type = cricket::MEDIA_TYPE_VIDEO;
1517 } else {
1518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1519 "Track kind is not audio or video");
1520 }
1521 return AddTransceiver(media_type, track, init);
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1526 return AddTransceiver(media_type, RtpTransceiverInit());
1527}
1528
1529RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1530PeerConnection::AddTransceiver(cricket::MediaType media_type,
1531 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001532 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001533 RTC_CHECK(IsUnifiedPlan())
1534 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001535 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1536 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1537 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1538 "media type is not audio or video");
1539 }
1540 return AddTransceiver(media_type, nullptr, init);
1541}
1542
1543RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1544PeerConnection::AddTransceiver(
1545 cricket::MediaType media_type,
1546 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001547 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001548 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001549 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1550 media_type == cricket::MEDIA_TYPE_VIDEO));
1551 if (track) {
1552 RTC_DCHECK_EQ(media_type,
1553 (track->kind() == MediaStreamTrackInterface::kAudioKind
1554 ? cricket::MEDIA_TYPE_AUDIO
1555 : cricket::MEDIA_TYPE_VIDEO));
1556 }
1557
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001558 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1559 init.send_encodings.size(), 0, 7, 8);
1560
Amit Hilbuchaa584152019-02-06 17:09:52 -08001561 size_t num_rids = absl::c_count_if(init.send_encodings,
1562 [](const RtpEncodingParameters& encoding) {
1563 return !encoding.rid.empty();
1564 });
1565 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001566 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001567 RTCErrorType::INVALID_PARAMETER,
1568 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001569 }
1570
Amit Hilbuchf4770402019-04-08 14:11:57 -07001571 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1572 [](const RtpEncodingParameters& encoding) {
1573 return !IsLegalRsidName(encoding.rid);
1574 })) {
1575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1576 "Invalid RID value provided.");
1577 }
1578
Amit Hilbuchaa584152019-02-06 17:09:52 -08001579 if (absl::c_any_of(init.send_encodings,
1580 [](const RtpEncodingParameters& encoding) {
1581 return encoding.ssrc.has_value();
1582 })) {
1583 LOG_AND_RETURN_ERROR(
1584 RTCErrorType::UNSUPPORTED_PARAMETER,
1585 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001586 }
1587
1588 RtpParameters parameters;
1589 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001590
1591 // Encodings are dropped from the tail if too many are provided.
1592 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1593 parameters.encodings.erase(
1594 parameters.encodings.begin() + kMaxSimulcastStreams,
1595 parameters.encodings.end());
1596 }
1597
1598 // Single RID should be removed.
1599 if (parameters.encodings.size() == 1 &&
1600 !parameters.encodings[0].rid.empty()) {
1601 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1602 parameters.encodings[0].rid.clear();
1603 }
1604
1605 // If RIDs were not provided, they are generated for simulcast scenario.
1606 if (parameters.encodings.size() > 1 && num_rids == 0) {
1607 rtc::UniqueStringGenerator rid_generator;
1608 for (RtpEncodingParameters& encoding : parameters.encodings) {
1609 encoding.rid = rid_generator();
1610 }
1611 }
1612
Florent Castelli892acf02018-10-01 22:47:20 +02001613 if (UnimplementedRtpParameterHasValue(parameters)) {
1614 LOG_AND_RETURN_ERROR(
1615 RTCErrorType::UNSUPPORTED_PARAMETER,
1616 "Attempted to set an unimplemented parameter of RtpParameters.");
1617 }
Steve Anton9158ef62017-11-27 13:01:52 -08001618
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001619 auto result = cricket::CheckRtpParametersValues(parameters);
1620 if (!result.ok()) {
1621 LOG_AND_RETURN_ERROR(result.type(), result.message());
1622 }
1623
Steve Anton3d954a62018-04-02 11:27:23 -07001624 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1625 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001626 // Set the sender ID equal to the track ID if the track is specified unless
1627 // that sender ID is already in use.
1628 std::string sender_id =
1629 (track && !FindSenderById(track->id()) ? track->id()
1630 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001631 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001632 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001633 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1634 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1635 transceiver->internal()->set_direction(init.direction);
1636
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001637 if (update_negotiation_needed) {
1638 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001639 }
Steve Antonf9381f02017-12-14 10:23:57 -08001640
1641 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1642}
1643
Steve Anton02ee47c2018-01-10 16:26:06 -08001644rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1645PeerConnection::CreateSender(
1646 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001647 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001648 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001649 const std::vector<std::string>& stream_ids,
1650 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001651 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001652 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001653 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1654 RTC_DCHECK(!track ||
1655 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1656 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1657 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001658 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001659 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001660 } else {
1661 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1662 RTC_DCHECK(!track ||
1663 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1664 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001665 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001666 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001668 bool set_track_succeeded = sender->SetTrack(track);
1669 RTC_DCHECK(set_track_succeeded);
1670 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001671 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001672 return sender;
1673}
1674
1675rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1676PeerConnection::CreateReceiver(cricket::MediaType media_type,
1677 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001678 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1679 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001680 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001681 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001682 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1683 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001684 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001685 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001686 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001687 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001688 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1689 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001690 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001691 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001692 return receiver;
1693}
1694
1695rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1696PeerConnection::CreateAndAddTransceiver(
1697 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1698 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1699 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001700 // Ensure that the new sender does not have an ID that is already in use by
1701 // another sender.
1702 // Allow receiver IDs to conflict since those come from remote SDP (which
1703 // could be invalid, but should not cause a crash).
1704 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001705 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001706 signaling_thread(),
1707 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001708 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001709 transceiver->internal()->SignalNegotiationNeeded.connect(
1710 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001711 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001712}
1713
Steve Anton52d86772018-02-20 15:48:12 -08001714void PeerConnection::OnNegotiationNeeded() {
1715 RTC_DCHECK_RUN_ON(signaling_thread());
1716 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001717 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001718}
1719
deadbeeffac06552015-11-25 11:26:01 -08001720rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001721 const std::string& kind,
1722 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001723 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001724 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1725 "Plan SdpSemantics. Please use AddTransceiver "
1726 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001727 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001728 if (IsClosed()) {
1729 return nullptr;
1730 }
Steve Anton4171afb2017-11-20 10:20:22 -08001731
Seth Hampson5b4f0752018-04-02 16:31:36 -07001732 // Internally we need to have one stream with Plan B semantics, so we
1733 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001734 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001735 if (stream_id.empty()) {
1736 stream_ids.push_back(rtc::CreateRandomUuid());
1737 RTC_LOG(LS_INFO)
1738 << "No stream_id specified for sender. Generated stream ID: "
1739 << stream_ids[0];
1740 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001741 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001742 }
1743
Steve Anton4171afb2017-11-20 10:20:22 -08001744 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001745 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001746 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001747 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001748 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001749 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001750 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001751 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001752 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001753 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001754 auto video_sender =
1755 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001756 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001757 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001758 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001759 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001760 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001762 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001763 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001764 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001765
deadbeefe1f9d832016-01-14 15:35:42 -08001766 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001767}
1768
deadbeef70ab1a12015-09-28 16:53:55 -07001769std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1770 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001771 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001772 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001773 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001774 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001775 }
1776 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001777}
1778
Steve Anton4171afb2017-11-20 10:20:22 -08001779std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1780PeerConnection::GetSendersInternal() const {
1781 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1782 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001783 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001784 auto senders = transceiver->internal()->senders();
1785 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1786 }
1787 return all_senders;
1788}
1789
deadbeef70ab1a12015-09-28 16:53:55 -07001790std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1791PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001792 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001793 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001794 for (const auto& receiver : GetReceiversInternal()) {
1795 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001796 }
1797 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001798}
1799
Steve Anton4171afb2017-11-20 10:20:22 -08001800std::vector<
1801 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1802PeerConnection::GetReceiversInternal() const {
1803 std::vector<
1804 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1805 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001806 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001807 auto receivers = transceiver->internal()->receivers();
1808 all_receivers.insert(all_receivers.end(), receivers.begin(),
1809 receivers.end());
1810 }
1811 return all_receivers;
1812}
1813
Steve Anton9158ef62017-11-27 13:01:52 -08001814std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1815PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001816 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001817 RTC_CHECK(IsUnifiedPlan())
1818 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001819 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001820 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001821 all_transceivers.push_back(transceiver);
1822 }
1823 return all_transceivers;
1824}
1825
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001827 MediaStreamTrackInterface* track,
1828 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001829 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001830 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001831 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001832 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 return false;
1834 }
1835
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001836 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001837 // The StatsCollector is used to tell if a track is valid because it may
1838 // remember tracks that the PeerConnection previously removed.
1839 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001840 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1841 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001842 return false;
1843 }
Steve Antonad182762018-09-05 20:22:40 +00001844 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1845 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 return true;
1847}
1848
hbos74e1a4f2016-09-15 23:33:01 -07001849void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001850 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001851 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001852 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001853 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001854 stats_collector_->GetStatsReport(callback);
1855}
1856
Henrik Boström1df1bf82018-03-20 13:24:20 +01001857void PeerConnection::GetStats(
1858 rtc::scoped_refptr<RtpSenderInterface> selector,
1859 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1860 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001861 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001862 RTC_DCHECK(callback);
1863 RTC_DCHECK(stats_collector_);
1864 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1865 if (selector) {
1866 for (const auto& proxy_transceiver : transceivers_) {
1867 for (const auto& proxy_sender :
1868 proxy_transceiver->internal()->senders()) {
1869 if (proxy_sender == selector) {
1870 internal_sender = proxy_sender->internal();
1871 break;
1872 }
1873 }
1874 if (internal_sender)
1875 break;
1876 }
1877 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001878 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001879 // belong to the PeerConnection (in Plan B, senders can be removed from the
1880 // PeerConnection). This means that "all the stats objects representing the
1881 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1882 // produces an empty stats report.
1883 stats_collector_->GetStatsReport(internal_sender, callback);
1884}
1885
1886void PeerConnection::GetStats(
1887 rtc::scoped_refptr<RtpReceiverInterface> selector,
1888 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1889 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001890 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001891 RTC_DCHECK(callback);
1892 RTC_DCHECK(stats_collector_);
1893 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1894 if (selector) {
1895 for (const auto& proxy_transceiver : transceivers_) {
1896 for (const auto& proxy_receiver :
1897 proxy_transceiver->internal()->receivers()) {
1898 if (proxy_receiver == selector) {
1899 internal_receiver = proxy_receiver->internal();
1900 break;
1901 }
1902 }
1903 if (internal_receiver)
1904 break;
1905 }
1906 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001907 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001908 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1909 // the PeerConnection). This means that "all the stats objects representing
1910 // the selector" is an empty set. Invoking GetStatsReport() with a null
1911 // selector produces an empty stats report.
1912 stats_collector_->GetStatsReport(internal_receiver, callback);
1913}
1914
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001916 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917 return signaling_state_;
1918}
1919
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920PeerConnectionInterface::IceConnectionState
1921PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001922 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001923 return ice_connection_state_;
1924}
1925
Alex Loiko9289eda2018-11-23 16:18:59 +00001926PeerConnectionInterface::IceConnectionState
1927PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001928 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001929 return standardized_ice_connection_state_;
1930}
1931
Jonas Olsson635474e2018-10-18 15:58:17 +02001932PeerConnectionInterface::PeerConnectionState
1933PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001934 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001935 return connection_state_;
1936}
1937
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938PeerConnectionInterface::IceGatheringState
1939PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001940 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 return ice_gathering_state_;
1942}
1943
Yves Gerey665174f2018-06-19 15:03:05 +02001944rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 const std::string& label,
1946 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001947 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001948 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001949
deadbeefab9b2d12015-10-14 11:33:11 -07001950 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001951
kwibergd1fe2812016-04-27 06:47:29 -07001952 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001953 if (config) {
1954 internal_config.reset(new InternalDataChannelInit(*config));
1955 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001956 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001957 InternalCreateDataChannel(label, internal_config.get()));
1958 if (!channel.get()) {
1959 return nullptr;
1960 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001962 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1963 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001964 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001965 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001966 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001967 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 return DataChannelProxy::Create(signaling_thread(), channel.get());
1969}
1970
1971void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001972 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001973 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001974 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001975
nisse7ce109a2017-01-31 00:57:56 -08001976 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001977 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001978 return;
1979 }
deadbeefab9b2d12015-10-14 11:33:11 -07001980
Steve Anton8d3444d2017-10-20 15:30:51 -07001981 if (IsClosed()) {
1982 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001983 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001984 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001985 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001986 return;
1987 }
1988
zhihuang1c378ed2017-08-17 14:10:50 -07001989 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001990 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001991 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001992 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001993 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001994 return;
1995 }
1996
Steve Anton22da89f2018-01-25 13:58:07 -08001997 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1998 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1999 if (IsUnifiedPlan()) {
2000 RTCError error = HandleLegacyOfferOptions(options);
2001 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002002 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002003 return;
2004 }
2005 }
2006
zhihuang1c378ed2017-08-17 14:10:50 -07002007 cricket::MediaSessionOptions session_options;
2008 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002009 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010}
2011
Steve Anton22da89f2018-01-25 13:58:07 -08002012RTCError PeerConnection::HandleLegacyOfferOptions(
2013 const RTCOfferAnswerOptions& options) {
2014 RTC_DCHECK(IsUnifiedPlan());
2015
2016 if (options.offer_to_receive_audio == 0) {
2017 RemoveRecvDirectionFromReceivingTransceiversOfType(
2018 cricket::MEDIA_TYPE_AUDIO);
2019 } else if (options.offer_to_receive_audio == 1) {
2020 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2021 } else if (options.offer_to_receive_audio > 1) {
2022 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2023 "offer_to_receive_audio > 1 is not supported.");
2024 }
2025
2026 if (options.offer_to_receive_video == 0) {
2027 RemoveRecvDirectionFromReceivingTransceiversOfType(
2028 cricket::MEDIA_TYPE_VIDEO);
2029 } else if (options.offer_to_receive_video == 1) {
2030 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2031 } else if (options.offer_to_receive_video > 1) {
2032 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2033 "offer_to_receive_video > 1 is not supported.");
2034 }
2035
2036 return RTCError::OK();
2037}
2038
2039void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2040 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002041 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002042 RtpTransceiverDirection new_direction =
2043 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2044 if (new_direction != transceiver->direction()) {
2045 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2046 << " transceiver (MID="
2047 << transceiver->mid().value_or("<not set>") << ") from "
2048 << RtpTransceiverDirectionToString(
2049 transceiver->direction())
2050 << " to "
2051 << RtpTransceiverDirectionToString(new_direction)
2052 << " since CreateOffer specified offer_to_receive=0";
2053 transceiver->internal()->set_direction(new_direction);
2054 }
Steve Anton22da89f2018-01-25 13:58:07 -08002055 }
2056}
2057
2058void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2059 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002060 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002061 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002062 RTC_LOG(LS_INFO)
2063 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2064 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002065 RtpTransceiverInit init;
2066 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002067 AddTransceiver(media_type, nullptr, init,
2068 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002069 }
2070}
2071
2072std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2073PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2074 std::vector<
2075 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2076 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002077 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002078 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002079 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2080 receiving_transceivers.push_back(transceiver);
2081 }
2082 }
2083 return receiving_transceivers;
2084}
2085
htaa2a49d92016-03-04 02:51:39 -08002086void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2087 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002088 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002089 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002090 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002091 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002092 return;
2093 }
2094
Steve Antondffead82018-02-06 10:31:29 -08002095 if (!(signaling_state_ == kHaveRemoteOffer ||
2096 signaling_state_ == kHaveLocalPrAnswer)) {
2097 std::string error =
2098 "PeerConnection cannot create an answer in a state other than "
2099 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002100 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002101 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002102 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002103 return;
2104 }
2105
Steve Antondffead82018-02-06 10:31:29 -08002106 // The remote description should be set if we're in the right state.
2107 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002108
Steve Anton22da89f2018-01-25 13:58:07 -08002109 if (IsUnifiedPlan()) {
2110 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2111 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2112 "supported with Unified Plan semantics. Use the "
2113 "RtpTransceiver API instead.";
2114 }
2115 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2116 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2117 "supported with Unified Plan semantics. Use the "
2118 "RtpTransceiver API instead.";
2119 }
2120 }
2121
htaa2a49d92016-03-04 02:51:39 -08002122 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002123 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002124
Steve Antond25da372017-11-06 14:50:29 -08002125 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126}
2127
2128void PeerConnection::SetLocalDescription(
2129 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002130 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002131 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002132 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002133
Steve Anton80dd7b52018-02-16 17:08:42 -08002134 // The SetLocalDescription contract is that we take ownership of the session
2135 // description regardless of the outcome, so wrap it in a unique_ptr right
2136 // away. Ideally, SetLocalDescription's signature will be changed to take the
2137 // description as a unique_ptr argument to formalize this agreement.
2138 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2139
nisse7ce109a2017-01-31 00:57:56 -08002140 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002141 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142 return;
2143 }
Steve Anton8a006912017-12-04 15:25:56 -08002144
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002146 PostSetSessionDescriptionFailure(
2147 observer,
2148 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 return;
2150 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002151
Steve Anton80dd7b52018-02-16 17:08:42 -08002152 // If a session error has occurred the PeerConnection is in a possibly
2153 // inconsistent state so fail right away.
2154 if (session_error() != SessionError::kNone) {
2155 std::string error_message = GetSessionErrorMsg();
2156 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << 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 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002162
Steve Anton80dd7b52018-02-16 17:08:42 -08002163 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2164 if (!error.ok()) {
2165 std::string error_message = GetSetDescriptionErrorMessage(
2166 cricket::CS_LOCAL, desc->GetType(), error);
2167 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002168 PostSetSessionDescriptionFailure(
2169 observer,
2170 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002171 return;
2172 }
2173
2174 // Grab the description type before moving ownership to ApplyLocalDescription,
2175 // which may destroy it before returning.
2176 const SdpType type = desc->GetType();
2177
2178 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002179 // |desc| may be destroyed at this point.
2180
2181 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002182 // If ApplyLocalDescription fails, the PeerConnection could be in an
2183 // inconsistent state, so act conservatively here and set the session error
2184 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2185 SetSessionError(SessionError::kContent, error.message());
2186 std::string error_message =
2187 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2188 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002189 PostSetSessionDescriptionFailure(
2190 observer,
2191 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002192 return;
2193 }
Steve Anton8a006912017-12-04 15:25:56 -08002194 RTC_DCHECK(local_description());
2195
2196 PostSetSessionDescriptionSuccess(observer);
2197
Steve Antonad182762018-09-05 20:22:40 +00002198 // MaybeStartGathering needs to be called after posting
2199 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2200 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002201 transport_controller_->MaybeStartGathering();
2202
Steve Antona3a92c22017-12-07 10:27:41 -08002203 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002204 // TODO(deadbeef): We already had to hop to the network thread for
2205 // MaybeStartGathering...
2206 network_thread()->Invoke<void>(
2207 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2208 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002209 // Make UMA notes about what was agreed to.
2210 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002211 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002212
2213 if (IsUnifiedPlan()) {
2214 bool was_negotiation_needed = is_negotiation_needed_;
2215 UpdateNegotiationNeeded();
2216 if (signaling_state() == kStable && was_negotiation_needed &&
2217 is_negotiation_needed_) {
2218 Observer()->OnRenegotiationNeeded();
2219 }
2220 }
2221
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002222 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002223}
2224
2225RTCError PeerConnection::ApplyLocalDescription(
2226 std::unique_ptr<SessionDescriptionInterface> desc) {
2227 RTC_DCHECK_RUN_ON(signaling_thread());
2228 RTC_DCHECK(desc);
2229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 // Update stats here so that we have the most recent stats for tracks and
2231 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002232 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002233
Steve Antondcc3c022017-12-22 16:02:54 -08002234 // Take a reference to the old local description since it's used below to
2235 // compare against the new local description. When setting the new local
2236 // description, grab ownership of the replaced session description in case it
2237 // is the same as |old_local_description|, to keep it alive for the duration
2238 // of the method.
2239 const SessionDescriptionInterface* old_local_description =
2240 local_description();
2241 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002242 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002243 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002244 replaced_local_description = pending_local_description_
2245 ? std::move(pending_local_description_)
2246 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002247 current_local_description_ = std::move(desc);
2248 pending_local_description_ = nullptr;
2249 current_remote_description_ = std::move(pending_remote_description_);
2250 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002251 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002252 pending_local_description_ = std::move(desc);
2253 }
2254 // The session description to apply now must be accessed by
2255 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002256 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002257
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002258 // Report statistics about any use of simulcast.
2259 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2260 *local_description()->description());
2261
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002262 if (!is_caller_) {
2263 if (remote_description()) {
2264 // Remote description was applied first, so this PC is the callee.
2265 is_caller_ = false;
2266 } else {
2267 // Local description is applied first, so this PC is the caller.
2268 is_caller_ = true;
2269 }
2270 }
2271
Zhi Huange830e682018-03-30 10:48:35 -07002272 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2273 if (!error.ok()) {
2274 return error;
2275 }
2276
Steve Antondcc3c022017-12-22 16:02:54 -08002277 if (IsUnifiedPlan()) {
2278 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002279 cricket::CS_LOCAL, *local_description(), old_local_description,
2280 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002281 if (!error.ok()) {
2282 return error;
2283 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002284 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2285 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002286 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002287 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2288 // Note that code paths that don't set MID won't be able to use
2289 // information about DTLS transports.
2290 if (transceiver->mid()) {
2291 auto dtls_transport =
2292 LookupDtlsTransportByMidInternal(*transceiver->mid());
2293 transceiver->internal()->sender_internal()->set_transport(
2294 dtls_transport);
2295 transceiver->internal()->receiver_internal()->set_transport(
2296 dtls_transport);
2297 }
2298
Steve Antondcc3c022017-12-22 16:02:54 -08002299 const ContentInfo* content =
2300 FindMediaSectionForTransceiver(transceiver, local_description());
2301 if (!content) {
2302 continue;
2303 }
2304 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002305 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2306 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002307 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002308 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2309 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2310 // "recvonly", process the removal of a remote track for the media
2311 // description, given transceiver, removeList, and muteTracks.
2312 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2313 (transceiver->internal()->fired_direction() &&
2314 RtpTransceiverDirectionHasRecv(
2315 *transceiver->internal()->fired_direction()))) {
2316 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2317 &removed_streams);
2318 }
2319 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2320 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002321 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002322 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002323 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002324 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002325 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002326 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002327 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002328 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002329 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002330 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002331 }
2332 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002333 // Media channels will be created only when offer is set. These may use new
2334 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002335 if (type == SdpType::kOffer) {
2336 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2337 // description is applied. Restore back to old description.
2338 RTCError error = CreateChannels(*local_description()->description());
2339 if (!error.ok()) {
2340 return error;
2341 }
2342 }
Steve Antondcc3c022017-12-22 16:02:54 -08002343 // Remove unused channels if MediaContentDescription is rejected.
2344 RemoveUnusedChannels(local_description()->description());
2345 }
Steve Anton8a006912017-12-04 15:25:56 -08002346
Zhi Huange830e682018-03-30 10:48:35 -07002347 error = UpdateSessionState(type, cricket::CS_LOCAL,
2348 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002349 if (!error.ok()) {
2350 return error;
2351 }
Steve Antondcc3c022017-12-22 16:02:54 -08002352
Steve Anton8a006912017-12-04 15:25:56 -08002353 if (remote_description()) {
2354 // Now that we have a local description, we can push down remote candidates.
2355 UseCandidatesInSessionDescription(remote_description());
2356 }
2357
2358 pending_ice_restarts_.clear();
2359 if (session_error() != SessionError::kNone) {
2360 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2361 }
2362
deadbeefab9b2d12015-10-14 11:33:11 -07002363 // If setting the description decided our SSL role, allocate any necessary
2364 // SCTP sids.
2365 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002366 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002367 AllocateSctpSids(role);
2368 }
2369
Steve Antond3679212018-01-17 17:41:02 -08002370 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002371 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002372 const ContentInfo* content =
2373 FindMediaSectionForTransceiver(transceiver, local_description());
2374 if (!content) {
2375 continue;
2376 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002377 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2378 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002379 // 0 is a special value meaning "this sender has no associated send
2380 // stream". Need to call this so the sender won't attempt to configure
2381 // a no longer existing stream and run into DCHECKs in the lower
2382 // layers.
2383 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002384 } else {
2385 // Get the StreamParams from the channel which could generate SSRCs.
2386 const std::vector<StreamParams>& streams = channel->local_streams();
2387 transceiver->internal()->sender_internal()->set_stream_ids(
2388 streams[0].stream_ids());
2389 transceiver->internal()->sender_internal()->SetSsrc(
2390 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002391 }
2392 }
2393 } else {
2394 // Plan B semantics.
2395
Steve Antondcc3c022017-12-22 16:02:54 -08002396 // Update state and SSRC of local MediaStreams and DataChannels based on the
2397 // local session description.
2398 const cricket::ContentInfo* audio_content =
2399 GetFirstAudioContent(local_description()->description());
2400 if (audio_content) {
2401 if (audio_content->rejected) {
2402 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2403 } else {
2404 const cricket::AudioContentDescription* audio_desc =
2405 audio_content->media_description()->as_audio();
2406 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2407 }
deadbeeffaac4972015-11-12 15:33:07 -08002408 }
deadbeefab9b2d12015-10-14 11:33:11 -07002409
Steve Antondcc3c022017-12-22 16:02:54 -08002410 const cricket::ContentInfo* video_content =
2411 GetFirstVideoContent(local_description()->description());
2412 if (video_content) {
2413 if (video_content->rejected) {
2414 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2415 } else {
2416 const cricket::VideoContentDescription* video_desc =
2417 video_content->media_description()->as_video();
2418 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2419 }
deadbeeffaac4972015-11-12 15:33:07 -08002420 }
deadbeefab9b2d12015-10-14 11:33:11 -07002421 }
2422
2423 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002424 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002425 if (data_content) {
Steve Anton46afbf92019-05-10 11:15:18 -07002426 const cricket::DataContentDescription* data_desc =
2427 data_content->media_description()->as_data();
2428 if (absl::StartsWith(data_desc->protocol(),
2429 cricket::kMediaProtocolRtpPrefix)) {
2430 UpdateLocalRtpDataChannels(data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002431 }
2432 }
2433
Steve Anton8a006912017-12-04 15:25:56 -08002434 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435}
2436
Steve Anton06817cd2018-12-18 15:55:30 -08002437// The SDP parser used to populate these values by default for the 'content
2438// name' if an a=mid line was absent.
2439static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2440 switch (media_type) {
2441 case cricket::MEDIA_TYPE_AUDIO:
2442 return cricket::CN_AUDIO;
2443 case cricket::MEDIA_TYPE_VIDEO:
2444 return cricket::CN_VIDEO;
2445 case cricket::MEDIA_TYPE_DATA:
2446 return cricket::CN_DATA;
2447 }
2448 RTC_NOTREACHED();
2449 return "";
2450}
2451
2452void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002453 cricket::SessionDescription* new_remote_description) {
2454 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002455 const cricket::ContentInfos& local_contents =
2456 (local_description() ? local_description()->description()->contents()
2457 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002458 const cricket::ContentInfos& remote_contents =
2459 (remote_description() ? remote_description()->description()->contents()
2460 : cricket::ContentInfos());
2461 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2462 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002463 if (!content.name.empty()) {
2464 continue;
2465 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002466 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002467 absl::string_view source_explanation;
2468 if (IsUnifiedPlan()) {
2469 if (i < local_contents.size()) {
2470 new_mid = local_contents[i].name;
2471 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002472 } else if (i < remote_contents.size()) {
2473 new_mid = remote_contents[i].name;
2474 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002475 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002476 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002477 source_explanation = "generated just now";
2478 }
2479 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002480 new_mid = std::string(
2481 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002482 source_explanation = "to match pre-existing behavior";
2483 }
Steve Antond7180cc2019-02-07 10:44:53 -08002484 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002485 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002486 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002487 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2488 << " is missing an a=mid line. Filling in the value '"
2489 << new_mid << "' " << source_explanation << ".";
2490 }
2491}
2492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002494 SetSessionDescriptionObserver* observer,
2495 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002496 SetRemoteDescription(
2497 std::unique_ptr<SessionDescriptionInterface>(desc),
2498 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2499 new SetRemoteDescriptionObserverAdapter(this, observer)));
2500}
2501
2502void PeerConnection::SetRemoteDescription(
2503 std::unique_ptr<SessionDescriptionInterface> desc,
2504 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002505 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002506 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002507
nisse7ce109a2017-01-31 00:57:56 -08002508 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002509 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002510 return;
2511 }
Steve Anton8a006912017-12-04 15:25:56 -08002512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002513 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002514 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002515 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 return;
2517 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002518
Steve Anton80dd7b52018-02-16 17:08:42 -08002519 // If a session error has occurred the PeerConnection is in a possibly
2520 // inconsistent state so fail right away.
2521 if (session_error() != SessionError::kNone) {
2522 std::string error_message = GetSessionErrorMsg();
2523 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2524 observer->OnSetRemoteDescriptionComplete(
2525 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2526 return;
2527 }
Steve Anton71439a62018-02-15 11:53:06 -08002528
Steve Antonba42e992018-04-09 14:10:01 -07002529 if (desc->GetType() == SdpType::kOffer) {
2530 // Report to UMA the format of the received offer.
2531 ReportSdpFormatReceived(*desc);
2532 }
2533
Steve Anton06817cd2018-12-18 15:55:30 -08002534 // Handle remote descriptions missing a=mid lines for interop with legacy end
2535 // points.
2536 FillInMissingRemoteMids(desc->description());
2537
Steve Anton80dd7b52018-02-16 17:08:42 -08002538 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002539 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002540 std::string error_message = GetSetDescriptionErrorMessage(
2541 cricket::CS_REMOTE, desc->GetType(), error);
2542 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002543 observer->OnSetRemoteDescriptionComplete(
2544 RTCError(error.type(), std::move(error_message)));
2545 return;
2546 }
Steve Anton71439a62018-02-15 11:53:06 -08002547
Steve Anton80dd7b52018-02-16 17:08:42 -08002548 // Grab the description type before moving ownership to
2549 // ApplyRemoteDescription, which may destroy it before returning.
2550 const SdpType type = desc->GetType();
2551
2552 error = ApplyRemoteDescription(std::move(desc));
2553 // |desc| may be destroyed at this point.
2554
2555 if (!error.ok()) {
2556 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2557 // inconsistent state, so act conservatively here and set the session error
2558 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2559 SetSessionError(SessionError::kContent, error.message());
2560 std::string error_message =
2561 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2562 RTC_LOG(LS_ERROR) << error_message;
2563 observer->OnSetRemoteDescriptionComplete(
2564 RTCError(error.type(), std::move(error_message)));
2565 return;
2566 }
2567 RTC_DCHECK(remote_description());
2568
2569 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002570 // TODO(deadbeef): We already had to hop to the network thread for
2571 // MaybeStartGathering...
2572 network_thread()->Invoke<void>(
2573 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2574 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002575 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002576 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002577 }
2578
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002579 if (IsUnifiedPlan()) {
2580 bool was_negotiation_needed = is_negotiation_needed_;
2581 UpdateNegotiationNeeded();
2582 if (signaling_state() == kStable && was_negotiation_needed &&
2583 is_negotiation_needed_) {
2584 Observer()->OnRenegotiationNeeded();
2585 }
2586 }
2587
Steve Anton8a006912017-12-04 15:25:56 -08002588 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002589 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002590}
2591
2592RTCError PeerConnection::ApplyRemoteDescription(
2593 std::unique_ptr<SessionDescriptionInterface> desc) {
2594 RTC_DCHECK_RUN_ON(signaling_thread());
2595 RTC_DCHECK(desc);
2596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597 // Update stats here so that we have the most recent stats for tracks and
2598 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002599 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002600
Steve Antondcc3c022017-12-22 16:02:54 -08002601 // Take a reference to the old remote description since it's used below to
2602 // compare against the new remote description. When setting the new remote
2603 // description, grab ownership of the replaced session description in case it
2604 // is the same as |old_remote_description|, to keep it alive for the duration
2605 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002606 const SessionDescriptionInterface* old_remote_description =
2607 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002608 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002609 SdpType type = desc->GetType();
2610 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002611 replaced_remote_description = pending_remote_description_
2612 ? std::move(pending_remote_description_)
2613 : std::move(current_remote_description_);
2614 current_remote_description_ = std::move(desc);
2615 pending_remote_description_ = nullptr;
2616 current_local_description_ = std::move(pending_local_description_);
2617 } else {
2618 replaced_remote_description = std::move(pending_remote_description_);
2619 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 }
Steve Anton8a006912017-12-04 15:25:56 -08002621 // The session description to apply now must be accessed by
2622 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002623 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002625 // Report statistics about any use of simulcast.
2626 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2627 *remote_description()->description());
2628
Zhi Huange830e682018-03-30 10:48:35 -07002629 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2630 if (!error.ok()) {
2631 return error;
2632 }
Steve Anton8a006912017-12-04 15:25:56 -08002633 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002634 if (IsUnifiedPlan()) {
2635 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002636 cricket::CS_REMOTE, *remote_description(), local_description(),
2637 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002638 if (!error.ok()) {
2639 return error;
2640 }
Steve Antondcc3c022017-12-22 16:02:54 -08002641 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002642 // Media channels will be created only when offer is set. These may use new
2643 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002644 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002645 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002646 // description is applied. Restore back to old description.
2647 RTCError error = CreateChannels(*remote_description()->description());
2648 if (!error.ok()) {
2649 return error;
2650 }
2651 }
Steve Antondcc3c022017-12-22 16:02:54 -08002652 // Remove unused channels if MediaContentDescription is rejected.
2653 RemoveUnusedChannels(remote_description()->description());
2654 }
Steve Anton8a006912017-12-04 15:25:56 -08002655
Zhi Huange830e682018-03-30 10:48:35 -07002656 // NOTE: Candidates allocation will be initiated only when
2657 // SetLocalDescription is called.
2658 error = UpdateSessionState(type, cricket::CS_REMOTE,
2659 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002660 if (!error.ok()) {
2661 return error;
2662 }
2663
2664 if (local_description() &&
2665 !UseCandidatesInSessionDescription(remote_description())) {
2666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2667 }
2668
2669 if (old_remote_description) {
2670 for (const cricket::ContentInfo& content :
2671 old_remote_description->description()->contents()) {
2672 // Check if this new SessionDescription contains new ICE ufrag and
2673 // password that indicates the remote peer requests an ICE restart.
2674 // TODO(deadbeef): When we start storing both the current and pending
2675 // remote description, this should reset pending_ice_restarts and compare
2676 // against the current description.
2677 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2678 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002679 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002680 pending_ice_restarts_.insert(content.name);
2681 }
2682 } else {
2683 // We retain all received candidates only if ICE is not restarted.
2684 // When ICE is restarted, all previous candidates belong to an old
2685 // generation and should not be kept.
2686 // TODO(deadbeef): This goes against the W3C spec which says the remote
2687 // description should only contain candidates from the last set remote
2688 // description plus any candidates added since then. We should remove
2689 // this once we're sure it won't break anything.
2690 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2691 old_remote_description, content.name, mutable_remote_description());
2692 }
2693 }
2694 }
2695
2696 if (session_error() != SessionError::kNone) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2698 }
2699
2700 // Set the the ICE connection state to connecting since the connection may
2701 // become writable with peer reflexive candidates before any remote candidate
2702 // is signaled.
2703 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2704 // is to have a new signal the indicates a change in checking state from the
2705 // transport and expose a new checking() member from transport that can be
2706 // read to determine the current checking state. The existing SignalConnecting
2707 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002708 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002709 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002710 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2711 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2712 }
2713
deadbeefab9b2d12015-10-14 11:33:11 -07002714 // If setting the description decided our SSL role, allocate any necessary
2715 // SCTP sids.
2716 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002717 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002718 AllocateSctpSids(role);
2719 }
2720
Steve Antondcc3c022017-12-22 16:02:54 -08002721 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002722 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002723 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002724 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002725 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002726 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002727 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002728 const ContentInfo* content =
2729 FindMediaSectionForTransceiver(transceiver, remote_description());
2730 if (!content) {
2731 continue;
2732 }
2733 const MediaContentDescription* media_desc = content->media_description();
2734 RtpTransceiverDirection local_direction =
2735 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002736 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2737 // RTCSessionDescription: Set the associated remote streams given
2738 // transceiver.[[Receiver]], msids, addList, and removeList".
2739 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2740 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2741 std::vector<std::string> stream_ids;
2742 if (!media_desc->streams().empty()) {
2743 // The remote description has signaled the stream IDs.
2744 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002745 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002746 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2747 << " (" << GetStreamIdsString(stream_ids) << ").";
2748 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2749 stream_ids, &added_streams,
2750 &removed_streams);
2751 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2752 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2753 // and transceiver's current direction is neither sendrecv nor recvonly,
2754 // process the addition of a remote track for the media description.
2755 if (!transceiver->fired_direction() ||
2756 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2757 RTC_LOG(LS_INFO)
2758 << "Processing the addition of a remote track for MID="
2759 << content->name << ".";
2760 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002761 }
Steve Antondcc3c022017-12-22 16:02:54 -08002762 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002763 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002764 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2765 // removal of a remote track for the media description, given transceiver,
2766 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002767 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002768 (transceiver->fired_direction() &&
2769 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2770 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2771 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002772 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002773 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002774 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002775 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002776 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002777 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002778 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002779 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002780 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002781 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2782 if (transceiver->mid()) {
2783 auto dtls_transport =
2784 LookupDtlsTransportByMidInternal(*transceiver->mid());
2785 transceiver->internal()->sender_internal()->set_transport(
2786 dtls_transport);
2787 transceiver->internal()->receiver_internal()->set_transport(
2788 dtls_transport);
2789 }
Steve Antondcc3c022017-12-22 16:02:54 -08002790 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002791 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002792 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002793 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002794 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2795 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002796 transceiver->Stop();
2797 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002798 if (!content->rejected &&
2799 RtpTransceiverDirectionHasRecv(local_direction)) {
2800 // Set ssrc to 0 in the case of an unsignalled ssrc.
2801 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002802 if (!media_desc->streams().empty() &&
2803 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002804 ssrc = media_desc->streams()[0].first_ssrc();
2805 }
2806 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002807 }
Steve Antondcc3c022017-12-22 16:02:54 -08002808 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002809 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002810 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002811 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002812 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002813 observer->OnTrack(transceiver);
2814 observer->OnAddTrack(transceiver->receiver(),
2815 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002816 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002817 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002818 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002819 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002820 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002821 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002822 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002823 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002824 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002825 }
Steve Antondcc3c022017-12-22 16:02:54 -08002826 }
2827
Henrik Boströmfdb92012017-11-09 19:55:44 +01002828 const cricket::ContentInfo* audio_content =
2829 GetFirstAudioContent(remote_description()->description());
2830 const cricket::ContentInfo* video_content =
2831 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002832 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002833 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002834 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002835 GetFirstVideoContentDescription(remote_description()->description());
Steve Anton46afbf92019-05-10 11:15:18 -07002836 const cricket::DataContentDescription* data_desc =
2837 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002838
2839 // Check if the descriptions include streams, just in case the peer supports
2840 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002841 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002842 (audio_desc && !audio_desc->streams().empty()) ||
2843 (video_desc && !video_desc->streams().empty())) {
2844 remote_peer_supports_msid_ = true;
2845 }
deadbeefab9b2d12015-10-14 11:33:11 -07002846
2847 // We wait to signal new streams until we finish processing the description,
2848 // since only at that point will new streams have all their tracks.
2849 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2850
Steve Antondcc3c022017-12-22 16:02:54 -08002851 if (!IsUnifiedPlan()) {
2852 // TODO(steveanton): When removing RTP senders/receivers in response to a
2853 // rejected media section, there is some cleanup logic that expects the
2854 // voice/ video channel to still be set. But in this method the voice/video
2855 // channel would have been destroyed by the SetRemoteDescription caller
2856 // above so the cleanup that relies on them fails to run. The RemoveSenders
2857 // calls should be moved to right before the DestroyChannel calls to fix
2858 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002859
Steve Antondcc3c022017-12-22 16:02:54 -08002860 // Find all audio rtp streams and create corresponding remote AudioTracks
2861 // and MediaStreams.
2862 if (audio_content) {
2863 if (audio_content->rejected) {
2864 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2865 } else {
2866 bool default_audio_track_needed =
2867 !remote_peer_supports_msid_ &&
2868 RtpTransceiverDirectionHasSend(audio_desc->direction());
2869 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2870 default_audio_track_needed, audio_desc->type(),
2871 new_streams);
2872 }
deadbeeffaac4972015-11-12 15:33:07 -08002873 }
deadbeefab9b2d12015-10-14 11:33:11 -07002874
Steve Antondcc3c022017-12-22 16:02:54 -08002875 // Find all video rtp streams and create corresponding remote VideoTracks
2876 // and MediaStreams.
2877 if (video_content) {
2878 if (video_content->rejected) {
2879 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2880 } else {
2881 bool default_video_track_needed =
2882 !remote_peer_supports_msid_ &&
2883 RtpTransceiverDirectionHasSend(video_desc->direction());
2884 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2885 default_video_track_needed, video_desc->type(),
2886 new_streams);
2887 }
deadbeeffaac4972015-11-12 15:33:07 -08002888 }
deadbeefab9b2d12015-10-14 11:33:11 -07002889
Steve Anton46afbf92019-05-10 11:15:18 -07002890 // Update the DataChannels with the information from the remote peer.
2891 if (data_desc) {
2892 if (absl::StartsWith(data_desc->protocol(),
2893 cricket::kMediaProtocolRtpPrefix)) {
2894 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2895 }
deadbeefab9b2d12015-10-14 11:33:11 -07002896 }
deadbeefab9b2d12015-10-14 11:33:11 -07002897
Steve Antondcc3c022017-12-22 16:02:54 -08002898 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002899 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002900 for (size_t i = 0; i < new_streams->count(); ++i) {
2901 MediaStreamInterface* new_stream = new_streams->at(i);
2902 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002903 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002904 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2905 }
deadbeefab9b2d12015-10-14 11:33:11 -07002906
Steve Antondcc3c022017-12-22 16:02:54 -08002907 UpdateEndedRemoteMediaStreams();
2908 }
deadbeefab9b2d12015-10-14 11:33:11 -07002909
Steve Anton8a006912017-12-04 15:25:56 -08002910 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002911}
2912
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002913void PeerConnection::SetAssociatedRemoteStreams(
2914 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2915 const std::vector<std::string>& stream_ids,
2916 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2917 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2918 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2919 for (const std::string& stream_id : stream_ids) {
2920 rtc::scoped_refptr<MediaStreamInterface> stream =
2921 remote_streams_->find(stream_id);
2922 if (!stream) {
2923 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2924 MediaStream::Create(stream_id));
2925 remote_streams_->AddStream(stream);
2926 added_streams->push_back(stream);
2927 }
2928 media_streams.push_back(stream);
2929 }
2930 // Special case: "a=msid" missing, use random stream ID.
2931 if (media_streams.empty() &&
2932 !(remote_description()->description()->msid_signaling() &
2933 cricket::kMsidSignalingMediaSection)) {
2934 if (!missing_msid_default_stream_) {
2935 missing_msid_default_stream_ = MediaStreamProxy::Create(
2936 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2937 added_streams->push_back(missing_msid_default_stream_);
2938 }
2939 media_streams.push_back(missing_msid_default_stream_);
2940 }
2941 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2942 receiver->streams();
2943 // SetStreams() will add/remove the receiver's track to/from the streams. This
2944 // differs from the spec - the spec uses an "addList" and "removeList" to
2945 // update the stream-track relationships in a later step. We do this earlier,
2946 // changing the order of things, but the end-result is the same.
2947 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2948 // instead. https://crbug.com/webrtc/9480
2949 receiver->SetStreams(media_streams);
2950 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2951}
2952
Steve Anton0f5400a2018-07-17 14:25:36 -07002953void PeerConnection::ProcessRemovalOfRemoteTrack(
2954 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2955 transceiver,
2956 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2957 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2958 RTC_DCHECK(transceiver->mid());
2959 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2960 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002961 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002962 transceiver->internal()->receiver_internal()->streams();
2963 // This will remove the remote track from the streams.
2964 transceiver->internal()->receiver_internal()->set_stream_ids({});
2965 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002966 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2967}
2968
2969void PeerConnection::RemoveRemoteStreamsIfEmpty(
2970 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2971 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2972 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2973 // streams, see if the stream was removed by checking if this was the last
2974 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002975 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002976 if (remote_stream->GetAudioTracks().empty() &&
2977 remote_stream->GetVideoTracks().empty()) {
2978 remote_streams_->RemoveStream(remote_stream);
2979 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002980 }
2981 }
2982}
2983
Steve Antondcc3c022017-12-22 16:02:54 -08002984RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2985 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002986 const SessionDescriptionInterface& new_session,
2987 const SessionDescriptionInterface* old_local_description,
2988 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002989 RTC_DCHECK(IsUnifiedPlan());
2990
Steve Anton7464fca2018-01-19 11:10:37 -08002991 const cricket::ContentGroup* bundle_group = nullptr;
2992 if (new_session.GetType() == SdpType::kOffer) {
2993 auto bundle_group_or_error =
2994 GetEarlyBundleGroup(*new_session.description());
2995 if (!bundle_group_or_error.ok()) {
2996 return bundle_group_or_error.MoveError();
2997 }
2998 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002999 }
Steve Antondcc3c022017-12-22 16:02:54 -08003000
Steve Antondcc3c022017-12-22 16:02:54 -08003001 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003002 for (size_t i = 0; i < new_contents.size(); ++i) {
3003 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003004 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003005 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003006 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3007 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003008 const cricket::ContentInfo* old_local_content = nullptr;
3009 if (old_local_description &&
3010 i < old_local_description->description()->contents().size()) {
3011 old_local_content =
3012 &old_local_description->description()->contents()[i];
3013 }
3014 const cricket::ContentInfo* old_remote_content = nullptr;
3015 if (old_remote_description &&
3016 i < old_remote_description->description()->contents().size()) {
3017 old_remote_content =
3018 &old_remote_description->description()->contents()[i];
3019 }
Steve Antondcc3c022017-12-22 16:02:54 -08003020 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003021 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3022 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003023 if (!transceiver_or_error.ok()) {
3024 return transceiver_or_error.MoveError();
3025 }
3026 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003027 RTCError error =
3028 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3029 if (!error.ok()) {
3030 return error;
3031 }
3032 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003033 if (GetDataMid() && new_content.name != *GetDataMid()) {
3034 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003035 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3036 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003037 continue;
3038 }
3039 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3040 if (!error.ok()) {
3041 return error;
3042 }
Steve Antondcc3c022017-12-22 16:02:54 -08003043 } else {
3044 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3045 "Unknown section type.");
3046 }
3047 }
3048
3049 return RTCError::OK();
3050}
3051
3052RTCError PeerConnection::UpdateTransceiverChannel(
3053 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3054 transceiver,
3055 const cricket::ContentInfo& content,
3056 const cricket::ContentGroup* bundle_group) {
3057 RTC_DCHECK(IsUnifiedPlan());
3058 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003059 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003060 if (content.rejected) {
3061 if (channel) {
3062 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003063 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003064 }
3065 } else {
3066 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003067 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003068 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003069 } else {
Steve Anton69470252018-02-09 11:43:08 -08003070 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003071 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003072 }
3073 if (!channel) {
3074 LOG_AND_RETURN_ERROR(
3075 RTCErrorType::INTERNAL_ERROR,
3076 "Failed to create channel for mid=" + content.name);
3077 }
3078 transceiver->internal()->SetChannel(channel);
3079 }
3080 }
3081 return RTCError::OK();
3082}
3083
Steve Antonfa2260d2017-12-28 16:38:23 -08003084RTCError PeerConnection::UpdateDataChannel(
3085 cricket::ContentSource source,
3086 const cricket::ContentInfo& content,
3087 const cricket::ContentGroup* bundle_group) {
3088 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003089 // If data channels are disabled, ignore this media section. CreateAnswer
3090 // will take care of rejecting it.
3091 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003092 }
3093 if (content.rejected) {
3094 DestroyDataChannel();
3095 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003096 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003097 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003098 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3099 "Failed to create data channel.");
3100 }
3101 }
3102 if (source == cricket::CS_REMOTE) {
3103 const MediaContentDescription* data_desc = content.media_description();
3104 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3105 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3106 }
3107 }
3108 }
3109 return RTCError::OK();
3110}
3111
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003112// This method will extract any send encodings that were sent by the remote
3113// connection. This is currently only relevant for Simulcast scenario (where
3114// the number of layers may be communicated by the server).
3115static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3116 const MediaContentDescription& desc) {
3117 if (!desc.HasSimulcast()) {
3118 return {};
3119 }
3120 std::vector<RtpEncodingParameters> result;
3121 const SimulcastDescription& simulcast = desc.simulcast_description();
3122
3123 // This is a remote description, the parameters we are after should appear
3124 // as receive streams.
3125 for (const auto& alternatives : simulcast.receive_layers()) {
3126 RTC_DCHECK(!alternatives.empty());
3127 // There is currently no way to specify or choose from alternatives.
3128 // We will always use the first alternative, which is the most preferred.
3129 const SimulcastLayer& layer = alternatives[0];
3130 RtpEncodingParameters parameters;
3131 parameters.rid = layer.rid;
3132 parameters.active = !layer.is_paused;
3133 result.push_back(parameters);
3134 }
3135
3136 return result;
3137}
3138
3139static RTCError UpdateSimulcastLayerStatusInSender(
3140 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003141 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003142 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003143 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003144 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003145
3146 // The simulcast envelope cannot be changed, only the status of the streams.
3147 // So we will iterate over the send encodings rather than the layers.
3148 for (RtpEncodingParameters& encoding : parameters.encodings) {
3149 auto iter = std::find_if(layers.begin(), layers.end(),
3150 [&encoding](const SimulcastLayer& layer) {
3151 return layer.rid == encoding.rid;
3152 });
3153 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003154 if (iter == layers.end()) {
3155 disabled_layers.push_back(encoding.rid);
3156 continue;
3157 }
3158
3159 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003160 }
3161
Amit Hilbuch619b2942019-02-26 15:55:19 -08003162 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003163 if (result.ok()) {
3164 result = sender->DisableEncodingLayers(disabled_layers);
3165 }
3166
3167 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003168}
3169
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003170static bool SimulcastIsRejected(
3171 const ContentInfo* local_content,
3172 const MediaContentDescription& answer_media_desc) {
3173 bool simulcast_offered = local_content &&
3174 local_content->media_description() &&
3175 local_content->media_description()->HasSimulcast();
3176 bool simulcast_answered = answer_media_desc.HasSimulcast();
3177 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3178 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3179 return simulcast_offered && (!simulcast_answered || !rids_supported);
3180}
3181
Amit Hilbuch2297d332019-02-19 12:49:22 -08003182static RTCError DisableSimulcastInSender(
3183 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003184 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003185 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003186 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003187 return RTCError::OK();
3188 }
3189
Amit Hilbuch2297d332019-02-19 12:49:22 -08003190 std::vector<std::string> disabled_layers;
3191 std::transform(
3192 parameters.encodings.begin() + 1, parameters.encodings.end(),
3193 std::back_inserter(disabled_layers),
3194 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3195 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003196}
3197
Steve Antondcc3c022017-12-22 16:02:54 -08003198RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3199PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003200 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003201 size_t mline_index,
3202 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003203 const ContentInfo* old_local_content,
3204 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003205 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003206 // If this is an offer then the m= section might be recycled. If the m=
3207 // section is being recycled (defined as: rejected in the current local or
3208 // remote description and not rejected in new description), dissociate the
3209 // currently associated RtpTransceiver by setting its mid property to null,
3210 // and discard the mapping between the transceiver and its m= section index.
3211 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3212 old_remote_content)) {
3213 // We want to dissociate the transceiver that has the rejected mid.
3214 const std::string& old_mid =
3215 (old_local_content && old_local_content->rejected)
3216 ? old_local_content->name
3217 : old_remote_content->name;
3218 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003219 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003220 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3221 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003222 old_transceiver->internal()->set_mid(absl::nullopt);
3223 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003224 }
3225 }
3226 const MediaContentDescription* media_desc = content.media_description();
3227 auto transceiver = GetAssociatedTransceiver(content.name);
3228 if (source == cricket::CS_LOCAL) {
3229 // Find the RtpTransceiver that corresponds to this m= section, using the
3230 // mapping between transceivers and m= section indices established when
3231 // creating the offer.
3232 if (!transceiver) {
3233 transceiver = GetTransceiverByMLineIndex(mline_index);
3234 }
3235 if (!transceiver) {
3236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3237 "Unknown transceiver");
3238 }
3239 } else {
3240 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3241 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3242 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003243 // When simulcast is requested, a transceiver cannot be associated because
3244 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003245 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003246 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3247 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003248 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3249 }
3250 // If no RtpTransceiver was found in the previous step, create one with a
3251 // recvonly direction.
3252 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003253 RTC_LOG(LS_INFO) << "Adding "
3254 << cricket::MediaTypeToString(media_desc->type())
3255 << " transceiver for MID=" << content.name
3256 << " at i=" << mline_index
3257 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003258 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003259 std::vector<RtpEncodingParameters> send_encodings =
3260 GetSendEncodingsFromRemoteDescription(*media_desc);
3261 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3262 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003263 std::string receiver_id;
3264 if (!media_desc->streams().empty()) {
3265 receiver_id = media_desc->streams()[0].id;
3266 } else {
3267 receiver_id = rtc::CreateRandomUuid();
3268 }
3269 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003270 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003271 transceiver->internal()->set_direction(
3272 RtpTransceiverDirection::kRecvOnly);
3273 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003274
3275 // Check if the offer indicated simulcast but the answer rejected it.
3276 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003277 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003278 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003279 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003280 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003281 if (!error.ok()) {
3282 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3283 return std::move(error);
3284 }
3285 }
Steve Antondcc3c022017-12-22 16:02:54 -08003286 }
3287 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003288 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003289 LOG_AND_RETURN_ERROR(
3290 RTCErrorType::INVALID_PARAMETER,
3291 "Transceiver type does not match media description type.");
3292 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003293 if (media_desc->HasSimulcast()) {
3294 std::vector<SimulcastLayer> layers =
3295 source == cricket::CS_LOCAL
3296 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3297 : media_desc->simulcast_description()
3298 .receive_layers()
3299 .GetAllLayers();
3300 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003301 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003302 if (!error.ok()) {
3303 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3304 return std::move(error);
3305 }
3306 }
Steve Antondcc3c022017-12-22 16:02:54 -08003307 // Associate the found or created RtpTransceiver with the m= section by
3308 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3309 // section, and establish a mapping between the transceiver and the index of
3310 // the m= section.
3311 transceiver->internal()->set_mid(content.name);
3312 transceiver->internal()->set_mline_index(mline_index);
3313 return std::move(transceiver);
3314}
3315
3316rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3317PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3318 RTC_DCHECK(IsUnifiedPlan());
3319 for (auto transceiver : transceivers_) {
3320 if (transceiver->mid() == mid) {
3321 return transceiver;
3322 }
3323 }
3324 return nullptr;
3325}
3326
3327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3328PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3329 RTC_DCHECK(IsUnifiedPlan());
3330 for (auto transceiver : transceivers_) {
3331 if (transceiver->internal()->mline_index() == mline_index) {
3332 return transceiver;
3333 }
3334 }
3335 return nullptr;
3336}
3337
3338rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3339PeerConnection::FindAvailableTransceiverToReceive(
3340 cricket::MediaType media_type) const {
3341 RTC_DCHECK(IsUnifiedPlan());
3342 // From JSEP section 5.10 (Applying a Remote Description):
3343 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3344 // the same type that were added to the PeerConnection by addTrack and are not
3345 // associated with any m= section and are not stopped, find the first such
3346 // RtpTransceiver.
3347 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003348 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003349 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3350 !transceiver->stopped()) {
3351 return transceiver;
3352 }
3353 }
3354 return nullptr;
3355}
3356
Steve Antoned10bd92017-12-05 10:52:59 -08003357const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3358 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3359 transceiver,
3360 const SessionDescriptionInterface* sdesc) const {
3361 RTC_DCHECK(transceiver);
3362 RTC_DCHECK(sdesc);
3363 if (IsUnifiedPlan()) {
3364 if (!transceiver->internal()->mid()) {
3365 // This transceiver is not associated with a media section yet.
3366 return nullptr;
3367 }
3368 return sdesc->description()->GetContentByName(
3369 *transceiver->internal()->mid());
3370 } else {
3371 // Plan B only allows at most one audio and one video section, so use the
3372 // first media section of that type.
3373 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003374 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003375 }
3376}
3377
deadbeef46c73892016-11-16 19:42:04 -08003378PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003379 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003380 return configuration_;
3381}
3382
deadbeef293e9262017-01-11 12:28:30 -08003383bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3384 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003385 RTC_DCHECK_RUN_ON(signaling_thread());
3386 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003387 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003388 if (IsClosed()) {
3389 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3390 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3391 }
3392
Qingsi Wanga2d60672018-04-11 16:57:45 -07003393 // According to JSEP, after setLocalDescription, changing the candidate pool
3394 // size is not allowed, and changing the set of ICE servers will not result
3395 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003396 if (local_description() && configuration.ice_candidate_pool_size !=
3397 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003398 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3399 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003400 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003401 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003402
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003403 if (local_description() &&
3404 configuration.use_media_transport != configuration_.use_media_transport) {
3405 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3406 "SetLocalDescription.";
3407 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3408 }
3409
3410 if (remote_description() &&
3411 configuration.use_media_transport != configuration_.use_media_transport) {
3412 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3413 "SetRemoteDescription.";
3414 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3415 }
3416
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003417 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003418 configuration.use_media_transport_for_data_channels !=
3419 configuration_.use_media_transport_for_data_channels) {
3420 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3421 "after calling SetLocalDescription.";
3422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3423 }
3424
3425 if (remote_description() &&
3426 configuration.use_media_transport_for_data_channels !=
3427 configuration_.use_media_transport_for_data_channels) {
3428 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3429 "after calling SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
3433 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003434 configuration.crypto_options != configuration_.crypto_options) {
3435 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3436 "SetLocalDescription.";
3437 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3438 }
3439
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003440 if (configuration.use_media_transport_for_data_channels ||
3441 configuration.use_media_transport) {
3442 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3443 << "Media transport requires MaxBundle policy.";
3444 }
3445
deadbeef293e9262017-01-11 12:28:30 -08003446 // The simplest (and most future-compatible) way to tell if the config was
3447 // modified in an invalid way is to copy each property we do support
3448 // modifying, then use operator==. There are far more properties we don't
3449 // support modifying than those we do, and more could be added.
3450 RTCConfiguration modified_config = configuration_;
3451 modified_config.servers = configuration.servers;
3452 modified_config.type = configuration.type;
3453 modified_config.ice_candidate_pool_size =
3454 configuration.ice_candidate_pool_size;
3455 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003456 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003457 modified_config.ice_check_interval_strong_connectivity =
3458 configuration.ice_check_interval_strong_connectivity;
3459 modified_config.ice_check_interval_weak_connectivity =
3460 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003461 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3462 modified_config.ice_unwritable_min_checks =
3463 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003464 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003465 modified_config.stun_candidate_keepalive_interval =
3466 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003467 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003468 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003469 modified_config.active_reset_srtp_params =
3470 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003471 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003472 modified_config.use_media_transport_for_data_channels =
3473 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003474 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003475 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003476 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3477 }
3478
Steve Anton038834f2017-07-14 15:59:59 -07003479 // Validate the modified configuration.
3480 RTCError validate_error = ValidateConfiguration(modified_config);
3481 if (!validate_error.ok()) {
3482 return SafeSetError(std::move(validate_error), error);
3483 }
3484
deadbeef293e9262017-01-11 12:28:30 -08003485 // Note that this isn't possible through chromium, since it's an unsigned
3486 // short in WebIDL.
3487 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003488 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003489 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3490 }
3491
3492 // Parse ICE servers before hopping to network thread.
3493 cricket::ServerAddresses stun_servers;
3494 std::vector<cricket::RelayServerConfig> turn_servers;
3495 RTCErrorType parse_error =
3496 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3497 if (parse_error != RTCErrorType::NONE) {
3498 return SafeSetError(parse_error, error);
3499 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003500 // Note if STUN or TURN servers were supplied.
3501 if (!stun_servers.empty()) {
3502 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3503 }
3504 if (!turn_servers.empty()) {
3505 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3506 }
deadbeef293e9262017-01-11 12:28:30 -08003507
3508 // In theory this shouldn't fail.
3509 if (!network_thread()->Invoke<bool>(
3510 RTC_FROM_HERE,
3511 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3512 stun_servers, turn_servers, modified_config.type,
3513 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003514 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003515 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003516 modified_config.stun_candidate_keepalive_interval,
3517 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003518 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003519 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3520 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003521
deadbeefd1a38b52016-12-10 13:15:33 -08003522 // As described in JSEP, calling setConfiguration with new ICE servers or
3523 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3524 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003525 if (modified_config.servers != configuration_.servers ||
3526 modified_config.type != configuration_.type ||
3527 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003528 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003529 }
skvladd1f5fda2017-02-03 16:54:05 -08003530
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003531 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003532 transport_controller_->SetMediaTransportSettings(
3533 modified_config.use_media_transport,
3534 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003535
Zhi Huangb57e1692018-06-12 11:41:11 -07003536 if (configuration_.active_reset_srtp_params !=
3537 modified_config.active_reset_srtp_params) {
3538 transport_controller_->SetActiveResetSrtpParams(
3539 modified_config.active_reset_srtp_params);
3540 }
3541
deadbeef293e9262017-01-11 12:28:30 -08003542 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003543 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003544 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003545}
3546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547bool PeerConnection::AddIceCandidate(
3548 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003549 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003550 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003551 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003552 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003553 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003554 return false;
3555 }
Steve Antond25da372017-11-06 14:50:29 -08003556
3557 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003558 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003559 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003560 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003561 return false;
3562 }
3563
3564 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003565 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003566 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003567 return false;
3568 }
3569
3570 bool valid = false;
3571 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3572 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003573 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003574 return false;
3575 }
3576
3577 // Add this candidate to the remote session description.
3578 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003579 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003580 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003581 return false;
3582 }
3583
3584 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003585 bool result = UseCandidate(ice_candidate);
3586 if (result) {
3587 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003588 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3589 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3590 }
3591 if (ice_candidate->candidate().address().IsPrivateIP()) {
3592 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3593 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003594 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3595 } else {
3596 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3597 }
3598 return result;
Steve Antond25da372017-11-06 14:50:29 -08003599 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003600 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003601 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003602 return true;
3603 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003604}
3605
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003606bool PeerConnection::RemoveIceCandidates(
3607 const std::vector<cricket::Candidate>& candidates) {
3608 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003609 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003610 if (IsClosed()) {
3611 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3612 return false;
3613 }
3614
Steve Antond25da372017-11-06 14:50:29 -08003615 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003616 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3617 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003618 return false;
3619 }
3620
3621 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003622 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003623 return false;
3624 }
3625
3626 size_t number_removed =
3627 mutable_remote_description()->RemoveCandidates(candidates);
3628 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003629 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003630 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003631 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003632 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003633 }
3634
3635 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003636 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3637 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003638 RTC_LOG(LS_ERROR)
3639 << "RemoveIceCandidates: Error when removing remote candidates: "
3640 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003641 }
3642 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003643}
3644
Niels Möller0c4f7be2018-05-07 14:01:37 +02003645RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003646 if (!worker_thread()->IsCurrent()) {
3647 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003648 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003649 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003650 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003651
Niels Möller0c4f7be2018-05-07 14:01:37 +02003652 const bool has_min = bitrate.min_bitrate_bps.has_value();
3653 const bool has_start = bitrate.start_bitrate_bps.has_value();
3654 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003655 if (has_min && *bitrate.min_bitrate_bps < 0) {
3656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3657 "min_bitrate_bps <= 0");
3658 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003659 if (has_start) {
3660 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003661 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003662 "start_bitrate_bps < min_bitrate_bps");
3663 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3665 "curent_bitrate_bps < 0");
3666 }
3667 }
3668 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003669 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003671 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003672 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3674 "max_bitrate_bps < min_bitrate_bps");
3675 } else if (*bitrate.max_bitrate_bps < 0) {
3676 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3677 "max_bitrate_bps < 0");
3678 }
3679 }
3680
zstein4b979802017-06-02 14:37:37 -07003681 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003682 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003683
3684 return RTCError::OK();
3685}
3686
Alex Narest78609d52017-10-20 10:37:47 +02003687void PeerConnection::SetBitrateAllocationStrategy(
3688 std::unique_ptr<rtc::BitrateAllocationStrategy>
3689 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003690 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003691 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3692 // move-capture values in lambdas.
3693 struct Task {
3694 PeerConnection* const pc;
3695 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3696 void operator()() {
3697 RTC_DCHECK_RUN_ON(pc->worker_thread());
3698 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3699 }
3700 };
3701 worker_thread()->Invoke<void>(
3702 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003703 return;
3704 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003705 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003706 RTC_DCHECK(call_.get());
3707 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3708}
3709
henrika5f6bf242017-11-01 11:06:56 +01003710void PeerConnection::SetAudioPlayout(bool playout) {
3711 if (!worker_thread()->IsCurrent()) {
3712 worker_thread()->Invoke<void>(
3713 RTC_FROM_HERE,
3714 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3715 return;
3716 }
3717 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003718 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003719 audio_state->SetPlayout(playout);
3720}
3721
3722void PeerConnection::SetAudioRecording(bool recording) {
3723 if (!worker_thread()->IsCurrent()) {
3724 worker_thread()->Invoke<void>(
3725 RTC_FROM_HERE,
3726 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3727 return;
3728 }
3729 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003730 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003731 audio_state->SetRecording(recording);
3732}
3733
Steve Anton8c0f7a72017-10-03 10:03:10 -07003734std::unique_ptr<rtc::SSLCertificate>
3735PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003736 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3737 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003738 return nullptr;
3739 }
Steve Antonf25303e2018-10-16 15:23:31 -07003740 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003741}
3742
Zhi Huang70b820f2018-01-27 14:16:15 -08003743std::unique_ptr<rtc::SSLCertChain>
3744PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003745 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003746 auto audio_transceiver = GetFirstAudioTransceiver();
3747 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003748 return nullptr;
3749 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003750 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003751 audio_transceiver->internal()->channel()->transport_name());
3752}
3753
3754rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3755PeerConnection::GetFirstAudioTransceiver() const {
3756 for (auto transceiver : transceivers_) {
3757 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3758 return transceiver;
3759 }
3760 }
3761 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003762}
3763
ivoc14d5dbe2016-07-04 07:06:55 -07003764bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3765 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003766 // TODO(eladalon): It would be better to not allow negative values into PC.
3767 const size_t max_size = (max_size_bytes < 0)
3768 ? RtcEventLog::kUnlimitedOutput
3769 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003770 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3771 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3772 output_period_ms = 5000;
3773 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003774 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003775 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003776 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003777}
3778
Bjorn Tereliusde939432017-11-20 17:38:14 +01003779bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3780 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003781 // TODO(eladalon): In C++14, this can be done with a lambda.
3782 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003783 bool operator()() {
3784 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3785 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003786 PeerConnection* const pc;
3787 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003788 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003789 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003790 return worker_thread()->Invoke<bool>(
3791 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003792}
3793
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003794bool PeerConnection::StartRtcEventLog(
3795 std::unique_ptr<RtcEventLogOutput> output) {
3796 return StartRtcEventLog(std::move(output),
3797 webrtc::RtcEventLog::kImmediateOutput);
3798}
3799
ivoc14d5dbe2016-07-04 07:06:55 -07003800void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003801 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003802 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3803}
3804
Harald Alvestrandad88c882018-11-28 16:47:46 +01003805rtc::scoped_refptr<DtlsTransportInterface>
3806PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003807 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003808 return transport_controller_->LookupDtlsTransportByMid(mid);
3809}
3810
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003811rtc::scoped_refptr<DtlsTransport>
3812PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003813 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003814 return transport_controller_->LookupDtlsTransportByMid(mid);
3815}
3816
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003817rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3818 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003819 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003820 return sctp_transport_;
3821}
3822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003823const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003824 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003825 return pending_local_description_ ? pending_local_description_.get()
3826 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003827}
3828
3829const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003830 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003831 return pending_remote_description_ ? pending_remote_description_.get()
3832 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003833}
3834
deadbeeffe4a8a42016-12-20 17:56:17 -08003835const SessionDescriptionInterface* PeerConnection::current_local_description()
3836 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003837 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003838 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003839}
3840
3841const SessionDescriptionInterface* PeerConnection::current_remote_description()
3842 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003843 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003844 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003845}
3846
3847const SessionDescriptionInterface* PeerConnection::pending_local_description()
3848 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003849 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003850 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003851}
3852
3853const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3854 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003855 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003856 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003857}
3858
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003859void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003860 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003861 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003862 // Update stats here so that we have the most recent stats for tracks and
3863 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003864 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003865
Steve Anton75737c02017-11-06 10:37:17 -08003866 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003867 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003868
Mirko Bonadei739baf02019-01-27 17:29:42 +01003869 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003870 transceiver->Stop();
3871 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003872
3873 // Ensure that all asynchronous stats requests are completed before destroying
3874 // the transport controller below.
3875 if (stats_collector_) {
3876 stats_collector_->WaitForPendingRequest();
3877 }
3878
3879 // Don't destroy BaseChannels until after stats has been cleaned up so that
3880 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003881 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003882
Qingsi Wang93a84392018-01-30 17:13:09 -08003883 // The event log is used in the transport controller, which must be outlived
3884 // by the former. CreateOffer by the peer connection is implemented
3885 // asynchronously and if the peer connection is closed without resetting the
3886 // WebRTC session description factory, the session description factory would
3887 // call the transport controller.
3888 webrtc_session_desc_factory_.reset();
3889 transport_controller_.reset();
3890
deadbeef42a42632017-03-10 15:18:00 -08003891 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003892 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3893 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003894
Steve Anton978b8762017-09-29 12:15:02 -07003895 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003896 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003897 call_.reset();
3898 // The event log must outlive call (and any other object that uses it).
3899 event_log_.reset();
3900 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003901 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003902 // The .h file says that observer can be discarded after close() returns.
3903 // Make sure this is true.
3904 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003905}
3906
Steve Antonad182762018-09-05 20:22:40 +00003907void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003908 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003909 switch (msg->message_id) {
3910 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3911 SetSessionDescriptionMsg* param =
3912 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3913 param->observer->OnSuccess();
3914 delete param;
3915 break;
3916 }
3917 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3918 SetSessionDescriptionMsg* param =
3919 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3920 param->observer->OnFailure(std::move(param->error));
3921 delete param;
3922 break;
3923 }
3924 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3925 CreateSessionDescriptionMsg* param =
3926 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3927 param->observer->OnFailure(std::move(param->error));
3928 delete param;
3929 break;
3930 }
3931 case MSG_GETSTATS: {
3932 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3933 StatsReports reports;
3934 stats_->GetStats(param->track, &reports);
3935 param->observer->OnComplete(reports);
3936 delete param;
3937 break;
3938 }
3939 case MSG_FREE_DATACHANNELS: {
3940 sctp_data_channels_to_free_.clear();
3941 break;
3942 }
3943 case MSG_REPORT_USAGE_PATTERN: {
3944 ReportUsagePattern();
3945 break;
3946 }
3947 default:
3948 RTC_NOTREACHED() << "Not implemented";
3949 break;
3950 }
3951}
3952
Steve Antonafb0bb72018-02-20 11:35:37 -08003953cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3954 RTC_DCHECK(!IsUnifiedPlan());
3955 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3956 GetAudioTransceiver()->internal()->channel());
3957 if (voice_channel) {
3958 return voice_channel->media_channel();
3959 } else {
3960 return nullptr;
3961 }
3962}
3963
3964cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3965 RTC_DCHECK(!IsUnifiedPlan());
3966 auto* video_channel = static_cast<cricket::VideoChannel*>(
3967 GetVideoTransceiver()->internal()->channel());
3968 if (video_channel) {
3969 return video_channel->media_channel();
3970 } else {
3971 return nullptr;
3972 }
3973}
3974
Steve Anton4171afb2017-11-20 10:20:22 -08003975void PeerConnection::CreateAudioReceiver(
3976 MediaStreamInterface* stream,
3977 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003978 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3979 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003980 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3981 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003982 auto* audio_receiver = new AudioRtpReceiver(
3983 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003984 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003985 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3986 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3987 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003988 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003989 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003990 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003991}
3992
Steve Anton4171afb2017-11-20 10:20:22 -08003993void PeerConnection::CreateVideoReceiver(
3994 MediaStreamInterface* stream,
3995 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003996 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3997 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003998 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3999 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004000 auto* video_receiver = new VideoRtpReceiver(
4001 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004002 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004003 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4004 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4005 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004006 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004007 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004008 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004009}
4010
deadbeef70ab1a12015-09-28 16:53:55 -07004011// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4012// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004013rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004014 const RtpSenderInfo& remote_sender_info) {
4015 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4016 if (!receiver) {
4017 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4018 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004019 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004020 }
Steve Anton4171afb2017-11-20 10:20:22 -08004021 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4022 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4023 } else {
4024 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4025 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004026 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004027}
4028
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4030 MediaStreamInterface* stream) {
4031 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004032 RTC_DCHECK(track);
4033 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004035 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004036 // We already have a sender for this track, so just change the stream_id
4037 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004038 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004039 return;
4040 }
4041
4042 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004043 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004044 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004045 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004046 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004047 // If the sender has already been configured in SDP, we call SetSsrc,
4048 // which will connect the sender to the underlying transport. This can
4049 // occur if a local session description that contains the ID of the sender
4050 // is set before AddStream is called. It can also occur if the local
4051 // session description is not changed and RemoveStream is called, and
4052 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004053 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004054 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004055 if (sender_info) {
4056 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004057 }
4058}
4059
4060// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4061// indefinitely, when we have unified plan SDP.
4062void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4063 MediaStreamInterface* stream) {
4064 RTC_DCHECK(!IsClosed());
4065 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004066 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004067 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4068 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004069 return;
4070 }
Steve Anton4171afb2017-11-20 10:20:22 -08004071 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004072}
4073
4074void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4075 MediaStreamInterface* stream) {
4076 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004077 RTC_DCHECK(track);
4078 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004079 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004080 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004081 // We already have a sender for this track, so just change the stream_id
4082 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004083 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004084 return;
4085 }
4086
4087 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004088 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004089 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004090 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004091 GetVideoTransceiver()->internal()->AddSender(new_sender);
4092 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004093 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004094 if (sender_info) {
4095 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004096 }
4097}
4098
4099void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4100 MediaStreamInterface* stream) {
4101 RTC_DCHECK(!IsClosed());
4102 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004103 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004104 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4105 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004106 return;
4107 }
Steve Anton4171afb2017-11-20 10:20:22 -08004108 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004109}
4110
Steve Antonba818672017-11-06 10:21:57 -08004111void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004112 if (ice_connection_state_ == new_state) {
4113 return;
4114 }
4115
deadbeefcbecd352015-09-23 11:50:27 -07004116 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004117 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004118 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004119 return;
4120 }
Steve Antonba818672017-11-06 10:21:57 -08004121
Mirko Bonadei675513b2017-11-09 11:09:25 +01004122 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4123 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004124 RTC_DCHECK(ice_connection_state_ !=
4125 PeerConnectionInterface::kIceConnectionClosed);
4126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004127 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004128 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004129}
4130
Alex Loiko9289eda2018-11-23 16:18:59 +00004131void PeerConnection::SetStandardizedIceConnectionState(
4132 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004133 if (standardized_ice_connection_state_ == new_state)
4134 return;
4135 if (IsClosed())
4136 return;
4137 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004138 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004139}
4140
Jonas Olsson635474e2018-10-18 15:58:17 +02004141void PeerConnection::SetConnectionState(
4142 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004143 if (connection_state_ == new_state)
4144 return;
4145 if (IsClosed())
4146 return;
4147 connection_state_ = new_state;
4148 Observer()->OnConnectionChange(new_state);
4149}
4150
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004151void PeerConnection::OnIceGatheringChange(
4152 PeerConnectionInterface::IceGatheringState new_state) {
4153 if (IsClosed()) {
4154 return;
4155 }
4156 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004157 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004158}
4159
jbauch81bf7b02017-03-25 08:31:12 -07004160void PeerConnection::OnIceCandidate(
4161 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004162 if (IsClosed()) {
4163 return;
4164 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004165 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004166 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4167 candidate->candidate().address().IsPrivateIP()) {
4168 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4169 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004170 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4171 candidate->candidate().address().IsUnresolvedIP()) {
4172 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4173 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004174 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004175}
4176
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004177void PeerConnection::OnIceCandidatesRemoved(
4178 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004179 if (IsClosed()) {
4180 return;
4181 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004182 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004183}
4184
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004185void PeerConnection::ChangeSignalingState(
4186 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004187 if (signaling_state_ == signaling_state) {
4188 return;
4189 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004190 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4191 << GetSignalingStateString(signaling_state_)
4192 << " New state: "
4193 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004194 signaling_state_ = signaling_state;
4195 if (signaling_state == kClosed) {
4196 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004197 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004198 standardized_ice_connection_state_ =
4199 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004200 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4201 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004202 if (ice_gathering_state_ != kIceGatheringComplete) {
4203 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004204 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004205 }
4206 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004207 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004208}
4209
deadbeefeb459812015-12-15 19:24:43 -08004210void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4211 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004212 if (IsClosed()) {
4213 return;
4214 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004215 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004216 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004217}
4218
deadbeefeb459812015-12-15 19:24:43 -08004219void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4220 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004221 if (IsClosed()) {
4222 return;
4223 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004224 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004225 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004226}
4227
4228void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4229 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004230 if (IsClosed()) {
4231 return;
4232 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004233 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004234 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004235}
4236
4237void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4238 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004239 if (IsClosed()) {
4240 return;
4241 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004242 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004243 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004244}
4245
Henrik Boström31638672017-11-23 17:48:32 +01004246void PeerConnection::PostSetSessionDescriptionSuccess(
4247 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004248 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4249 signaling_thread()->Post(RTC_FROM_HERE, this,
4250 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004251}
4252
deadbeefab9b2d12015-10-14 11:33:11 -07004253void PeerConnection::PostSetSessionDescriptionFailure(
4254 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004255 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004256 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004257 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4258 msg->error = std::move(error);
4259 signaling_thread()->Post(RTC_FROM_HERE, this,
4260 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004261}
4262
4263void PeerConnection::PostCreateSessionDescriptionFailure(
4264 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004265 RTCError error) {
4266 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004267 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4268 msg->error = std::move(error);
4269 signaling_thread()->Post(RTC_FROM_HERE, this,
4270 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004271}
4272
zhihuang1c378ed2017-08-17 14:10:50 -07004273void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004274 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004275 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004276 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004277
Steve Antondcc3c022017-12-22 16:02:54 -08004278 if (IsUnifiedPlan()) {
4279 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4280 } else {
4281 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4282 }
4283
Steve Antonfa2260d2017-12-28 16:38:23 -08004284 // Intentionally unset the data channel type for RTP data channel with the
4285 // second condition. Otherwise the RTP data channels would be successfully
4286 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4287 // when building with chromium. We want to leave RTP data channels broken, so
4288 // people won't try to use them.
4289 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4290 session_options->data_channel_type = data_channel_type();
4291 }
4292
Steve Antondcc3c022017-12-22 16:02:54 -08004293 // Apply ICE restart flag and renomination flag.
4294 for (auto& options : session_options->media_description_options) {
4295 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4296 options.transport_options.enable_ice_renomination =
4297 configuration_.enable_ice_renomination;
4298 }
4299
4300 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004301 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004302 session_options->pooled_ice_credentials =
4303 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4304 RTC_FROM_HERE,
4305 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4306 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004307 session_options->offer_extmap_allow_mixed =
4308 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004309
4310 if (configuration_.enable_dtls_srtp &&
4311 !configuration_.enable_dtls_srtp.value()) {
4312 session_options->media_transport_settings =
4313 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4314 }
Steve Antondcc3c022017-12-22 16:02:54 -08004315}
4316
4317void PeerConnection::GetOptionsForPlanBOffer(
4318 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4319 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004320 // Figure out transceiver directional preferences.
4321 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4322 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4323
4324 // By default, generate sendrecv/recvonly m= sections.
4325 bool recv_audio = true;
4326 bool recv_video = true;
4327
4328 // By default, only offer a new m= section if we have media to send with it.
4329 bool offer_new_audio_description = send_audio;
4330 bool offer_new_video_description = send_video;
4331 bool offer_new_data_description = HasDataChannels();
4332
4333 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004334 if (offer_answer_options.offer_to_receive_audio !=
4335 RTCOfferAnswerOptions::kUndefined) {
4336 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004337 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004338 offer_new_audio_description ||
4339 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004340 }
Steve Antondcc3c022017-12-22 16:02:54 -08004341 if (offer_answer_options.offer_to_receive_video !=
4342 RTCOfferAnswerOptions::kUndefined) {
4343 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004344 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004345 offer_new_video_description ||
4346 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004347 }
4348
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004349 absl::optional<size_t> audio_index;
4350 absl::optional<size_t> video_index;
4351 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004352 // If a current description exists, generate m= sections in the same order,
4353 // using the first audio/video/data section that appears and rejecting
4354 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004355 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004356 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004357 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004358 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4359 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4360 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004361 }
4362
zhihuang1c378ed2017-08-17 14:10:50 -07004363 // Add audio/video/data m= sections to the end if needed.
4364 if (!audio_index && offer_new_audio_description) {
4365 session_options->media_description_options.push_back(
4366 cricket::MediaDescriptionOptions(
4367 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004368 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4369 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004370 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004371 }
zhihuang1c378ed2017-08-17 14:10:50 -07004372 if (!video_index && offer_new_video_description) {
4373 session_options->media_description_options.push_back(
4374 cricket::MediaDescriptionOptions(
4375 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004376 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4377 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004378 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004379 }
zhihuang1c378ed2017-08-17 14:10:50 -07004380 if (!data_index && offer_new_data_description) {
4381 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004382 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004383 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004384 }
4385
4386 cricket::MediaDescriptionOptions* audio_media_description_options =
4387 !audio_index ? nullptr
4388 : &session_options->media_description_options[*audio_index];
4389 cricket::MediaDescriptionOptions* video_media_description_options =
4390 !video_index ? nullptr
4391 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004392
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004393 AddPlanBRtpSenderOptions(GetSendersInternal(),
4394 audio_media_description_options,
4395 video_media_description_options,
4396 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004397}
4398
Steve Antondcc3c022017-12-22 16:02:54 -08004399static cricket::MediaDescriptionOptions
4400GetMediaDescriptionOptionsForTransceiver(
4401 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4402 transceiver,
4403 const std::string& mid) {
4404 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004405 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004406 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004407 media_description_options.codec_preferences =
4408 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004409 // This behavior is specified in JSEP. The gist is that:
4410 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4411 // sendrecv.
4412 // 2. If the MSID is included, then it must be included in any subsequent
4413 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004414 if (transceiver->stopped() ||
4415 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4416 !transceiver->internal()->has_ever_been_used_to_send())) {
4417 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004418 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004419
4420 cricket::SenderOptions sender_options;
4421 sender_options.track_id = transceiver->sender()->id();
4422 sender_options.stream_ids = transceiver->sender()->stream_ids();
4423
4424 // The following sets up RIDs and Simulcast.
4425 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004426 RtpParameters send_parameters =
4427 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004428 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4429 send_parameters.encodings.end(),
4430 [](const RtpEncodingParameters& encoding) {
4431 return !encoding.rid.empty();
4432 });
4433
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004434 std::vector<RidDescription> send_rids;
4435 SimulcastLayerList send_layers;
4436 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4437 if (encoding.rid.empty()) {
4438 continue;
4439 }
4440 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4441 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4442 }
4443
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004444 if (has_rids) {
4445 sender_options.rids = send_rids;
4446 }
4447
4448 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004449 // When RIDs are configured, we must set num_sim_layers to 0 to.
4450 // Otherwise, num_sim_layers must be 1 because either there is no
4451 // simulcast, or simulcast is acheived by munging the SDP.
4452 sender_options.num_sim_layers = has_rids ? 0 : 1;
4453 media_description_options.sender_options.push_back(sender_options);
4454
Steve Antondcc3c022017-12-22 16:02:54 -08004455 return media_description_options;
4456}
4457
Steve Anton5c72e712018-12-10 14:25:30 -08004458// Returns the ContentInfo at mline index |i|, or null if none exists.
4459static const ContentInfo* GetContentByIndex(
4460 const SessionDescriptionInterface* sdesc,
4461 size_t i) {
4462 if (!sdesc) {
4463 return nullptr;
4464 }
4465 const ContentInfos& contents = sdesc->description()->contents();
4466 return (i < contents.size() ? &contents[i] : nullptr);
4467}
4468
Steve Antondcc3c022017-12-22 16:02:54 -08004469void PeerConnection::GetOptionsForUnifiedPlanOffer(
4470 const RTCOfferAnswerOptions& offer_answer_options,
4471 cricket::MediaSessionOptions* session_options) {
4472 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4473 // Offers) and 5.2.2 (Subsequent Offers).
4474 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4475 const ContentInfos& local_contents =
4476 (local_description() ? local_description()->description()->contents()
4477 : ContentInfos());
4478 const ContentInfos& remote_contents =
4479 (remote_description() ? remote_description()->description()->contents()
4480 : ContentInfos());
4481 // The mline indices that can be recycled. New transceivers should reuse these
4482 // slots first.
4483 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004484 // First, go through each media section that exists in either the local or
4485 // remote description and generate a media section in this offer for the
4486 // associated transceiver. If a media section can be recycled, generate a
4487 // default, rejected media section here that can be later overwritten.
4488 for (size_t i = 0;
4489 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4490 // Either |local_content| or |remote_content| is non-null.
4491 const ContentInfo* local_content =
4492 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004493 const ContentInfo* current_local_content =
4494 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004495 const ContentInfo* remote_content =
4496 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004497 const ContentInfo* current_remote_content =
4498 GetContentByIndex(current_remote_description(), i);
4499 bool had_been_rejected =
4500 (current_local_content && current_local_content->rejected) ||
4501 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004502 const std::string& mid =
4503 (local_content ? local_content->name : remote_content->name);
4504 cricket::MediaType media_type =
4505 (local_content ? local_content->media_description()->type()
4506 : remote_content->media_description()->type());
4507 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4508 media_type == cricket::MEDIA_TYPE_VIDEO) {
4509 auto transceiver = GetAssociatedTransceiver(mid);
4510 RTC_CHECK(transceiver);
4511 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004512 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004513 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004514 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004515 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4516 RtpTransceiverDirection::kInactive,
4517 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004518 recycleable_mline_indices.push(i);
4519 } else {
4520 session_options->media_description_options.push_back(
4521 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4522 // CreateOffer shouldn't really cause any state changes in
4523 // PeerConnection, but we need a way to match new transceivers to new
4524 // media sections in SetLocalDescription and JSEP specifies this is done
4525 // by recording the index of the media section generated for the
4526 // transceiver in the offer.
4527 transceiver->internal()->set_mline_index(i);
4528 }
4529 } else {
4530 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004531 RTC_CHECK(GetDataMid());
4532 if (had_been_rejected || mid != *GetDataMid()) {
4533 session_options->media_description_options.push_back(
4534 GetMediaDescriptionOptionsForRejectedData(mid));
4535 } else {
4536 session_options->media_description_options.push_back(
4537 GetMediaDescriptionOptionsForActiveData(mid));
4538 }
Steve Antondcc3c022017-12-22 16:02:54 -08004539 }
4540 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004541
Steve Antondcc3c022017-12-22 16:02:54 -08004542 // Next, look for transceivers that are newly added (that is, are not stopped
4543 // and not associated). Reuse media sections marked as recyclable first,
4544 // otherwise append to the end of the offer. New media sections should be
4545 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004546 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004547 if (transceiver->mid() || transceiver->stopped()) {
4548 continue;
4549 }
4550 size_t mline_index;
4551 if (!recycleable_mline_indices.empty()) {
4552 mline_index = recycleable_mline_indices.front();
4553 recycleable_mline_indices.pop();
4554 session_options->media_description_options[mline_index] =
4555 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004556 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004557 } else {
4558 mline_index = session_options->media_description_options.size();
4559 session_options->media_description_options.push_back(
4560 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004561 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004562 }
4563 // See comment above for why CreateOffer changes the transceiver's state.
4564 transceiver->internal()->set_mline_index(mline_index);
4565 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004566 // Lastly, add a m-section if we have local data channels and an m section
4567 // does not already exist.
4568 if (!GetDataMid() && HasDataChannels()) {
4569 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004570 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004571 }
Steve Antondcc3c022017-12-22 16:02:54 -08004572}
4573
4574void PeerConnection::GetOptionsForAnswer(
4575 const RTCOfferAnswerOptions& offer_answer_options,
4576 cricket::MediaSessionOptions* session_options) {
4577 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4578
4579 if (IsUnifiedPlan()) {
4580 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4581 } else {
4582 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4583 }
4584
Steve Antonfa2260d2017-12-28 16:38:23 -08004585 // Intentionally unset the data channel type for RTP data channel. Otherwise
4586 // the RTP data channels would be successfully negotiated by default and the
4587 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4588 // We want to leave RTP data channels broken, so people won't try to use them.
4589 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4590 session_options->data_channel_type = data_channel_type();
4591 }
4592
Steve Antondcc3c022017-12-22 16:02:54 -08004593 // Apply ICE renomination flag.
4594 for (auto& options : session_options->media_description_options) {
4595 options.transport_options.enable_ice_renomination =
4596 configuration_.enable_ice_renomination;
4597 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004598
4599 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004600 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004601 session_options->pooled_ice_credentials =
4602 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4603 RTC_FROM_HERE,
4604 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4605 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004606}
4607
Steve Antondcc3c022017-12-22 16:02:54 -08004608void PeerConnection::GetOptionsForPlanBAnswer(
4609 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004610 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004611 // Figure out transceiver directional preferences.
4612 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4613 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4614
4615 // By default, generate sendrecv/recvonly m= sections. The direction is also
4616 // restricted by the direction in the offer.
4617 bool recv_audio = true;
4618 bool recv_video = true;
4619
4620 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004621 if (offer_answer_options.offer_to_receive_audio !=
4622 RTCOfferAnswerOptions::kUndefined) {
4623 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004624 }
Steve Antondcc3c022017-12-22 16:02:54 -08004625 if (offer_answer_options.offer_to_receive_video !=
4626 RTCOfferAnswerOptions::kUndefined) {
4627 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004628 }
4629
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004630 absl::optional<size_t> audio_index;
4631 absl::optional<size_t> video_index;
4632 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004633
4634 // Generate m= sections that match those in the offer.
4635 // Note that mediasession.cc will handle intersection our preferred
4636 // direction with the offered direction.
4637 GenerateMediaDescriptionOptions(
4638 remote_description(),
4639 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4640 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4641 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004642
4643 cricket::MediaDescriptionOptions* audio_media_description_options =
4644 !audio_index ? nullptr
4645 : &session_options->media_description_options[*audio_index];
4646 cricket::MediaDescriptionOptions* video_media_description_options =
4647 !video_index ? nullptr
4648 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004649
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004650 AddPlanBRtpSenderOptions(GetSendersInternal(),
4651 audio_media_description_options,
4652 video_media_description_options,
4653 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004654}
zhihuangaf388472016-11-02 16:49:48 -07004655
Steve Antondcc3c022017-12-22 16:02:54 -08004656void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4657 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4658 cricket::MediaSessionOptions* session_options) {
4659 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4660 // Answers) and 5.3.2 (Subsequent Answers).
4661 RTC_DCHECK(remote_description());
4662 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4663 for (const ContentInfo& content :
4664 remote_description()->description()->contents()) {
4665 cricket::MediaType media_type = content.media_description()->type();
4666 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4667 media_type == cricket::MEDIA_TYPE_VIDEO) {
4668 auto transceiver = GetAssociatedTransceiver(content.name);
4669 RTC_CHECK(transceiver);
4670 session_options->media_description_options.push_back(
4671 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4672 } else {
4673 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004674 // Reject all data sections if data channels are disabled.
4675 // Reject a data section if it has already been rejected.
4676 // Reject all data sections except for the first one.
4677 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4678 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004679 session_options->media_description_options.push_back(
4680 GetMediaDescriptionOptionsForRejectedData(content.name));
4681 } else {
4682 session_options->media_description_options.push_back(
4683 GetMediaDescriptionOptionsForActiveData(content.name));
4684 }
Steve Antondcc3c022017-12-22 16:02:54 -08004685 }
4686 }
htaa2a49d92016-03-04 02:51:39 -08004687}
4688
zhihuang1c378ed2017-08-17 14:10:50 -07004689void PeerConnection::GenerateMediaDescriptionOptions(
4690 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004691 RtpTransceiverDirection audio_direction,
4692 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004693 absl::optional<size_t>* audio_index,
4694 absl::optional<size_t>* video_index,
4695 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004696 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004697 for (const cricket::ContentInfo& content :
4698 session_desc->description()->contents()) {
4699 if (IsAudioContent(&content)) {
4700 // If we already have an audio m= section, reject this extra one.
4701 if (*audio_index) {
4702 session_options->media_description_options.push_back(
4703 cricket::MediaDescriptionOptions(
4704 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004705 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004706 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004707 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004708 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004709 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4710 content.name, audio_direction,
4711 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004712 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004713 }
4714 } else if (IsVideoContent(&content)) {
4715 // If we already have an video m= section, reject this extra one.
4716 if (*video_index) {
4717 session_options->media_description_options.push_back(
4718 cricket::MediaDescriptionOptions(
4719 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004720 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004721 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004722 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004723 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004724 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4725 content.name, video_direction,
4726 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004727 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004728 }
4729 } else {
4730 RTC_DCHECK(IsDataContent(&content));
4731 // If we already have an data m= section, reject this extra one.
4732 if (*data_index) {
4733 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004734 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004735 } else {
4736 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004737 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004738 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004739 }
4740 }
htaa2a49d92016-03-04 02:51:39 -08004741 }
deadbeefab9b2d12015-10-14 11:33:11 -07004742}
4743
Steve Antonfa2260d2017-12-28 16:38:23 -08004744cricket::MediaDescriptionOptions
4745PeerConnection::GetMediaDescriptionOptionsForActiveData(
4746 const std::string& mid) const {
4747 // Direction for data sections is meaningless, but legacy endpoints might
4748 // expect sendrecv.
4749 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4750 RtpTransceiverDirection::kSendRecv,
4751 /*stopped=*/false);
4752 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4753 return options;
4754}
4755
4756cricket::MediaDescriptionOptions
4757PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4758 const std::string& mid) const {
4759 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4760 RtpTransceiverDirection::kInactive,
4761 /*stopped=*/true);
4762 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4763 return options;
4764}
4765
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004766absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004767 switch (data_channel_type_) {
4768 case cricket::DCT_RTP:
4769 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004770 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004771 }
4772 return rtp_data_channel_->content_name();
4773 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004774 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004775 case cricket::DCT_MEDIA_TRANSPORT:
4776 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004777 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004778 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004779 }
4780}
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4783 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4784 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004785 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004786}
4787
Steve Anton4171afb2017-11-20 10:20:22 -08004788void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004789 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004790 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004791 cricket::MediaType media_type,
4792 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004793 RTC_DCHECK(!IsUnifiedPlan());
4794
Steve Anton4171afb2017-11-20 10:20:22 -08004795 std::vector<RtpSenderInfo>* current_senders =
4796 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004797
Steve Anton4171afb2017-11-20 10:20:22 -08004798 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004799 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004800 for (auto sender_it = current_senders->begin();
4801 sender_it != current_senders->end();
4802 /* incremented manually */) {
4803 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004804 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004805 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004806 std::string params_stream_id;
4807 if (params) {
4808 params_stream_id =
4809 (!params->first_stream_id().empty() ? params->first_stream_id()
4810 : kDefaultStreamId);
4811 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004812 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004813 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004814 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004815 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004816 sender_exists) {
4817 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004818 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004819 OnRemoteSenderRemoved(info, media_type);
4820 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004821 }
4822 }
4823
Steve Anton4171afb2017-11-20 10:20:22 -08004824 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004825 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004826 if (!params.has_ssrcs()) {
4827 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4828 // sender, this means it is coming from a Unified Plan endpoint,so we just
4829 // create a default.
4830 default_sender_needed = true;
4831 break;
4832 }
4833
Seth Hampson845e8782018-03-02 11:34:10 -08004834 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004835 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004836 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4837 // not supported in Plan B, we just take the first here and create the
4838 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004839 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004840 (!params.first_stream_id().empty() ? params.first_stream_id()
4841 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004842 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004843 uint32_t ssrc = params.first_ssrc();
4844
4845 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004846 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004847 if (!stream) {
4848 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004849 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004850 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004851 remote_streams_->AddStream(stream);
4852 new_streams->AddStream(stream);
4853 }
4854
Steve Anton4171afb2017-11-20 10:20:22 -08004855 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004856 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004857 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004858 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004859 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004860 }
4861 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004862
Steve Anton4171afb2017-11-20 10:20:22 -08004863 // Add default sender if necessary.
4864 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004865 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004866 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004867 if (!default_stream) {
4868 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004869 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004870 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004871 remote_streams_->AddStream(default_stream);
4872 new_streams->AddStream(default_stream);
4873 }
Steve Anton4171afb2017-11-20 10:20:22 -08004874 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4875 ? kDefaultAudioSenderId
4876 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004877 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004878 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004879 if (!default_sender_info) {
4880 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004881 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004882 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004883 }
4884 }
deadbeefab9b2d12015-10-14 11:33:11 -07004885}
4886
Steve Anton4171afb2017-11-20 10:20:22 -08004887void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4888 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004889 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4890 << " receiver for track_id=" << sender_info.sender_id
4891 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004892
Steve Anton3d954a62018-04-02 11:27:23 -07004893 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004894 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004895 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004896 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004897 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004898 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004899 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004900 }
4901}
4902
Steve Anton4171afb2017-11-20 10:20:22 -08004903void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4904 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004905 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4906 << " receiver for track_id=" << sender_info.sender_id
4907 << " and stream_id=" << sender_info.stream_id;
4908
Seth Hampson845e8782018-03-02 11:34:10 -08004909 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004910
Henrik Boström933d8b02017-10-10 10:05:16 -07004911 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004912 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004913 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4914 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004915 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004916 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004917 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004918 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004919 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004920 }
4921 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004922 // Stopping or destroying a VideoRtpReceiver will end the
4923 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004924 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004925 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004926 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004927 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004928 // There's no guarantee the track is still available, e.g. the track may
4929 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004930 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004931 }
4932 } else {
nisseede5da42017-01-12 05:15:36 -08004933 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004934 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004935 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004936 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004937 }
deadbeefab9b2d12015-10-14 11:33:11 -07004938}
4939
4940void PeerConnection::UpdateEndedRemoteMediaStreams() {
4941 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4942 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4943 MediaStreamInterface* stream = remote_streams_->at(i);
4944 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4945 streams_to_remove.push_back(stream);
4946 }
4947 }
4948
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004949 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004950 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004951 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004952 }
4953}
4954
Steve Anton4171afb2017-11-20 10:20:22 -08004955void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004956 const std::vector<cricket::StreamParams>& streams,
4957 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004958 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004959
Seth Hampson845e8782018-03-02 11:34:10 -08004960 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004961 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004962 for (auto sender_it = current_senders->begin();
4963 sender_it != current_senders->end();
4964 /* incremented manually */) {
4965 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004966 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004967 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4968 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004969 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004970 OnLocalSenderRemoved(info, media_type);
4971 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004972 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004973 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004974 }
4975 }
4976
Steve Anton4171afb2017-11-20 10:20:22 -08004977 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004978 for (const cricket::StreamParams& params : streams) {
4979 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004980 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004981 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004982 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004983 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004984 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004985 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004986 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004987 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004988 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004989 }
4990 }
4991}
4992
Steve Anton4171afb2017-11-20 10:20:22 -08004993void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4994 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004995 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004996 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004997 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004998 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4999 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005000 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005001 return;
5002 }
5003
deadbeeffac06552015-11-25 11:26:01 -08005004 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005005 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005006 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005007 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005008 }
deadbeeffac06552015-11-25 11:26:01 -08005009
Seth Hampson5b4f0752018-04-02 16:31:36 -07005010 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005011 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005012}
5013
Steve Anton4171afb2017-11-20 10:20:22 -08005014void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5015 cricket::MediaType media_type) {
5016 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005017 if (!sender) {
5018 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005019 // SessionDescriptions has been renegotiated.
5020 return;
5021 }
deadbeeffac06552015-11-25 11:26:01 -08005022
5023 // A sender has been removed from the SessionDescription but it's still
5024 // associated with the PeerConnection. This only occurs if the SDP doesn't
5025 // match with the calls to CreateSender, AddStream and RemoveStream.
5026 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005027 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005028 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005029 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005030 }
deadbeeffac06552015-11-25 11:26:01 -08005031
Steve Anton4171afb2017-11-20 10:20:22 -08005032 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005033}
5034
5035void PeerConnection::UpdateLocalRtpDataChannels(
5036 const cricket::StreamParamsVec& streams) {
5037 std::vector<std::string> existing_channels;
5038
5039 // Find new and active data channels.
5040 for (const cricket::StreamParams& params : streams) {
5041 // |it->sync_label| is actually the data channel label. The reason is that
5042 // we use the same naming of data channels as we do for
5043 // MediaStreams and Tracks.
5044 // For MediaStreams, the sync_label is the MediaStream label and the
5045 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005046 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005047 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005048 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005049 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005050 continue;
5051 }
5052 // Set the SSRC the data channel should use for sending.
5053 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5054 existing_channels.push_back(data_channel_it->first);
5055 }
5056
5057 UpdateClosingRtpDataChannels(existing_channels, true);
5058}
5059
5060void PeerConnection::UpdateRemoteRtpDataChannels(
5061 const cricket::StreamParamsVec& streams) {
5062 std::vector<std::string> existing_channels;
5063
5064 // Find new and active data channels.
5065 for (const cricket::StreamParams& params : streams) {
5066 // The data channel label is either the mslabel or the SSRC if the mslabel
5067 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005068 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005069 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005070 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005071 auto data_channel_it = rtp_data_channels_.find(label);
5072 if (data_channel_it == rtp_data_channels_.end()) {
5073 // This is a new data channel.
5074 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5075 } else {
5076 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5077 }
5078 existing_channels.push_back(label);
5079 }
5080
5081 UpdateClosingRtpDataChannels(existing_channels, false);
5082}
5083
5084void PeerConnection::UpdateClosingRtpDataChannels(
5085 const std::vector<std::string>& active_channels,
5086 bool is_local_update) {
5087 auto it = rtp_data_channels_.begin();
5088 while (it != rtp_data_channels_.end()) {
5089 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005090 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005091 ++it;
5092 continue;
5093 }
5094
5095 if (is_local_update) {
5096 data_channel->SetSendSsrc(0);
5097 } else {
5098 data_channel->RemotePeerRequestClose();
5099 }
5100
5101 if (data_channel->state() == DataChannel::kClosed) {
5102 rtp_data_channels_.erase(it);
5103 it = rtp_data_channels_.begin();
5104 } else {
5105 ++it;
5106 }
5107 }
5108}
5109
5110void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5111 uint32_t remote_ssrc) {
5112 rtc::scoped_refptr<DataChannel> channel(
5113 InternalCreateDataChannel(label, nullptr));
5114 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005116 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005117 return;
5118 }
5119 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005120 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5121 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005122 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005123}
5124
5125rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5126 const std::string& label,
5127 const InternalDataChannelInit* config) {
5128 if (IsClosed()) {
5129 return nullptr;
5130 }
Steve Anton75737c02017-11-06 10:37:17 -08005131 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005132 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005133 << "InternalCreateDataChannel: Data is not supported in this call.";
5134 return nullptr;
5135 }
5136 InternalDataChannelInit new_config =
5137 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005138 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005139 if (new_config.id < 0) {
5140 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005141 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005142 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005143 RTC_LOG(LS_ERROR)
5144 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005145 return nullptr;
5146 }
5147 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005148 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005149 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005150 return nullptr;
5151 }
5152 }
5153
Steve Anton75737c02017-11-06 10:37:17 -08005154 rtc::scoped_refptr<DataChannel> channel(
5155 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005156 if (!channel) {
5157 sid_allocator_.ReleaseSid(new_config.id);
5158 return nullptr;
5159 }
5160
5161 if (channel->data_channel_type() == cricket::DCT_RTP) {
5162 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005163 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5164 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005165 return nullptr;
5166 }
5167 rtp_data_channels_[channel->label()] = channel;
5168 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005169 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005170 sctp_data_channels_.push_back(channel);
5171 channel->SignalClosed.connect(this,
5172 &PeerConnection::OnSctpDataChannelClosed);
5173 }
5174
Steve Anton2d8609c2018-01-23 16:38:46 -08005175 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005176 return channel;
5177}
5178
5179bool PeerConnection::HasDataChannels() const {
5180 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5181}
5182
5183void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005184 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005185 for (const auto& channel : sctp_data_channels_) {
5186 if (channel->id() < 0) {
5187 int sid;
5188 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005189 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5190 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005191 continue;
5192 }
5193 channel->SetSctpSid(sid);
5194 }
5195 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005196 // Since closing modifies the list of channels, we have to do the actual
5197 // closing outside the loop.
5198 for (const auto& channel : channels_to_close) {
5199 channel->CloseAbruptly();
5200 }
deadbeefab9b2d12015-10-14 11:33:11 -07005201}
5202
5203void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005204 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005205 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5206 ++it) {
5207 if (it->get() == channel) {
5208 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005209 // After the closing procedure is done, it's safe to use this ID for
5210 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005211 sid_allocator_.ReleaseSid(channel->id());
5212 }
deadbeefbd292462015-12-14 18:15:29 -08005213 // Since this method is triggered by a signal from the DataChannel,
5214 // we can't free it directly here; we need to free it asynchronously.
5215 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005216 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005217 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5218 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005219 return;
5220 }
5221 }
5222}
5223
deadbeefab9b2d12015-10-14 11:33:11 -07005224void PeerConnection::OnDataChannelDestroyed() {
5225 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5226 // DataChannel may callback to us and try to modify the list.
5227 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5228 temp_rtp_dcs.swap(rtp_data_channels_);
5229 for (const auto& kv : temp_rtp_dcs) {
5230 kv.second->OnTransportChannelDestroyed();
5231 }
5232
5233 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5234 temp_sctp_dcs.swap(sctp_data_channels_);
5235 for (const auto& channel : temp_sctp_dcs) {
5236 channel->OnTransportChannelDestroyed();
5237 }
5238}
5239
5240void PeerConnection::OnDataChannelOpenMessage(
5241 const std::string& label,
5242 const InternalDataChannelInit& config) {
5243 rtc::scoped_refptr<DataChannel> channel(
5244 InternalCreateDataChannel(label, &config));
5245 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005246 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005247 return;
5248 }
5249
deadbeefa601f5c2016-06-06 14:27:39 -07005250 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5251 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005252 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005253 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005254}
5255
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005256bool PeerConnection::HandleOpenMessage_s(
5257 const cricket::ReceiveDataParams& params,
5258 const rtc::CopyOnWriteBuffer& buffer) {
5259 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5260 // Received OPEN message; parse and signal that a new data channel should
5261 // be created.
5262 std::string label;
5263 InternalDataChannelInit config;
5264 config.id = params.ssrc;
5265 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5266 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5267 << params.ssrc;
5268 return true;
5269 }
5270 config.open_handshake_role = InternalDataChannelInit::kAcker;
5271 OnDataChannelOpenMessage(label, config);
5272 return true;
5273 }
5274 return false;
5275}
5276
Steve Anton4171afb2017-11-20 10:20:22 -08005277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5278PeerConnection::GetAudioTransceiver() const {
5279 // This method only works with Plan B SDP, where there is a single
5280 // audio/video transceiver.
5281 RTC_DCHECK(!IsUnifiedPlan());
5282 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005283 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005284 return transceiver;
5285 }
5286 }
5287 RTC_NOTREACHED();
5288 return nullptr;
5289}
5290
5291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5292PeerConnection::GetVideoTransceiver() const {
5293 // This method only works with Plan B SDP, where there is a single
5294 // audio/video transceiver.
5295 RTC_DCHECK(!IsUnifiedPlan());
5296 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005297 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005298 return transceiver;
5299 }
5300 }
5301 RTC_NOTREACHED();
5302 return nullptr;
5303}
5304
5305// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5306// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005307bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005308 switch (type) {
5309 case cricket::MEDIA_TYPE_AUDIO:
5310 return !GetAudioTransceiver()->internal()->senders().empty();
5311 case cricket::MEDIA_TYPE_VIDEO:
5312 return !GetVideoTransceiver()->internal()->senders().empty();
5313 case cricket::MEDIA_TYPE_DATA:
5314 return false;
5315 }
5316 RTC_NOTREACHED();
5317 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005318}
5319
Steve Anton4171afb2017-11-20 10:20:22 -08005320rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5321PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005322 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005323 for (auto sender : transceiver->internal()->senders()) {
5324 if (sender->track() == track) {
5325 return sender;
5326 }
5327 }
5328 }
5329 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005330}
5331
Steve Anton4171afb2017-11-20 10:20:22 -08005332rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5333PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005334 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005335 for (auto sender : transceiver->internal()->senders()) {
5336 if (sender->id() == sender_id) {
5337 return sender;
5338 }
5339 }
5340 }
5341 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005342}
5343
Steve Anton4171afb2017-11-20 10:20:22 -08005344rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5345PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005346 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005347 for (auto receiver : transceiver->internal()->receivers()) {
5348 if (receiver->id() == receiver_id) {
5349 return receiver;
5350 }
5351 }
5352 }
5353 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005354}
5355
Steve Anton4171afb2017-11-20 10:20:22 -08005356std::vector<PeerConnection::RtpSenderInfo>*
5357PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5358 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5359 media_type == cricket::MEDIA_TYPE_VIDEO);
5360 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5361 ? &remote_audio_sender_infos_
5362 : &remote_video_sender_infos_;
5363}
5364
5365std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005366 cricket::MediaType media_type) {
5367 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5368 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005369 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5370 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005371}
5372
Steve Anton4171afb2017-11-20 10:20:22 -08005373const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5374 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005375 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005376 const std::string sender_id) const {
5377 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005378 if (sender_info.stream_id == stream_id &&
5379 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005380 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005381 }
5382 }
5383 return nullptr;
5384}
5385
5386DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5387 for (const auto& channel : sctp_data_channels_) {
5388 if (channel->id() == sid) {
5389 return channel;
5390 }
5391 }
5392 return nullptr;
5393}
5394
Karl Wibergfb3be392019-03-22 14:13:22 +01005395PeerConnection::InitializePortAllocatorResult
5396PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005397 const cricket::ServerAddresses& stun_servers,
5398 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005399 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005400 RTC_DCHECK_RUN_ON(network_thread());
5401
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005402 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403 // To handle both internal and externally created port allocator, we will
5404 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005405 int port_allocator_flags = port_allocator_->flags();
5406 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5407 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5408 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005409 // If the disable-IPv6 flag was specified, we'll not override it
5410 // by experiment.
5411 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005412 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005413 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5414 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005415 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005416 }
5417
zhihuangb09b3f92017-03-07 14:40:51 -08005418 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005419 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005420 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005421 }
5422
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005424 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005425 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005426 }
5427
honghaiz60347052016-05-31 18:29:12 -07005428 if (configuration.candidate_network_policy ==
5429 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005430 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005431 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005432 }
5433
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005434 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005435 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005436 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5437 }
5438
Karl Wibergfb3be392019-03-22 14:13:22 +01005439 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005440 // No step delay is used while allocating ports.
5441 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005442 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005443 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005444 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005445
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005446 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005447 for (auto& turn_server : turn_servers_copy) {
5448 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005449 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005450 // Call this last since it may create pooled allocator sessions using the
5451 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005452 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005453 stun_servers, std::move(turn_servers_copy),
5454 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5455 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005456 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005457
5458 InitializePortAllocatorResult res;
5459 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5460 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005461}
5462
deadbeef91dd5672016-05-18 16:55:30 -07005463bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005464 const cricket::ServerAddresses& stun_servers,
5465 const std::vector<cricket::RelayServerConfig>& turn_servers,
5466 IceTransportsType type,
5467 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005468 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005469 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005470 absl::optional<int> stun_candidate_keepalive_interval,
5471 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005472 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005473 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005474 // According to JSEP, after setLocalDescription, changing the candidate pool
5475 // size is not allowed, and changing the set of ICE servers will not result
5476 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005477 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005478 port_allocator_->FreezeCandidatePool();
5479 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005480 // Add the custom tls turn servers if they exist.
5481 auto turn_servers_copy = turn_servers;
5482 for (auto& turn_server : turn_servers_copy) {
5483 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5484 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005485 // Call this last since it may create pooled allocator sessions using the
5486 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005487 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005488 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5489 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005490}
5491
Steve Antonba818672017-11-06 10:21:57 -08005492cricket::ChannelManager* PeerConnection::channel_manager() const {
5493 return factory_->channel_manager();
5494}
5495
Elad Alon99c3fe52017-10-13 16:29:40 +02005496bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005497 std::unique_ptr<RtcEventLogOutput> output,
5498 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005499 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005500 if (!event_log_) {
5501 return false;
5502 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005503 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005504}
5505
5506void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005507 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005508 if (event_log_) {
5509 event_log_->StopLogging();
5510 }
ivoc14d5dbe2016-07-04 07:06:55 -07005511}
nisseeaabdf62017-05-05 02:23:02 -07005512
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005513cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005514 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005515 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005516 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005517 if (channel && channel->content_name() == content_name) {
5518 return channel;
5519 }
Steve Anton75737c02017-11-06 10:37:17 -08005520 }
5521 if (rtp_data_channel() &&
5522 rtp_data_channel()->content_name() == content_name) {
5523 return rtp_data_channel();
5524 }
5525 return nullptr;
5526}
5527
5528bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005529 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005530 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005531 RTC_LOG(LS_INFO)
5532 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005533 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005534 return false;
5535 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005536 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005537 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005538 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005539 return false;
5540 }
5541
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005542 absl::optional<rtc::SSLRole> dtls_role;
5543 if (sctp_mid_) {
5544 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5545 } else if (is_caller_) {
5546 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5547 }
Zhi Huange830e682018-03-30 10:48:35 -07005548 if (dtls_role) {
5549 *role = *dtls_role;
5550 return true;
5551 }
5552 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005553}
5554
5555bool PeerConnection::GetSslRole(const std::string& content_name,
5556 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005557 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005558 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005559 RTC_LOG(LS_INFO)
5560 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005561 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005562 return false;
5563 }
5564
Zhi Huange830e682018-03-30 10:48:35 -07005565 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5566 if (dtls_role) {
5567 *role = *dtls_role;
5568 return true;
5569 }
5570 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005571}
5572
Steve Antonf8470812017-12-04 10:46:21 -08005573void PeerConnection::SetSessionError(SessionError error,
5574 const std::string& error_desc) {
5575 RTC_DCHECK_RUN_ON(signaling_thread());
5576 if (error != session_error_) {
5577 session_error_ = error;
5578 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005579 }
5580}
5581
Zhi Huange830e682018-03-30 10:48:35 -07005582RTCError PeerConnection::UpdateSessionState(
5583 SdpType type,
5584 cricket::ContentSource source,
5585 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005586 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005587
5588 // If there's already a pending error then no state transition should happen.
5589 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005590 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005591
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005592 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005593 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005594 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005595 }
5596
5597 // Update the signaling state according to the specified state machine (see
5598 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005599 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005600 ChangeSignalingState(source == cricket::CS_LOCAL
5601 ? PeerConnectionInterface::kHaveLocalOffer
5602 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005603 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005604 ChangeSignalingState(source == cricket::CS_LOCAL
5605 ? PeerConnectionInterface::kHaveLocalPrAnswer
5606 : PeerConnectionInterface::kHaveRemotePrAnswer);
5607 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005608 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005609 ChangeSignalingState(PeerConnectionInterface::kStable);
5610 }
5611
5612 // Update internal objects according to the session description's media
5613 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005614 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005615 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005616 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005617 }
5618
Steve Anton8a006912017-12-04 15:25:56 -08005619 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005620}
5621
Steve Anton8a006912017-12-04 15:25:56 -08005622RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005623 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005624 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005625 const SessionDescriptionInterface* sdesc =
5626 (source == cricket::CS_LOCAL ? local_description()
5627 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005628 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005629
5630 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005631 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005632 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005633 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005634 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005635 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005636 continue;
5637 }
5638 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005639 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005640 if (!content_desc) {
5641 continue;
5642 }
5643 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005644 bool success = (source == cricket::CS_LOCAL)
5645 ? channel->SetLocalContent(content_desc, type, &error)
5646 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005647 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005648 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005649 }
5650 }
5651
5652 // If using the RtpDataChannel, push down the new SDP section for it too.
5653 if (rtp_data_channel_) {
5654 const ContentInfo* data_content =
5655 cricket::GetFirstDataContent(sdesc->description());
5656 if (data_content && !data_content->rejected) {
5657 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005658 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005659 if (data_desc) {
5660 std::string error;
5661 bool success =
5662 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005663 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005664 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005665 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005667 }
Steve Anton75737c02017-11-06 10:37:17 -08005668 }
5669 }
5670 }
Steve Antoned10bd92017-12-05 10:52:59 -08005671
Steve Anton75737c02017-11-06 10:37:17 -08005672 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5673 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5674 if (sctp_transport_ && local_description() && remote_description() &&
5675 cricket::GetFirstDataContent(local_description()->description()) &&
5676 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005677 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005678 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005679 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5680 GetSctpPort(local_description()->description()),
5681 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005682 if (!success) {
5683 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5684 "Failed to push down SCTP parameters.");
5685 }
Steve Anton75737c02017-11-06 10:37:17 -08005686 }
Steve Antoned10bd92017-12-05 10:52:59 -08005687
Steve Anton8a006912017-12-04 15:25:56 -08005688 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005689}
5690
Karl Wiberg739506e2019-04-03 11:37:28 +02005691bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5692 int local_sctp_port,
5693 int remote_sctp_port) {
5694 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005695 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5696 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005697 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005698}
5699
Steve Anton8a006912017-12-04 15:25:56 -08005700RTCError PeerConnection::PushdownTransportDescription(
5701 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005702 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005703 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005704
Zhi Huange830e682018-03-30 10:48:35 -07005705 if (source == cricket::CS_LOCAL) {
5706 const SessionDescriptionInterface* sdesc = local_description();
5707 RTC_DCHECK(sdesc);
5708 return transport_controller_->SetLocalDescription(type,
5709 sdesc->description());
5710 } else {
5711 const SessionDescriptionInterface* sdesc = remote_description();
5712 RTC_DCHECK(sdesc);
5713 return transport_controller_->SetRemoteDescription(type,
5714 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005715 }
Steve Anton75737c02017-11-06 10:37:17 -08005716}
5717
5718bool PeerConnection::GetTransportDescription(
5719 const SessionDescription* description,
5720 const std::string& content_name,
5721 cricket::TransportDescription* tdesc) {
5722 if (!description || !tdesc) {
5723 return false;
5724 }
5725 const TransportInfo* transport_info =
5726 description->GetTransportInfoByName(content_name);
5727 if (!transport_info) {
5728 return false;
5729 }
5730 *tdesc = transport_info->description;
5731 return true;
5732}
5733
Steve Anton75737c02017-11-06 10:37:17 -08005734cricket::IceConfig PeerConnection::ParseIceConfig(
5735 const PeerConnectionInterface::RTCConfiguration& config) const {
5736 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005737 switch (config.continual_gathering_policy) {
5738 case PeerConnectionInterface::GATHER_ONCE:
5739 gathering_policy = cricket::GATHER_ONCE;
5740 break;
5741 case PeerConnectionInterface::GATHER_CONTINUALLY:
5742 gathering_policy = cricket::GATHER_CONTINUALLY;
5743 break;
5744 default:
5745 RTC_NOTREACHED();
5746 gathering_policy = cricket::GATHER_ONCE;
5747 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005748
Steve Anton75737c02017-11-06 10:37:17 -08005749 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005750 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5751 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005752 ice_config.prioritize_most_likely_candidate_pairs =
5753 config.prioritize_most_likely_ice_candidate_pairs;
5754 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005755 RTCConfigurationToIceConfigOptionalInt(
5756 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005757 ice_config.continual_gathering_policy = gathering_policy;
5758 ice_config.presume_writable_when_fully_relayed =
5759 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005760 ice_config.ice_check_interval_strong_connectivity =
5761 config.ice_check_interval_strong_connectivity;
5762 ice_config.ice_check_interval_weak_connectivity =
5763 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005764 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005765 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5766 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005767 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005768 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005769 ice_config.regather_all_networks_interval_range =
5770 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005771 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005772 return ice_config;
5773}
5774
Steve Anton75737c02017-11-06 10:37:17 -08005775bool PeerConnection::SendData(const cricket::SendDataParams& params,
5776 const rtc::CopyOnWriteBuffer& payload,
5777 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005778 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005779 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5780 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5781 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005782 return false;
5783 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005784 if (media_transport_) {
5785 SendDataParams send_params;
5786 send_params.type = ToWebrtcDataMessageType(params.type);
5787 send_params.ordered = params.ordered;
5788 if (params.max_rtx_count >= 0) {
5789 send_params.max_rtx_count = params.max_rtx_count;
5790 } else if (params.max_rtx_ms >= 0) {
5791 send_params.max_rtx_ms = params.max_rtx_ms;
5792 }
5793 return media_transport_->SendData(params.sid, send_params, payload).ok();
5794 }
Steve Anton75737c02017-11-06 10:37:17 -08005795 return rtp_data_channel_
5796 ? rtp_data_channel_->SendData(params, payload, result)
5797 : network_thread()->Invoke<bool>(
5798 RTC_FROM_HERE,
5799 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005800 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005801}
5802
5803bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005804 RTC_DCHECK_RUN_ON(signaling_thread());
5805 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005806 // Don't log an error here, because DataChannels are expected to call
5807 // ConnectDataChannel in this state. It's the only way to initially tell
5808 // whether or not the underlying transport is ready.
5809 return false;
5810 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005811 if (media_transport_) {
5812 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5813 &DataChannel::OnChannelReady);
5814 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5815 &DataChannel::OnDataReceived);
5816 SignalMediaTransportChannelClosing_s.connect(
5817 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5818 SignalMediaTransportChannelClosed_s.connect(
5819 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5820 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005821 rtp_data_channel_->SignalReadyToSendData.connect(
5822 webrtc_data_channel, &DataChannel::OnChannelReady);
5823 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5824 &DataChannel::OnDataReceived);
5825 } else {
5826 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5827 &DataChannel::OnChannelReady);
5828 SignalSctpDataReceived.connect(webrtc_data_channel,
5829 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005830 SignalSctpClosingProcedureStartedRemotely.connect(
5831 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5832 SignalSctpClosingProcedureComplete.connect(
5833 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005834 }
5835 return true;
5836}
5837
5838void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005839 RTC_DCHECK_RUN_ON(signaling_thread());
5840 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005841 RTC_LOG(LS_ERROR)
5842 << "DisconnectDataChannel called when rtp_data_channel_ and "
5843 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005844 return;
5845 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005846 if (media_transport_) {
5847 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5848 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5849 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5850 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5851 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005852 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5853 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5854 } else {
5855 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5856 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005857 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5858 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005859 }
5860}
5861
5862void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005863 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005864 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005865 return;
5866 }
Steve Anton75737c02017-11-06 10:37:17 -08005867 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005868 RTC_LOG(LS_ERROR)
5869 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005870 return;
5871 }
5872 network_thread()->Invoke<void>(
5873 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005874 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005875}
5876
5877void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005878 if (media_transport_) {
5879 media_transport_->CloseChannel(sid);
5880 return;
5881 }
Steve Anton75737c02017-11-06 10:37:17 -08005882 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005883 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005884 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005885 return;
5886 }
5887 network_thread()->Invoke<void>(
5888 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005889 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005890}
5891
5892bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005893 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005894 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005895 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005896 sctp_ready_to_send_data_;
5897}
5898
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005899void PeerConnection::OnDataReceived(int channel_id,
5900 DataMessageType type,
5901 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005902 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005903 cricket::ReceiveDataParams params;
5904 params.sid = channel_id;
5905 params.type = ToCricketDataMessageType(type);
5906 media_transport_invoker_->AsyncInvoke<void>(
5907 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5908 RTC_DCHECK_RUN_ON(signaling_thread());
5909 if (!HandleOpenMessage_s(params, buffer)) {
5910 SignalMediaTransportReceivedData_s(params, buffer);
5911 }
5912 });
5913}
5914
5915void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005916 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005917 media_transport_invoker_->AsyncInvoke<void>(
5918 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5919 RTC_DCHECK_RUN_ON(signaling_thread());
5920 SignalMediaTransportChannelClosing_s(channel_id);
5921 });
5922}
5923
5924void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005925 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005926 media_transport_invoker_->AsyncInvoke<void>(
5927 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5928 RTC_DCHECK_RUN_ON(signaling_thread());
5929 SignalMediaTransportChannelClosed_s(channel_id);
5930 });
5931}
5932
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005933absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005934 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005935 if (sctp_mid_ && transport_controller_) {
5936 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5937 if (dtls_transport) {
5938 return dtls_transport->transport_name();
5939 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005940 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005941 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005942 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005943}
5944
Qingsi Wang72a43a12018-02-20 16:03:18 -08005945cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5946 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005947 network_thread()->Invoke<void>(
5948 RTC_FROM_HERE,
5949 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5950 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005951 return candidate_states_list;
5952}
5953
Steve Anton5dfde182018-02-06 10:34:40 -08005954std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5955 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005956 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005957 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005958 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005959 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005960 if (channel) {
5961 transport_names_by_mid[channel->content_name()] =
5962 channel->transport_name();
5963 }
Steve Anton75737c02017-11-06 10:37:17 -08005964 }
Steve Anton5dfde182018-02-06 10:34:40 -08005965 if (rtp_data_channel_) {
5966 transport_names_by_mid[rtp_data_channel_->content_name()] =
5967 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005968 }
5969 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005970 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005971 RTC_DCHECK(transport_name);
5972 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005973 }
Steve Anton5dfde182018-02-06 10:34:40 -08005974 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005975}
5976
Steve Anton5dfde182018-02-06 10:34:40 -08005977std::map<std::string, cricket::TransportStats>
5978PeerConnection::GetTransportStatsByNames(
5979 const std::set<std::string>& transport_names) {
5980 if (!network_thread()->IsCurrent()) {
5981 return network_thread()
5982 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5983 RTC_FROM_HERE,
5984 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005985 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005986 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005987 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5988 for (const std::string& transport_name : transport_names) {
5989 cricket::TransportStats transport_stats;
5990 bool success =
5991 transport_controller_->GetStats(transport_name, &transport_stats);
5992 if (success) {
5993 transport_stats_by_name[transport_name] = std::move(transport_stats);
5994 } else {
5995 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5996 << transport_name;
5997 }
5998 }
5999 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006000}
6001
6002bool PeerConnection::GetLocalCertificate(
6003 const std::string& transport_name,
6004 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006005 if (!certificate) {
6006 return false;
6007 }
6008 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6009 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006010}
6011
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006012std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006013 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006014 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006015}
6016
6017cricket::DataChannelType PeerConnection::data_channel_type() const {
6018 return data_channel_type_;
6019}
6020
6021bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006022 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006023 return pending_ice_restarts_.find(content_name) !=
6024 pending_ice_restarts_.end();
6025}
6026
Steve Anton75737c02017-11-06 10:37:17 -08006027bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6028 return transport_controller_->NeedsIceRestart(content_name);
6029}
6030
6031void PeerConnection::OnCertificateReady(
6032 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6033 transport_controller_->SetLocalCertificate(certificate);
6034}
6035
6036void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006037 SetSessionError(SessionError::kTransport,
6038 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006039}
6040
Alex Loiko9289eda2018-11-23 16:18:59 +00006041void PeerConnection::OnTransportControllerConnectionState(
6042 cricket::IceConnectionState state) {
6043 switch (state) {
6044 case cricket::kIceConnectionConnecting:
6045 // If the current state is Connected or Completed, then there were
6046 // writable channels but now there are not, so the next state must
6047 // be Disconnected.
6048 // kIceConnectionConnecting is currently used as the default,
6049 // un-connected state by the TransportController, so its only use is
6050 // detecting disconnections.
6051 if (ice_connection_state_ ==
6052 PeerConnectionInterface::kIceConnectionConnected ||
6053 ice_connection_state_ ==
6054 PeerConnectionInterface::kIceConnectionCompleted) {
6055 SetIceConnectionState(
6056 PeerConnectionInterface::kIceConnectionDisconnected);
6057 }
6058 break;
6059 case cricket::kIceConnectionFailed:
6060 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6061 break;
6062 case cricket::kIceConnectionConnected:
6063 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6064 "all transports are writable.";
6065 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6066 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6067 break;
6068 case cricket::kIceConnectionCompleted:
6069 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6070 "all transports are complete.";
6071 if (ice_connection_state_ !=
6072 PeerConnectionInterface::kIceConnectionConnected) {
6073 // If jumping directly from "checking" to "connected",
6074 // signal "connected" first.
6075 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6076 }
6077 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6078 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6079 ReportTransportStats();
6080 break;
6081 default:
6082 RTC_NOTREACHED();
6083 }
6084}
6085
Steve Anton75737c02017-11-06 10:37:17 -08006086void PeerConnection::OnTransportControllerCandidatesGathered(
6087 const std::string& transport_name,
6088 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006089 int sdp_mline_index;
6090 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006091 RTC_LOG(LS_ERROR)
6092 << "OnTransportControllerCandidatesGathered: content name "
6093 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006094 return;
6095 }
6096
6097 for (cricket::Candidates::const_iterator citer = candidates.begin();
6098 citer != candidates.end(); ++citer) {
6099 // Use transport_name as the candidate media id.
6100 std::unique_ptr<JsepIceCandidate> candidate(
6101 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6102 if (local_description()) {
6103 mutable_local_description()->AddCandidate(candidate.get());
6104 }
6105 OnIceCandidate(std::move(candidate));
6106 }
6107}
6108
6109void PeerConnection::OnTransportControllerCandidatesRemoved(
6110 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006111 // Sanity check.
6112 for (const cricket::Candidate& candidate : candidates) {
6113 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006114 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006115 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006116 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006117 return;
6118 }
6119 }
6120
6121 if (local_description()) {
6122 mutable_local_description()->RemoveCandidates(candidates);
6123 }
6124 OnIceCandidatesRemoved(candidates);
6125}
6126
6127void PeerConnection::OnTransportControllerDtlsHandshakeError(
6128 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006129 RTC_HISTOGRAM_ENUMERATION(
6130 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6131 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006132}
6133
Steve Antoned10bd92017-12-05 10:52:59 -08006134void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006135 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006136 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006137 if (channel && !channel->enabled()) {
6138 channel->Enable(true);
6139 }
Steve Anton75737c02017-11-06 10:37:17 -08006140 }
6141
Steve Anton4171afb2017-11-20 10:20:22 -08006142 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006143 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006144 }
Steve Anton75737c02017-11-06 10:37:17 -08006145}
6146
6147// Returns the media index for a local ice candidate given the content name.
6148bool PeerConnection::GetLocalCandidateMediaIndex(
6149 const std::string& content_name,
6150 int* sdp_mline_index) {
6151 if (!local_description() || !sdp_mline_index) {
6152 return false;
6153 }
6154
6155 bool content_found = false;
6156 const ContentInfos& contents = local_description()->description()->contents();
6157 for (size_t index = 0; index < contents.size(); ++index) {
6158 if (contents[index].name == content_name) {
6159 *sdp_mline_index = static_cast<int>(index);
6160 content_found = true;
6161 break;
6162 }
6163 }
6164 return content_found;
6165}
6166
6167bool PeerConnection::UseCandidatesInSessionDescription(
6168 const SessionDescriptionInterface* remote_desc) {
6169 if (!remote_desc) {
6170 return true;
6171 }
6172 bool ret = true;
6173
6174 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6175 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6176 for (size_t n = 0; n < candidates->count(); ++n) {
6177 const IceCandidateInterface* candidate = candidates->at(n);
6178 bool valid = false;
6179 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6180 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006181 RTC_LOG(LS_INFO)
6182 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006183 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006184 }
6185 continue;
6186 }
6187 ret = UseCandidate(candidate);
6188 if (!ret) {
6189 break;
6190 }
6191 }
6192 }
6193 return ret;
6194}
6195
6196bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6197 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6198 size_t remote_content_size =
6199 remote_description()->description()->contents().size();
6200 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006201 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006202 return false;
6203 }
6204
6205 cricket::ContentInfo content =
6206 remote_description()->description()->contents()[mediacontent_index];
6207 std::vector<cricket::Candidate> candidates;
6208 candidates.push_back(candidate->candidate());
6209 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006210 RTCError error =
6211 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006212 if (error.ok()) {
6213 // Candidates successfully submitted for checking.
6214 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6215 ice_connection_state_ ==
6216 PeerConnectionInterface::kIceConnectionDisconnected) {
6217 // If state is New, then the session has just gotten its first remote ICE
6218 // candidates, so go to Checking.
6219 // If state is Disconnected, the session is re-using old candidates or
6220 // receiving additional ones, so go to Checking.
6221 // If state is Connected, stay Connected.
6222 // TODO(bemasc): If state is Connected, and the new candidates are for a
6223 // newly added transport, then the state actually _should_ move to
6224 // checking. Add a way to distinguish that case.
6225 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6226 }
6227 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006228 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006229 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006230 }
6231 return true;
6232}
6233
6234void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006235 // Destroy video channel first since it may have a pointer to the
6236 // voice channel.
6237 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006238 if (!video_info || video_info->rejected) {
6239 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006240 }
6241
Steve Anton6fec8802017-12-04 10:37:29 -08006242 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6243 if (!audio_info || audio_info->rejected) {
6244 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006245 }
6246
6247 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6248 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006249 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006250 }
6251}
6252
Steve Antondcc3c022017-12-22 16:02:54 -08006253RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6254 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006255 const cricket::ContentGroup* bundle_group = nullptr;
6256 if (configuration_.bundle_policy ==
6257 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006258 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006259 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006260 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6261 "max-bundle configured but session description "
6262 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006263 }
6264 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006265 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006266}
6267
6268RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006269 // Creating the media channels. Transports should already have been created
6270 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006271 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006272 if (voice && !voice->rejected &&
6273 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006274 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006275 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006276 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6277 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006278 }
6279 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6280 }
6281
Steve Antondcc3c022017-12-22 16:02:54 -08006282 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006283 if (video && !video->rejected &&
6284 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006285 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006286 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006287 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6288 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006289 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006290 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006291 }
6292
Steve Antondcc3c022017-12-22 16:02:54 -08006293 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006294 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006295 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006296 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006297 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6298 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006299 }
6300 }
6301
Steve Anton8a006912017-12-04 15:25:56 -08006302 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006303}
6304
Steve Anton4171afb2017-11-20 10:20:22 -08006305// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006306cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006307 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006308 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006309 MediaTransportInterface* media_transport = nullptr;
6310 if (configuration_.use_media_transport) {
6311 media_transport = GetMediaTransport(mid);
6312 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006313
Steve Anton75737c02017-11-06 10:37:17 -08006314 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006315 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006316 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006317 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006318 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006319 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006320 }
Steve Anton75737c02017-11-06 10:37:17 -08006321 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6322 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006323 voice_channel->SignalSentPacket.connect(this,
6324 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006325 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006326
Steve Antoneda6ccd2017-12-04 10:21:55 -08006327 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006328}
6329
Steve Anton4171afb2017-11-20 10:20:22 -08006330// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006331cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006332 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006333 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006334 MediaTransportInterface* media_transport = nullptr;
6335 if (configuration_.use_media_transport) {
6336 media_transport = GetMediaTransport(mid);
6337 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006338
Steve Anton75737c02017-11-06 10:37:17 -08006339 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006340 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006341 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02006342 &ssrc_generator_, video_options_, video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006343 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006344 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006345 }
Steve Anton75737c02017-11-06 10:37:17 -08006346 video_channel->SignalDtlsSrtpSetupFailure.connect(
6347 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006348 video_channel->SignalSentPacket.connect(this,
6349 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006350 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006351
Steve Antoneda6ccd2017-12-04 10:21:55 -08006352 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006353}
6354
Zhi Huange830e682018-03-30 10:48:35 -07006355bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006356 switch (data_channel_type_) {
6357 case cricket::DCT_MEDIA_TRANSPORT:
6358 if (network_thread()->Invoke<bool>(
6359 RTC_FROM_HERE,
6360 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6361 this, mid))) {
6362 for (const auto& channel : sctp_data_channels_) {
6363 channel->OnTransportChannelCreated();
6364 }
6365 return true;
6366 }
Steve Anton75737c02017-11-06 10:37:17 -08006367 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006368 case cricket::DCT_SCTP:
6369 if (!sctp_factory_) {
6370 RTC_LOG(LS_ERROR)
6371 << "Trying to create SCTP transport, but didn't compile with "
6372 "SCTP support (HAVE_SCTP)";
6373 return false;
6374 }
6375 if (!network_thread()->Invoke<bool>(
6376 RTC_FROM_HERE,
6377 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6378 return false;
6379 }
6380 for (const auto& channel : sctp_data_channels_) {
6381 channel->OnTransportChannelCreated();
6382 }
6383 return true;
6384 case cricket::DCT_RTP:
6385 default:
6386 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6387 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6388 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006389 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006390 if (!rtp_data_channel_) {
6391 return false;
6392 }
6393 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6394 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6395 rtp_data_channel_->SignalSentPacket.connect(
6396 this, &PeerConnection::OnSentPacket_w);
6397 rtp_data_channel_->SetRtpTransport(rtp_transport);
6398 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006399 }
6400
Steve Anton75737c02017-11-06 10:37:17 -08006401 return true;
6402}
6403
6404Call::Stats PeerConnection::GetCallStats() {
6405 if (!worker_thread()->IsCurrent()) {
6406 return worker_thread()->Invoke<Call::Stats>(
6407 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6408 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006409 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006410 if (call_) {
6411 return call_->GetStats();
6412 } else {
6413 return Call::Stats();
6414 }
6415}
6416
Zhi Huange830e682018-03-30 10:48:35 -07006417bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006418 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006419 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006420 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6421 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006422 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006423 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006424 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006425 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6426 sctp_factory_->CreateSctpTransport(dtls_transport);
6427 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006428 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006429 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006430 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006431 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006432 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006433 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6434 // another thread. Would be nice if there was a helper class similar to
6435 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6436 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006437 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006438 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006439 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006440 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006441 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006442 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6443 std::move(cricket_sctp_transport));
6444 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006445 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006446}
6447
6448void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006449 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006450 sctp_transport_->Clear();
6451 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006452 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006453 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006454}
6455
6456void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006457 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006458 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006459 // Note: Cannot use rtc::Bind here because it will grab a reference to
6460 // PeerConnection and potentially cause PeerConnection to live longer than
6461 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6462 // be destroyed before PeerConnection is destroyed, and at that point all
6463 // pending tasks will be cleared.
6464 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6465 OnSctpTransportReadyToSendData_s(true);
6466 });
6467}
6468
6469void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006470 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006471 sctp_ready_to_send_data_ = ready;
6472 SignalSctpReadyToSendData(ready);
6473}
6474
6475void PeerConnection::OnSctpTransportDataReceived_n(
6476 const cricket::ReceiveDataParams& params,
6477 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006478 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006479 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006480 // Note: Cannot use rtc::Bind here because it will grab a reference to
6481 // PeerConnection and potentially cause PeerConnection to live longer than
6482 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6483 // be destroyed before PeerConnection is destroyed, and at that point all
6484 // pending tasks will be cleared.
6485 sctp_invoker_->AsyncInvoke<void>(
6486 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6487 OnSctpTransportDataReceived_s(params, payload);
6488 });
6489}
6490
6491void PeerConnection::OnSctpTransportDataReceived_s(
6492 const cricket::ReceiveDataParams& params,
6493 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006494 RTC_DCHECK_RUN_ON(signaling_thread());
6495 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006496 SignalSctpDataReceived(params, payload);
6497 }
6498}
6499
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006500void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006501 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006502 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006503 sctp_invoker_->AsyncInvoke<void>(
6504 RTC_FROM_HERE, signaling_thread(),
6505 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006506 &SignalSctpClosingProcedureStartedRemotely, sid));
6507}
6508
6509void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006510 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006511 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006512 sctp_invoker_->AsyncInvoke<void>(
6513 RTC_FROM_HERE, signaling_thread(),
6514 rtc::Bind(&sigslot::signal1<int>::operator(),
6515 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006516}
6517
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006518bool PeerConnection::SetupMediaTransportForDataChannels_n(
6519 const std::string& mid) {
6520 media_transport_ = transport_controller_->GetMediaTransport(mid);
6521 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006522 RTC_LOG(LS_ERROR)
6523 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006524 return false;
6525 }
6526
6527 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6528 media_transport_->SetDataSink(this);
6529 media_transport_data_mid_ = mid;
6530 transport_controller_->SignalMediaTransportStateChanged.connect(
6531 this, &PeerConnection::OnMediaTransportStateChanged_n);
6532 // Check the initial state right away, in case transport is already writable.
6533 OnMediaTransportStateChanged_n();
6534 return true;
6535}
6536
6537void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6538 if (!media_transport_) {
6539 return;
6540 }
6541 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6542 media_transport_data_mid_.reset();
6543 media_transport_->SetDataSink(nullptr);
6544 media_transport_invoker_ = nullptr;
6545 media_transport_ = nullptr;
6546}
6547
6548void PeerConnection::OnMediaTransportStateChanged_n() {
6549 if (!media_transport_data_mid_ ||
6550 transport_controller_->GetMediaTransportState(
6551 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6552 return;
6553 }
6554 media_transport_invoker_->AsyncInvoke<void>(
6555 RTC_FROM_HERE, signaling_thread(), [this] {
6556 RTC_DCHECK_RUN_ON(signaling_thread());
6557 media_transport_ready_to_send_data_ = true;
6558 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6559 });
6560}
6561
Steve Anton75737c02017-11-06 10:37:17 -08006562// Returns false if bundle is enabled and rtcp_mux is disabled.
6563bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6564 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6565 if (!bundle_enabled)
6566 return true;
6567
6568 const cricket::ContentGroup* bundle_group =
6569 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6570 RTC_DCHECK(bundle_group != NULL);
6571
6572 const cricket::ContentInfos& contents = desc->contents();
6573 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6574 citer != contents.end(); ++citer) {
6575 const cricket::ContentInfo* content = (&*citer);
6576 RTC_DCHECK(content != NULL);
6577 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006578 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006579 if (!HasRtcpMuxEnabled(content))
6580 return false;
6581 }
6582 }
6583 // RTCP-MUX is enabled in all the contents.
6584 return true;
6585}
6586
6587bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006588 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006589}
6590
Steve Anton06817cd2018-12-18 15:55:30 -08006591static RTCError ValidateMids(const cricket::SessionDescription& description) {
6592 std::set<std::string> mids;
6593 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006594 if (content.name.empty()) {
6595 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6596 "A media section is missing a MID attribute.");
6597 }
Steve Anton06817cd2018-12-18 15:55:30 -08006598 if (!mids.insert(content.name).second) {
6599 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6600 "Duplicate a=mid value '" + content.name + "'.");
6601 }
6602 }
6603 return RTCError::OK();
6604}
6605
Steve Anton8a006912017-12-04 15:25:56 -08006606RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006607 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006608 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006609 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006610 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006611 }
6612
6613 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006614 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006615 }
6616
Steve Anton3828c062017-12-06 10:34:51 -08006617 SdpType type = sdesc->GetType();
6618 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6619 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006620 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006621 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006622 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006623 }
6624
Steve Anton06817cd2018-12-18 15:55:30 -08006625 RTCError error = ValidateMids(*sdesc->description());
6626 if (!error.ok()) {
6627 return error;
6628 }
6629
Steve Anton75737c02017-11-06 10:37:17 -08006630 // Verify crypto settings.
6631 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006632 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6633 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006634 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006635 if (!crypto_error.ok()) {
6636 return crypto_error;
6637 }
Steve Anton75737c02017-11-06 10:37:17 -08006638 }
6639
6640 // Verify ice-ufrag and ice-pwd.
6641 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6643 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006644 }
6645
6646 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6648 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006649 }
6650
6651 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6652 // m-lines that do not rtcp-mux enabled.
6653
6654 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006655 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006656 // With an answer we want to compare the new answer session description with
6657 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006658 const cricket::SessionDescription* offer_desc =
6659 (source == cricket::CS_LOCAL) ? remote_description()->description()
6660 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006661 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6662 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6663 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6665 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006666 }
6667 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006668 // The re-offers should respect the order of m= sections in current
6669 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006670 // With a re-offer, either the current local or current remote descriptions
6671 // could be the most up to date, so we would like to check against both of
6672 // them if they exist. It could be the case that one of them has a 0 port
6673 // for a media section, but the other does not. This is important to check
6674 // against in the case that we are recycling an m= section.
6675 const cricket::SessionDescription* current_desc = nullptr;
6676 const cricket::SessionDescription* secondary_current_desc = nullptr;
6677 if (local_description()) {
6678 current_desc = local_description()->description();
6679 if (remote_description()) {
6680 secondary_current_desc = remote_description()->description();
6681 }
6682 } else if (remote_description()) {
6683 current_desc = remote_description()->description();
6684 }
Steve Anton75737c02017-11-06 10:37:17 -08006685 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006686 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6687 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006688 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6689 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006690 }
6691 }
6692
Steve Antonba42e992018-04-09 14:10:01 -07006693 if (IsUnifiedPlan()) {
6694 // Ensure that each audio and video media section has at most one
6695 // "StreamParams". This will return an error if receiving a session
6696 // description from a "Plan B" endpoint which adds multiple tracks of the
6697 // same type. With Unified Plan, there can only be at most one track per
6698 // media section.
6699 for (const ContentInfo& content : sdesc->description()->contents()) {
6700 const MediaContentDescription& desc = *content.description;
6701 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6702 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6703 desc.streams().size() > 1u) {
6704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6705 "Media section has more than one track specified "
6706 "with a=ssrc lines which is not supported with "
6707 "Unified Plan.");
6708 }
6709 }
6710 }
6711
Steve Anton8a006912017-12-04 15:25:56 -08006712 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006713}
6714
Steve Anton3828c062017-12-06 10:34:51 -08006715bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006716 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006717 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006718 return (state == PeerConnectionInterface::kStable) ||
6719 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006720 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006721 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006722 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6723 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6724 }
6725}
6726
Steve Anton3828c062017-12-06 10:34:51 -08006727bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006728 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006729 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006730 return (state == PeerConnectionInterface::kStable) ||
6731 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006732 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006733 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006734 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6735 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6736 }
6737}
6738
Steve Antonf8470812017-12-04 10:46:21 -08006739const char* PeerConnection::SessionErrorToString(SessionError error) const {
6740 switch (error) {
6741 case SessionError::kNone:
6742 return "ERROR_NONE";
6743 case SessionError::kContent:
6744 return "ERROR_CONTENT";
6745 case SessionError::kTransport:
6746 return "ERROR_TRANSPORT";
6747 }
6748 RTC_NOTREACHED();
6749 return "";
6750}
6751
Steve Anton75737c02017-11-06 10:37:17 -08006752std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006753 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006754 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6755 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006756 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006757}
6758
Steve Anton8e20f172018-03-06 10:55:04 -08006759void PeerConnection::ReportSdpFormatReceived(
6760 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006761 int num_audio_mlines = 0;
6762 int num_video_mlines = 0;
6763 int num_audio_tracks = 0;
6764 int num_video_tracks = 0;
6765 for (const ContentInfo& content : remote_offer.description()->contents()) {
6766 cricket::MediaType media_type = content.media_description()->type();
6767 int num_tracks = std::max(
6768 1, static_cast<int>(content.media_description()->streams().size()));
6769 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6770 num_audio_mlines += 1;
6771 num_audio_tracks += num_tracks;
6772 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6773 num_video_mlines += 1;
6774 num_video_tracks += num_tracks;
6775 }
6776 }
6777 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6778 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6779 format = kSdpFormatReceivedComplexUnifiedPlan;
6780 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6781 format = kSdpFormatReceivedComplexPlanB;
6782 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6783 format = kSdpFormatReceivedSimple;
6784 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006785 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6786 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006787}
6788
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006789void PeerConnection::NoteUsageEvent(UsageEvent event) {
6790 RTC_DCHECK_RUN_ON(signaling_thread());
6791 usage_event_accumulator_ |= static_cast<int>(event);
6792}
6793
6794void PeerConnection::ReportUsagePattern() const {
6795 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006796 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6797 usage_event_accumulator_,
6798 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006799 const int bad_bits =
6800 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6801 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6802 const int good_bits =
6803 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6804 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6805 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6806 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6807 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006808 // If called after close(), we can't report, because observer may have
6809 // been deallocated, and therefore pointer is null. Write to log instead.
6810 if (observer_) {
6811 Observer()->OnInterestingUsage(usage_event_accumulator_);
6812 } else {
6813 RTC_LOG(LS_INFO) << "Interesting usage signature "
6814 << usage_event_accumulator_
6815 << " observed after observer shutdown";
6816 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006817 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006818}
6819
Steve Anton0ffaaa22018-02-23 10:31:30 -08006820void PeerConnection::ReportNegotiatedSdpSemantics(
6821 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006822 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006823 switch (answer.description()->msid_signaling()) {
6824 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006825 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006826 break;
6827 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006828 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006829 break;
6830 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006831 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006832 break;
6833 case cricket::kMsidSignalingMediaSection |
6834 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006835 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006836 break;
6837 default:
6838 RTC_NOTREACHED();
6839 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006840 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6841 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006842}
6843
Steve Anton75737c02017-11-06 10:37:17 -08006844// We need to check the local/remote description for the Transport instead of
6845// the session, because a new Transport added during renegotiation may have
6846// them unset while the session has them set from the previous negotiation.
6847// Not doing so may trigger the auto generation of transport description and
6848// mess up DTLS identity information, ICE credential, etc.
6849bool PeerConnection::ReadyToUseRemoteCandidate(
6850 const IceCandidateInterface* candidate,
6851 const SessionDescriptionInterface* remote_desc,
6852 bool* valid) {
6853 *valid = true;
6854
6855 const SessionDescriptionInterface* current_remote_desc =
6856 remote_desc ? remote_desc : remote_description();
6857
6858 if (!current_remote_desc) {
6859 return false;
6860 }
6861
6862 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6863 size_t remote_content_size =
6864 current_remote_desc->description()->contents().size();
6865 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006866 RTC_LOG(LS_ERROR)
6867 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6868 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006869
6870 *valid = false;
6871 return false;
6872 }
6873
6874 cricket::ContentInfo content =
6875 current_remote_desc->description()->contents()[mediacontent_index];
6876
6877 const std::string transport_name = GetTransportName(content.name);
6878 if (transport_name.empty()) {
6879 return false;
6880 }
Zhi Huange830e682018-03-30 10:48:35 -07006881 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006882}
6883
6884bool PeerConnection::SrtpRequired() const {
6885 return dtls_enabled_ ||
6886 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6887}
6888
6889void PeerConnection::OnTransportControllerGatheringState(
6890 cricket::IceGatheringState state) {
6891 RTC_DCHECK(signaling_thread()->IsCurrent());
6892 if (state == cricket::kIceGatheringGathering) {
6893 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6894 } else if (state == cricket::kIceGatheringComplete) {
6895 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6896 }
6897}
6898
6899void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006900 std::map<std::string, std::set<cricket::MediaType>>
6901 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006902 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006903 if (transceiver->internal()->channel()) {
6904 const std::string& transport_name =
6905 transceiver->internal()->channel()->transport_name();
6906 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006907 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006908 }
Steve Anton75737c02017-11-06 10:37:17 -08006909 }
6910 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006911 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6912 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006913 }
Zhi Huange830e682018-03-30 10:48:35 -07006914
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006915 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006916 if (transport_name) {
6917 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006918 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006919 }
Zhi Huange830e682018-03-30 10:48:35 -07006920
Steve Antonc7b964c2018-02-01 14:39:45 -08006921 for (const auto& entry : media_types_by_transport_name) {
6922 const std::string& transport_name = entry.first;
6923 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006924 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006925 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006926 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006927 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006928 }
6929 }
6930}
6931// Walk through the ConnectionInfos to gather best connection usage
6932// for IPv4 and IPv6.
6933void PeerConnection::ReportBestConnectionState(
6934 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006935 for (const cricket::TransportChannelStats& channel_stats :
6936 stats.channel_stats) {
6937 for (const cricket::ConnectionInfo& connection_info :
6938 channel_stats.connection_infos) {
6939 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006940 continue;
6941 }
6942
Steve Antonc7b964c2018-02-01 14:39:45 -08006943 const cricket::Candidate& local = connection_info.local_candidate;
6944 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006945
6946 // Increment the counter for IceCandidatePairType.
6947 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6948 (local.type() == RELAY_PORT_TYPE &&
6949 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006950 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6951 GetIceCandidatePairCounter(local, remote),
6952 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006953 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006954 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6955 GetIceCandidatePairCounter(local, remote),
6956 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006957 } else {
6958 RTC_CHECK(0);
6959 }
Steve Anton75737c02017-11-06 10:37:17 -08006960
6961 // Increment the counter for IP type.
6962 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006963 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6964 kBestConnections_IPv4,
6965 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006966 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006967 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6968 kBestConnections_IPv6,
6969 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006970 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006971 RTC_CHECK(!local.address().hostname().empty() &&
6972 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006973 }
6974
6975 return;
6976 }
6977 }
6978}
6979
6980void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006981 const cricket::TransportStats& stats,
6982 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006983 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6984 return;
6985 }
6986
6987 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6988 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6989 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6990 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6991 return;
6992 }
6993
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006994 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6995 for (cricket::MediaType media_type : media_types) {
6996 switch (media_type) {
6997 case cricket::MEDIA_TYPE_AUDIO:
6998 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6999 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7000 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7001 break;
7002 case cricket::MEDIA_TYPE_VIDEO:
7003 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7004 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7005 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7006 break;
7007 case cricket::MEDIA_TYPE_DATA:
7008 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7009 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7010 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7011 break;
7012 default:
7013 RTC_NOTREACHED();
7014 continue;
7015 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007016 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007017 }
7018
7019 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7020 for (cricket::MediaType media_type : media_types) {
7021 switch (media_type) {
7022 case cricket::MEDIA_TYPE_AUDIO:
7023 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7024 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7025 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7026 break;
7027 case cricket::MEDIA_TYPE_VIDEO:
7028 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7029 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7030 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7031 break;
7032 case cricket::MEDIA_TYPE_DATA:
7033 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7034 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7035 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7036 break;
7037 default:
7038 RTC_NOTREACHED();
7039 continue;
7040 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007041 }
Steve Anton75737c02017-11-06 10:37:17 -08007042 }
7043}
7044
7045void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007046 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007047 RTC_DCHECK(call_);
7048 call_->OnSentPacket(sent_packet);
7049}
7050
7051const std::string PeerConnection::GetTransportName(
7052 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007053 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007054 if (channel) {
7055 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007056 }
Steve Anton6fec8802017-12-04 10:37:29 -08007057 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007058 RTC_DCHECK(sctp_mid_);
7059 if (content_name == *sctp_mid_) {
7060 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007061 }
7062 }
7063 // Return an empty string if failed to retrieve the transport name.
7064 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007065}
7066
Steve Anton6fec8802017-12-04 10:37:29 -08007067void PeerConnection::DestroyTransceiverChannel(
7068 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7069 transceiver) {
7070 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007071
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007072 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007073 if (channel) {
7074 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007075 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007076 }
7077}
7078
7079void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007080 if (rtp_data_channel_) {
7081 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007082 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007083 rtp_data_channel_ = nullptr;
7084 }
7085
7086 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7087 // grab a reference to this PeerConnection. If this is called from the
7088 // PeerConnection destructor, the RefCountedObject vtable will have already
7089 // been destroyed (since it is a subclass of PeerConnection) and using
7090 // rtc::Bind will cause "Pure virtual function called" error to appear.
7091
7092 if (sctp_transport_) {
7093 OnDataChannelDestroyed();
7094 network_thread()->Invoke<void>(RTC_FROM_HERE,
7095 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007096 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007097 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007098
7099 if (media_transport_) {
7100 OnDataChannelDestroyed();
7101 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7102 RTC_DCHECK_RUN_ON(network_thread());
7103 TeardownMediaTransportForDataChannels_n();
7104 });
7105 }
Steve Anton6fec8802017-12-04 10:37:29 -08007106}
7107
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007108void PeerConnection::DestroyChannelInterface(
7109 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007110 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007111 switch (channel->media_type()) {
7112 case cricket::MEDIA_TYPE_AUDIO:
7113 channel_manager()->DestroyVoiceChannel(
7114 static_cast<cricket::VoiceChannel*>(channel));
7115 break;
7116 case cricket::MEDIA_TYPE_VIDEO:
7117 channel_manager()->DestroyVideoChannel(
7118 static_cast<cricket::VideoChannel*>(channel));
7119 break;
7120 case cricket::MEDIA_TYPE_DATA:
7121 channel_manager()->DestroyRtpDataChannel(
7122 static_cast<cricket::RtpDataChannel*>(channel));
7123 break;
7124 default:
7125 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7126 break;
7127 }
Zhi Huange830e682018-03-30 10:48:35 -07007128}
Steve Anton6fec8802017-12-04 10:37:29 -08007129
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007130bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007131 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007132 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007133 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007134 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007135 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007136 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007137 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007138 auto base_channel = GetChannel(mid);
7139 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007140 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007141 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007142 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007143 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007144 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007145
Karl Wiberg5966c502019-02-21 23:55:09 +01007146 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007147 // Only pass media transport to call object if media transport is used
7148 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007149 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007150 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007151
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007152 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007153}
7154
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007155PeerConnectionObserver* PeerConnection::Observer() const {
7156 // In earlier production code, the pointer was not cleared on close,
7157 // which might have led to undefined behavior if the observer was not
7158 // deallocated, or strange crashes if it was.
7159 // We use CHECK in order to catch such behavior if it exists.
7160 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7161 RTC_CHECK(observer_);
7162 return observer_;
7163}
7164
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007165CryptoOptions PeerConnection::GetCryptoOptions() {
7166 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7167 // after it has been removed.
7168 return configuration_.crypto_options.has_value()
7169 ? *configuration_.crypto_options
7170 : factory_->options().crypto_options;
7171}
7172
Harald Alvestrand89061872018-01-02 14:08:34 +01007173void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007174 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007175 if (stats_collector_) {
7176 stats_collector_->ClearCachedStatsReport();
7177 }
7178}
7179
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007180void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007181 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7182 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007183}
7184
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007185void PeerConnection::UpdateNegotiationNeeded() {
7186 RTC_DCHECK_RUN_ON(signaling_thread());
7187 if (!IsUnifiedPlan()) {
7188 Observer()->OnRenegotiationNeeded();
7189 return;
7190 }
7191
7192 // If connection's [[IsClosed]] slot is true, abort these steps.
7193 if (IsClosed())
7194 return;
7195
7196 // If connection's signaling state is not "stable", abort these steps.
7197 if (signaling_state() != kStable)
7198 return;
7199
7200 // NOTE
7201 // The negotiation-needed flag will be updated once the state transitions to
7202 // "stable", as part of the steps for setting an RTCSessionDescription.
7203
7204 // If the result of checking if negotiation is needed is false, clear the
7205 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7206 // to false, and abort these steps.
7207 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7208 if (!is_negotiation_needed) {
7209 is_negotiation_needed_ = false;
7210 return;
7211 }
7212
7213 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7214 // steps.
7215 if (is_negotiation_needed_)
7216 return;
7217
7218 // Set connection's [[NegotiationNeeded]] slot to true.
7219 is_negotiation_needed_ = true;
7220
7221 // Queue a task that runs the following steps:
7222 // If connection's [[IsClosed]] slot is true, abort these steps.
7223 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7224 // Fire an event named negotiationneeded at connection.
7225 Observer()->OnRenegotiationNeeded();
7226}
7227
7228bool PeerConnection::CheckIfNegotiationIsNeeded() {
7229 RTC_DCHECK_RUN_ON(signaling_thread());
7230 // 1. If any implementation-specific negotiation is required, as described at
7231 // the start of this section, return true.
7232
7233 // 2. Let description be connection.[[CurrentLocalDescription]].
7234 const SessionDescriptionInterface* description = current_local_description();
7235 if (!description)
7236 return true;
7237
7238 // 3. If connection has created any RTCDataChannels, and no m= section in
7239 // description has been negotiated yet for data, return true.
7240 if (!sctp_data_channels_.empty()) {
7241 if (!cricket::GetFirstDataContent(description->description()->contents()))
7242 return true;
7243 }
7244
7245 // 4. For each transceiver in connection's set of transceivers, perform the
7246 // following checks:
7247 for (const auto& transceiver : transceivers_) {
7248 const ContentInfo* current_local_msection =
7249 FindTransceiverMSection(transceiver.get(), description);
7250
7251 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7252 transceiver.get(), current_remote_description());
7253
7254 // 4.3 If transceiver is stopped and is associated with an m= section,
7255 // but the associated m= section is not yet rejected in
7256 // connection.[[CurrentLocalDescription]] or
7257 // connection.[[CurrentRemoteDescription]], return true.
7258 if (transceiver->stopped()) {
7259 if (current_local_msection && !current_local_msection->rejected &&
7260 ((current_remote_msection && !current_remote_msection->rejected) ||
7261 !current_remote_msection)) {
7262 return true;
7263 }
7264 continue;
7265 }
7266
7267 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7268 // section in description, return true.
7269 if (!current_local_msection)
7270 return true;
7271
7272 const MediaContentDescription* current_local_media_description =
7273 current_local_msection->media_description();
7274 // 4.2 If transceiver isn't stopped and is associated with an m= section
7275 // in description then perform the following checks:
7276
7277 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7278 // associated m= section in description either doesn't contain a single
7279 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7280 // m= section, or the MSID values themselves, differ from what is in
7281 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7282 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7283 if (current_local_media_description->streams().size() == 0)
7284 return true;
7285
7286 std::vector<std::string> msection_msids;
7287 for (const auto& stream : current_local_media_description->streams()) {
7288 for (const std::string& msid : stream.stream_ids())
7289 msection_msids.push_back(msid);
7290 }
7291
7292 std::vector<std::string> transceiver_msids =
7293 transceiver->sender()->stream_ids();
7294 if (msection_msids.size() != transceiver_msids.size())
7295 return true;
7296
7297 absl::c_sort(transceiver_msids);
7298 absl::c_sort(msection_msids);
7299 if (transceiver_msids != msection_msids)
7300 return true;
7301 }
7302
7303 // 4.2.2 If description is of type "offer", and the direction of the
7304 // associated m= section in neither connection.[[CurrentLocalDescription]]
7305 // nor connection.[[CurrentRemoteDescription]] matches
7306 // transceiver.[[Direction]], return true.
7307 if (description->GetType() == SdpType::kOffer) {
7308 if (!current_remote_description())
7309 return true;
7310
7311 if (!current_remote_msection)
7312 return true;
7313
7314 RtpTransceiverDirection current_local_direction =
7315 current_local_media_description->direction();
7316 RtpTransceiverDirection current_remote_direction =
7317 current_remote_msection->media_description()->direction();
7318 if (transceiver->direction() != current_local_direction &&
7319 transceiver->direction() !=
7320 RtpTransceiverDirectionReversed(current_remote_direction)) {
7321 return true;
7322 }
7323 }
7324
7325 // 4.2.3 If description is of type "answer", and the direction of the
7326 // associated m= section in the description does not match
7327 // transceiver.[[Direction]] intersected with the offered direction (as
7328 // described in [JSEP] (section 5.3.1.)), return true.
7329 if (description->GetType() == SdpType::kAnswer) {
7330 if (!remote_description())
7331 return true;
7332
7333 const ContentInfo* offered_remote_msection =
7334 FindTransceiverMSection(transceiver.get(), remote_description());
7335
7336 RtpTransceiverDirection offered_direction =
7337 offered_remote_msection
7338 ? offered_remote_msection->media_description()->direction()
7339 : RtpTransceiverDirection::kInactive;
7340
7341 if (current_local_media_description->direction() !=
7342 (RtpTransceiverDirectionIntersection(
7343 transceiver->direction(),
7344 RtpTransceiverDirectionReversed(offered_direction)))) {
7345 return true;
7346 }
7347 }
7348 }
7349
7350 // If all the preceding checks were performed and true was not returned,
7351 // nothing remains to be negotiated; return false.
7352 return false;
7353}
7354
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007355} // namespace webrtc