blob: f7cfc9a71a97308be8879f698e264cac2a9e1902 [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"
28#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020030#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020033#include "logging/rtc_event_log/output/rtc_event_log_output_file.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) {
Danil Chapovalovc6d1d242019-04-23 09:48:11 +0000562 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 }
Danil Chapovalovc6d1d242019-04-23 09:48:11 +0000568 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(
1706 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001707 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001708 transceiver->internal()->SignalNegotiationNeeded.connect(
1709 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001710 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001711}
1712
Steve Anton52d86772018-02-20 15:48:12 -08001713void PeerConnection::OnNegotiationNeeded() {
1714 RTC_DCHECK_RUN_ON(signaling_thread());
1715 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001716 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001717}
1718
deadbeeffac06552015-11-25 11:26:01 -08001719rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001720 const std::string& kind,
1721 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001722 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001723 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1724 "Plan SdpSemantics. Please use AddTransceiver "
1725 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001726 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001727 if (IsClosed()) {
1728 return nullptr;
1729 }
Steve Anton4171afb2017-11-20 10:20:22 -08001730
Seth Hampson5b4f0752018-04-02 16:31:36 -07001731 // Internally we need to have one stream with Plan B semantics, so we
1732 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001733 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001734 if (stream_id.empty()) {
1735 stream_ids.push_back(rtc::CreateRandomUuid());
1736 RTC_LOG(LS_INFO)
1737 << "No stream_id specified for sender. Generated stream ID: "
1738 << stream_ids[0];
1739 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001740 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001741 }
1742
Steve Anton4171afb2017-11-20 10:20:22 -08001743 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001744 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001745 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001746 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001747 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001748 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001749 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001750 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001751 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001752 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001753 auto video_sender =
1754 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001755 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001756 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001757 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001758 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001759 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001761 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001762 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001763 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001764
deadbeefe1f9d832016-01-14 15:35:42 -08001765 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001766}
1767
deadbeef70ab1a12015-09-28 16:53:55 -07001768std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1769 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001770 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001771 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001772 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001773 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001774 }
1775 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001776}
1777
Steve Anton4171afb2017-11-20 10:20:22 -08001778std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1779PeerConnection::GetSendersInternal() const {
1780 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1781 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001782 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001783 auto senders = transceiver->internal()->senders();
1784 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1785 }
1786 return all_senders;
1787}
1788
deadbeef70ab1a12015-09-28 16:53:55 -07001789std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1790PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001791 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001792 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001793 for (const auto& receiver : GetReceiversInternal()) {
1794 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001795 }
1796 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001797}
1798
Steve Anton4171afb2017-11-20 10:20:22 -08001799std::vector<
1800 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1801PeerConnection::GetReceiversInternal() const {
1802 std::vector<
1803 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1804 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001805 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001806 auto receivers = transceiver->internal()->receivers();
1807 all_receivers.insert(all_receivers.end(), receivers.begin(),
1808 receivers.end());
1809 }
1810 return all_receivers;
1811}
1812
Steve Anton9158ef62017-11-27 13:01:52 -08001813std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1814PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001815 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001816 RTC_CHECK(IsUnifiedPlan())
1817 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001818 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001819 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001820 all_transceivers.push_back(transceiver);
1821 }
1822 return all_transceivers;
1823}
1824
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001826 MediaStreamTrackInterface* track,
1827 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001828 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001829 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001830 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 return false;
1833 }
1834
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001835 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001836 // The StatsCollector is used to tell if a track is valid because it may
1837 // remember tracks that the PeerConnection previously removed.
1838 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001839 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1840 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001841 return false;
1842 }
Steve Antonad182762018-09-05 20:22:40 +00001843 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1844 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 return true;
1846}
1847
hbos74e1a4f2016-09-15 23:33:01 -07001848void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001849 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001850 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001851 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001852 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001853 stats_collector_->GetStatsReport(callback);
1854}
1855
Henrik Boström1df1bf82018-03-20 13:24:20 +01001856void PeerConnection::GetStats(
1857 rtc::scoped_refptr<RtpSenderInterface> selector,
1858 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1859 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001860 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001861 RTC_DCHECK(callback);
1862 RTC_DCHECK(stats_collector_);
1863 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1864 if (selector) {
1865 for (const auto& proxy_transceiver : transceivers_) {
1866 for (const auto& proxy_sender :
1867 proxy_transceiver->internal()->senders()) {
1868 if (proxy_sender == selector) {
1869 internal_sender = proxy_sender->internal();
1870 break;
1871 }
1872 }
1873 if (internal_sender)
1874 break;
1875 }
1876 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001877 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001878 // belong to the PeerConnection (in Plan B, senders can be removed from the
1879 // PeerConnection). This means that "all the stats objects representing the
1880 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1881 // produces an empty stats report.
1882 stats_collector_->GetStatsReport(internal_sender, callback);
1883}
1884
1885void PeerConnection::GetStats(
1886 rtc::scoped_refptr<RtpReceiverInterface> selector,
1887 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1888 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001889 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001890 RTC_DCHECK(callback);
1891 RTC_DCHECK(stats_collector_);
1892 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1893 if (selector) {
1894 for (const auto& proxy_transceiver : transceivers_) {
1895 for (const auto& proxy_receiver :
1896 proxy_transceiver->internal()->receivers()) {
1897 if (proxy_receiver == selector) {
1898 internal_receiver = proxy_receiver->internal();
1899 break;
1900 }
1901 }
1902 if (internal_receiver)
1903 break;
1904 }
1905 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001906 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001907 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1908 // the PeerConnection). This means that "all the stats objects representing
1909 // the selector" is an empty set. Invoking GetStatsReport() with a null
1910 // selector produces an empty stats report.
1911 stats_collector_->GetStatsReport(internal_receiver, callback);
1912}
1913
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 return signaling_state_;
1917}
1918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919PeerConnectionInterface::IceConnectionState
1920PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 return ice_connection_state_;
1923}
1924
Alex Loiko9289eda2018-11-23 16:18:59 +00001925PeerConnectionInterface::IceConnectionState
1926PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001927 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001928 return standardized_ice_connection_state_;
1929}
1930
Jonas Olsson635474e2018-10-18 15:58:17 +02001931PeerConnectionInterface::PeerConnectionState
1932PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001933 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001934 return connection_state_;
1935}
1936
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937PeerConnectionInterface::IceGatheringState
1938PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001939 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940 return ice_gathering_state_;
1941}
1942
Yves Gerey665174f2018-06-19 15:03:05 +02001943rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 const std::string& label,
1945 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001946 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001947 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001948
deadbeefab9b2d12015-10-14 11:33:11 -07001949 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001950
kwibergd1fe2812016-04-27 06:47:29 -07001951 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001952 if (config) {
1953 internal_config.reset(new InternalDataChannelInit(*config));
1954 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001955 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001956 InternalCreateDataChannel(label, internal_config.get()));
1957 if (!channel.get()) {
1958 return nullptr;
1959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001961 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1962 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001963 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001964 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001965 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001966 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967 return DataChannelProxy::Create(signaling_thread(), channel.get());
1968}
1969
1970void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001971 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001972 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001973 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001974
nisse7ce109a2017-01-31 00:57:56 -08001975 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001976 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001977 return;
1978 }
deadbeefab9b2d12015-10-14 11:33:11 -07001979
Steve Anton8d3444d2017-10-20 15:30:51 -07001980 if (IsClosed()) {
1981 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001982 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001983 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001984 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001985 return;
1986 }
1987
zhihuang1c378ed2017-08-17 14:10:50 -07001988 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001989 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001990 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001991 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001992 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001993 return;
1994 }
1995
Steve Anton22da89f2018-01-25 13:58:07 -08001996 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1997 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1998 if (IsUnifiedPlan()) {
1999 RTCError error = HandleLegacyOfferOptions(options);
2000 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002001 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002002 return;
2003 }
2004 }
2005
zhihuang1c378ed2017-08-17 14:10:50 -07002006 cricket::MediaSessionOptions session_options;
2007 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002008 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009}
2010
Steve Anton22da89f2018-01-25 13:58:07 -08002011RTCError PeerConnection::HandleLegacyOfferOptions(
2012 const RTCOfferAnswerOptions& options) {
2013 RTC_DCHECK(IsUnifiedPlan());
2014
2015 if (options.offer_to_receive_audio == 0) {
2016 RemoveRecvDirectionFromReceivingTransceiversOfType(
2017 cricket::MEDIA_TYPE_AUDIO);
2018 } else if (options.offer_to_receive_audio == 1) {
2019 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2020 } else if (options.offer_to_receive_audio > 1) {
2021 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2022 "offer_to_receive_audio > 1 is not supported.");
2023 }
2024
2025 if (options.offer_to_receive_video == 0) {
2026 RemoveRecvDirectionFromReceivingTransceiversOfType(
2027 cricket::MEDIA_TYPE_VIDEO);
2028 } else if (options.offer_to_receive_video == 1) {
2029 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2030 } else if (options.offer_to_receive_video > 1) {
2031 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2032 "offer_to_receive_video > 1 is not supported.");
2033 }
2034
2035 return RTCError::OK();
2036}
2037
2038void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2039 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002040 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002041 RtpTransceiverDirection new_direction =
2042 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2043 if (new_direction != transceiver->direction()) {
2044 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2045 << " transceiver (MID="
2046 << transceiver->mid().value_or("<not set>") << ") from "
2047 << RtpTransceiverDirectionToString(
2048 transceiver->direction())
2049 << " to "
2050 << RtpTransceiverDirectionToString(new_direction)
2051 << " since CreateOffer specified offer_to_receive=0";
2052 transceiver->internal()->set_direction(new_direction);
2053 }
Steve Anton22da89f2018-01-25 13:58:07 -08002054 }
2055}
2056
2057void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2058 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002059 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002060 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002061 RTC_LOG(LS_INFO)
2062 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2063 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002064 RtpTransceiverInit init;
2065 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002066 AddTransceiver(media_type, nullptr, init,
2067 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002068 }
2069}
2070
2071std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2072PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2073 std::vector<
2074 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2075 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002076 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002077 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002078 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2079 receiving_transceivers.push_back(transceiver);
2080 }
2081 }
2082 return receiving_transceivers;
2083}
2084
htaa2a49d92016-03-04 02:51:39 -08002085void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2086 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002087 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002088 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002089 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002090 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002091 return;
2092 }
2093
Steve Antondffead82018-02-06 10:31:29 -08002094 if (!(signaling_state_ == kHaveRemoteOffer ||
2095 signaling_state_ == kHaveLocalPrAnswer)) {
2096 std::string error =
2097 "PeerConnection cannot create an answer in a state other than "
2098 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002099 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002100 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002101 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002102 return;
2103 }
2104
Steve Antondffead82018-02-06 10:31:29 -08002105 // The remote description should be set if we're in the right state.
2106 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002107
Steve Anton22da89f2018-01-25 13:58:07 -08002108 if (IsUnifiedPlan()) {
2109 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2110 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2111 "supported with Unified Plan semantics. Use the "
2112 "RtpTransceiver API instead.";
2113 }
2114 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2115 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2116 "supported with Unified Plan semantics. Use the "
2117 "RtpTransceiver API instead.";
2118 }
2119 }
2120
htaa2a49d92016-03-04 02:51:39 -08002121 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002122 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002123
Steve Antond25da372017-11-06 14:50:29 -08002124 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125}
2126
2127void PeerConnection::SetLocalDescription(
2128 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002129 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002130 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002131 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002132
Steve Anton80dd7b52018-02-16 17:08:42 -08002133 // The SetLocalDescription contract is that we take ownership of the session
2134 // description regardless of the outcome, so wrap it in a unique_ptr right
2135 // away. Ideally, SetLocalDescription's signature will be changed to take the
2136 // description as a unique_ptr argument to formalize this agreement.
2137 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2138
nisse7ce109a2017-01-31 00:57:56 -08002139 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002140 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 return;
2142 }
Steve Anton8a006912017-12-04 15:25:56 -08002143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002145 PostSetSessionDescriptionFailure(
2146 observer,
2147 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 return;
2149 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002150
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 // If a session error has occurred the PeerConnection is in a possibly
2152 // inconsistent state so fail right away.
2153 if (session_error() != SessionError::kNone) {
2154 std::string error_message = GetSessionErrorMsg();
2155 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002156 PostSetSessionDescriptionFailure(
2157 observer,
2158 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002159 return;
2160 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002161
Steve Anton80dd7b52018-02-16 17:08:42 -08002162 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2163 if (!error.ok()) {
2164 std::string error_message = GetSetDescriptionErrorMessage(
2165 cricket::CS_LOCAL, desc->GetType(), error);
2166 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002167 PostSetSessionDescriptionFailure(
2168 observer,
2169 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002170 return;
2171 }
2172
2173 // Grab the description type before moving ownership to ApplyLocalDescription,
2174 // which may destroy it before returning.
2175 const SdpType type = desc->GetType();
2176
2177 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002178 // |desc| may be destroyed at this point.
2179
2180 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002181 // If ApplyLocalDescription fails, the PeerConnection could be in an
2182 // inconsistent state, so act conservatively here and set the session error
2183 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2184 SetSessionError(SessionError::kContent, error.message());
2185 std::string error_message =
2186 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2187 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002188 PostSetSessionDescriptionFailure(
2189 observer,
2190 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002191 return;
2192 }
Steve Anton8a006912017-12-04 15:25:56 -08002193 RTC_DCHECK(local_description());
2194
2195 PostSetSessionDescriptionSuccess(observer);
2196
Steve Antonad182762018-09-05 20:22:40 +00002197 // MaybeStartGathering needs to be called after posting
2198 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2199 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002200 transport_controller_->MaybeStartGathering();
2201
Steve Antona3a92c22017-12-07 10:27:41 -08002202 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002203 // TODO(deadbeef): We already had to hop to the network thread for
2204 // MaybeStartGathering...
2205 network_thread()->Invoke<void>(
2206 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2207 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002208 // Make UMA notes about what was agreed to.
2209 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002210 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002211
2212 if (IsUnifiedPlan()) {
2213 bool was_negotiation_needed = is_negotiation_needed_;
2214 UpdateNegotiationNeeded();
2215 if (signaling_state() == kStable && was_negotiation_needed &&
2216 is_negotiation_needed_) {
2217 Observer()->OnRenegotiationNeeded();
2218 }
2219 }
2220
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002221 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002222}
2223
2224RTCError PeerConnection::ApplyLocalDescription(
2225 std::unique_ptr<SessionDescriptionInterface> desc) {
2226 RTC_DCHECK_RUN_ON(signaling_thread());
2227 RTC_DCHECK(desc);
2228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 // Update stats here so that we have the most recent stats for tracks and
2230 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002231 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002232
Steve Antondcc3c022017-12-22 16:02:54 -08002233 // Take a reference to the old local description since it's used below to
2234 // compare against the new local description. When setting the new local
2235 // description, grab ownership of the replaced session description in case it
2236 // is the same as |old_local_description|, to keep it alive for the duration
2237 // of the method.
2238 const SessionDescriptionInterface* old_local_description =
2239 local_description();
2240 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002241 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002242 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002243 replaced_local_description = pending_local_description_
2244 ? std::move(pending_local_description_)
2245 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002246 current_local_description_ = std::move(desc);
2247 pending_local_description_ = nullptr;
2248 current_remote_description_ = std::move(pending_remote_description_);
2249 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002250 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002251 pending_local_description_ = std::move(desc);
2252 }
2253 // The session description to apply now must be accessed by
2254 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002255 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002256
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002257 // Report statistics about any use of simulcast.
2258 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2259 *local_description()->description());
2260
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002261 if (!is_caller_) {
2262 if (remote_description()) {
2263 // Remote description was applied first, so this PC is the callee.
2264 is_caller_ = false;
2265 } else {
2266 // Local description is applied first, so this PC is the caller.
2267 is_caller_ = true;
2268 }
2269 }
2270
Zhi Huange830e682018-03-30 10:48:35 -07002271 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2272 if (!error.ok()) {
2273 return error;
2274 }
2275
Steve Antondcc3c022017-12-22 16:02:54 -08002276 if (IsUnifiedPlan()) {
2277 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002278 cricket::CS_LOCAL, *local_description(), old_local_description,
2279 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002280 if (!error.ok()) {
2281 return error;
2282 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002283 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2284 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002285 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002286 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2287 // Note that code paths that don't set MID won't be able to use
2288 // information about DTLS transports.
2289 if (transceiver->mid()) {
2290 auto dtls_transport =
2291 LookupDtlsTransportByMidInternal(*transceiver->mid());
2292 transceiver->internal()->sender_internal()->set_transport(
2293 dtls_transport);
2294 transceiver->internal()->receiver_internal()->set_transport(
2295 dtls_transport);
2296 }
2297
Steve Antondcc3c022017-12-22 16:02:54 -08002298 const ContentInfo* content =
2299 FindMediaSectionForTransceiver(transceiver, local_description());
2300 if (!content) {
2301 continue;
2302 }
2303 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002304 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2305 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002306 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002307 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2308 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2309 // "recvonly", process the removal of a remote track for the media
2310 // description, given transceiver, removeList, and muteTracks.
2311 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2312 (transceiver->internal()->fired_direction() &&
2313 RtpTransceiverDirectionHasRecv(
2314 *transceiver->internal()->fired_direction()))) {
2315 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2316 &removed_streams);
2317 }
2318 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2319 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002320 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002321 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002322 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002323 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002324 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002325 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002326 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002327 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002328 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002329 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002330 }
2331 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002332 // Media channels will be created only when offer is set. These may use new
2333 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002334 if (type == SdpType::kOffer) {
2335 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2336 // description is applied. Restore back to old description.
2337 RTCError error = CreateChannels(*local_description()->description());
2338 if (!error.ok()) {
2339 return error;
2340 }
2341 }
Steve Antondcc3c022017-12-22 16:02:54 -08002342 // Remove unused channels if MediaContentDescription is rejected.
2343 RemoveUnusedChannels(local_description()->description());
2344 }
Steve Anton8a006912017-12-04 15:25:56 -08002345
Zhi Huange830e682018-03-30 10:48:35 -07002346 error = UpdateSessionState(type, cricket::CS_LOCAL,
2347 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002348 if (!error.ok()) {
2349 return error;
2350 }
Steve Antondcc3c022017-12-22 16:02:54 -08002351
Steve Anton8a006912017-12-04 15:25:56 -08002352 if (remote_description()) {
2353 // Now that we have a local description, we can push down remote candidates.
2354 UseCandidatesInSessionDescription(remote_description());
2355 }
2356
2357 pending_ice_restarts_.clear();
2358 if (session_error() != SessionError::kNone) {
2359 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2360 }
2361
deadbeefab9b2d12015-10-14 11:33:11 -07002362 // If setting the description decided our SSL role, allocate any necessary
2363 // SCTP sids.
2364 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002365 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002366 AllocateSctpSids(role);
2367 }
2368
Steve Antond3679212018-01-17 17:41:02 -08002369 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002370 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002371 const ContentInfo* content =
2372 FindMediaSectionForTransceiver(transceiver, local_description());
2373 if (!content) {
2374 continue;
2375 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002376 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2377 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002378 // 0 is a special value meaning "this sender has no associated send
2379 // stream". Need to call this so the sender won't attempt to configure
2380 // a no longer existing stream and run into DCHECKs in the lower
2381 // layers.
2382 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002383 } else {
2384 // Get the StreamParams from the channel which could generate SSRCs.
2385 const std::vector<StreamParams>& streams = channel->local_streams();
2386 transceiver->internal()->sender_internal()->set_stream_ids(
2387 streams[0].stream_ids());
2388 transceiver->internal()->sender_internal()->SetSsrc(
2389 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002390 }
2391 }
2392 } else {
2393 // Plan B semantics.
2394
Steve Antondcc3c022017-12-22 16:02:54 -08002395 // Update state and SSRC of local MediaStreams and DataChannels based on the
2396 // local session description.
2397 const cricket::ContentInfo* audio_content =
2398 GetFirstAudioContent(local_description()->description());
2399 if (audio_content) {
2400 if (audio_content->rejected) {
2401 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2402 } else {
2403 const cricket::AudioContentDescription* audio_desc =
2404 audio_content->media_description()->as_audio();
2405 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2406 }
deadbeeffaac4972015-11-12 15:33:07 -08002407 }
deadbeefab9b2d12015-10-14 11:33:11 -07002408
Steve Antondcc3c022017-12-22 16:02:54 -08002409 const cricket::ContentInfo* video_content =
2410 GetFirstVideoContent(local_description()->description());
2411 if (video_content) {
2412 if (video_content->rejected) {
2413 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2414 } else {
2415 const cricket::VideoContentDescription* video_desc =
2416 video_content->media_description()->as_video();
2417 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2418 }
deadbeeffaac4972015-11-12 15:33:07 -08002419 }
deadbeefab9b2d12015-10-14 11:33:11 -07002420 }
2421
2422 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002423 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002424 if (data_content) {
2425 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002426 data_content->media_description()->as_data();
Danil Chapovalovc6d1d242019-04-23 09:48:11 +00002427 if (absl::StartsWith(data_desc->protocol(),
2428 cricket::kMediaProtocolRtpPrefix)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002429 UpdateLocalRtpDataChannels(data_desc->streams());
2430 }
2431 }
2432
Steve Anton8a006912017-12-04 15:25:56 -08002433 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434}
2435
Steve Anton06817cd2018-12-18 15:55:30 -08002436// The SDP parser used to populate these values by default for the 'content
2437// name' if an a=mid line was absent.
2438static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2439 switch (media_type) {
2440 case cricket::MEDIA_TYPE_AUDIO:
2441 return cricket::CN_AUDIO;
2442 case cricket::MEDIA_TYPE_VIDEO:
2443 return cricket::CN_VIDEO;
2444 case cricket::MEDIA_TYPE_DATA:
2445 return cricket::CN_DATA;
2446 }
2447 RTC_NOTREACHED();
2448 return "";
2449}
2450
2451void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002452 cricket::SessionDescription* new_remote_description) {
2453 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002454 const cricket::ContentInfos& local_contents =
2455 (local_description() ? local_description()->description()->contents()
2456 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002457 const cricket::ContentInfos& remote_contents =
2458 (remote_description() ? remote_description()->description()->contents()
2459 : cricket::ContentInfos());
2460 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2461 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002462 if (!content.name.empty()) {
2463 continue;
2464 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002465 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002466 absl::string_view source_explanation;
2467 if (IsUnifiedPlan()) {
2468 if (i < local_contents.size()) {
2469 new_mid = local_contents[i].name;
2470 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002471 } else if (i < remote_contents.size()) {
2472 new_mid = remote_contents[i].name;
2473 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002474 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002475 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002476 source_explanation = "generated just now";
2477 }
2478 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002479 new_mid = std::string(
2480 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002481 source_explanation = "to match pre-existing behavior";
2482 }
Steve Antond7180cc2019-02-07 10:44:53 -08002483 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002484 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002485 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002486 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2487 << " is missing an a=mid line. Filling in the value '"
2488 << new_mid << "' " << source_explanation << ".";
2489 }
2490}
2491
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002493 SetSessionDescriptionObserver* observer,
2494 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002495 SetRemoteDescription(
2496 std::unique_ptr<SessionDescriptionInterface>(desc),
2497 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2498 new SetRemoteDescriptionObserverAdapter(this, observer)));
2499}
2500
2501void PeerConnection::SetRemoteDescription(
2502 std::unique_ptr<SessionDescriptionInterface> desc,
2503 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002504 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002505 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002506
nisse7ce109a2017-01-31 00:57:56 -08002507 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002508 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002509 return;
2510 }
Steve Anton8a006912017-12-04 15:25:56 -08002511
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002513 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002514 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 return;
2516 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002517
Steve Anton80dd7b52018-02-16 17:08:42 -08002518 // If a session error has occurred the PeerConnection is in a possibly
2519 // inconsistent state so fail right away.
2520 if (session_error() != SessionError::kNone) {
2521 std::string error_message = GetSessionErrorMsg();
2522 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2523 observer->OnSetRemoteDescriptionComplete(
2524 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2525 return;
2526 }
Steve Anton71439a62018-02-15 11:53:06 -08002527
Steve Antonba42e992018-04-09 14:10:01 -07002528 if (desc->GetType() == SdpType::kOffer) {
2529 // Report to UMA the format of the received offer.
2530 ReportSdpFormatReceived(*desc);
2531 }
2532
Steve Anton06817cd2018-12-18 15:55:30 -08002533 // Handle remote descriptions missing a=mid lines for interop with legacy end
2534 // points.
2535 FillInMissingRemoteMids(desc->description());
2536
Steve Anton80dd7b52018-02-16 17:08:42 -08002537 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002538 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002539 std::string error_message = GetSetDescriptionErrorMessage(
2540 cricket::CS_REMOTE, desc->GetType(), error);
2541 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002542 observer->OnSetRemoteDescriptionComplete(
2543 RTCError(error.type(), std::move(error_message)));
2544 return;
2545 }
Steve Anton71439a62018-02-15 11:53:06 -08002546
Steve Anton80dd7b52018-02-16 17:08:42 -08002547 // Grab the description type before moving ownership to
2548 // ApplyRemoteDescription, which may destroy it before returning.
2549 const SdpType type = desc->GetType();
2550
2551 error = ApplyRemoteDescription(std::move(desc));
2552 // |desc| may be destroyed at this point.
2553
2554 if (!error.ok()) {
2555 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2556 // inconsistent state, so act conservatively here and set the session error
2557 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2558 SetSessionError(SessionError::kContent, error.message());
2559 std::string error_message =
2560 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2561 RTC_LOG(LS_ERROR) << error_message;
2562 observer->OnSetRemoteDescriptionComplete(
2563 RTCError(error.type(), std::move(error_message)));
2564 return;
2565 }
2566 RTC_DCHECK(remote_description());
2567
2568 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002569 // TODO(deadbeef): We already had to hop to the network thread for
2570 // MaybeStartGathering...
2571 network_thread()->Invoke<void>(
2572 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2573 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002574 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002575 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002576 }
2577
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002578 if (IsUnifiedPlan()) {
2579 bool was_negotiation_needed = is_negotiation_needed_;
2580 UpdateNegotiationNeeded();
2581 if (signaling_state() == kStable && was_negotiation_needed &&
2582 is_negotiation_needed_) {
2583 Observer()->OnRenegotiationNeeded();
2584 }
2585 }
2586
Steve Anton8a006912017-12-04 15:25:56 -08002587 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002588 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002589}
2590
2591RTCError PeerConnection::ApplyRemoteDescription(
2592 std::unique_ptr<SessionDescriptionInterface> desc) {
2593 RTC_DCHECK_RUN_ON(signaling_thread());
2594 RTC_DCHECK(desc);
2595
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596 // Update stats here so that we have the most recent stats for tracks and
2597 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002598 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002599
Steve Antondcc3c022017-12-22 16:02:54 -08002600 // Take a reference to the old remote description since it's used below to
2601 // compare against the new remote description. When setting the new remote
2602 // description, grab ownership of the replaced session description in case it
2603 // is the same as |old_remote_description|, to keep it alive for the duration
2604 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002605 const SessionDescriptionInterface* old_remote_description =
2606 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002607 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002608 SdpType type = desc->GetType();
2609 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002610 replaced_remote_description = pending_remote_description_
2611 ? std::move(pending_remote_description_)
2612 : std::move(current_remote_description_);
2613 current_remote_description_ = std::move(desc);
2614 pending_remote_description_ = nullptr;
2615 current_local_description_ = std::move(pending_local_description_);
2616 } else {
2617 replaced_remote_description = std::move(pending_remote_description_);
2618 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619 }
Steve Anton8a006912017-12-04 15:25:56 -08002620 // The session description to apply now must be accessed by
2621 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002622 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002623
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002624 // Report statistics about any use of simulcast.
2625 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2626 *remote_description()->description());
2627
Zhi Huange830e682018-03-30 10:48:35 -07002628 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2629 if (!error.ok()) {
2630 return error;
2631 }
Steve Anton8a006912017-12-04 15:25:56 -08002632 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002633 if (IsUnifiedPlan()) {
2634 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002635 cricket::CS_REMOTE, *remote_description(), local_description(),
2636 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002637 if (!error.ok()) {
2638 return error;
2639 }
Steve Antondcc3c022017-12-22 16:02:54 -08002640 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002641 // Media channels will be created only when offer is set. These may use new
2642 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002643 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002644 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002645 // description is applied. Restore back to old description.
2646 RTCError error = CreateChannels(*remote_description()->description());
2647 if (!error.ok()) {
2648 return error;
2649 }
2650 }
Steve Antondcc3c022017-12-22 16:02:54 -08002651 // Remove unused channels if MediaContentDescription is rejected.
2652 RemoveUnusedChannels(remote_description()->description());
2653 }
Steve Anton8a006912017-12-04 15:25:56 -08002654
Zhi Huange830e682018-03-30 10:48:35 -07002655 // NOTE: Candidates allocation will be initiated only when
2656 // SetLocalDescription is called.
2657 error = UpdateSessionState(type, cricket::CS_REMOTE,
2658 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002659 if (!error.ok()) {
2660 return error;
2661 }
2662
2663 if (local_description() &&
2664 !UseCandidatesInSessionDescription(remote_description())) {
2665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2666 }
2667
2668 if (old_remote_description) {
2669 for (const cricket::ContentInfo& content :
2670 old_remote_description->description()->contents()) {
2671 // Check if this new SessionDescription contains new ICE ufrag and
2672 // password that indicates the remote peer requests an ICE restart.
2673 // TODO(deadbeef): When we start storing both the current and pending
2674 // remote description, this should reset pending_ice_restarts and compare
2675 // against the current description.
2676 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2677 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002678 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002679 pending_ice_restarts_.insert(content.name);
2680 }
2681 } else {
2682 // We retain all received candidates only if ICE is not restarted.
2683 // When ICE is restarted, all previous candidates belong to an old
2684 // generation and should not be kept.
2685 // TODO(deadbeef): This goes against the W3C spec which says the remote
2686 // description should only contain candidates from the last set remote
2687 // description plus any candidates added since then. We should remove
2688 // this once we're sure it won't break anything.
2689 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2690 old_remote_description, content.name, mutable_remote_description());
2691 }
2692 }
2693 }
2694
2695 if (session_error() != SessionError::kNone) {
2696 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2697 }
2698
2699 // Set the the ICE connection state to connecting since the connection may
2700 // become writable with peer reflexive candidates before any remote candidate
2701 // is signaled.
2702 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2703 // is to have a new signal the indicates a change in checking state from the
2704 // transport and expose a new checking() member from transport that can be
2705 // read to determine the current checking state. The existing SignalConnecting
2706 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002707 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002708 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002709 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2710 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2711 }
2712
deadbeefab9b2d12015-10-14 11:33:11 -07002713 // If setting the description decided our SSL role, allocate any necessary
2714 // SCTP sids.
2715 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002716 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002717 AllocateSctpSids(role);
2718 }
2719
Steve Antondcc3c022017-12-22 16:02:54 -08002720 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002721 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002722 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002723 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002724 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002725 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002726 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002727 const ContentInfo* content =
2728 FindMediaSectionForTransceiver(transceiver, remote_description());
2729 if (!content) {
2730 continue;
2731 }
2732 const MediaContentDescription* media_desc = content->media_description();
2733 RtpTransceiverDirection local_direction =
2734 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002735 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2736 // RTCSessionDescription: Set the associated remote streams given
2737 // transceiver.[[Receiver]], msids, addList, and removeList".
2738 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2739 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2740 std::vector<std::string> stream_ids;
2741 if (!media_desc->streams().empty()) {
2742 // The remote description has signaled the stream IDs.
2743 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002744 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002745 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2746 << " (" << GetStreamIdsString(stream_ids) << ").";
2747 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2748 stream_ids, &added_streams,
2749 &removed_streams);
2750 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2751 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2752 // and transceiver's current direction is neither sendrecv nor recvonly,
2753 // process the addition of a remote track for the media description.
2754 if (!transceiver->fired_direction() ||
2755 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2756 RTC_LOG(LS_INFO)
2757 << "Processing the addition of a remote track for MID="
2758 << content->name << ".";
2759 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002760 }
Steve Antondcc3c022017-12-22 16:02:54 -08002761 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002763 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2764 // removal of a remote track for the media description, given transceiver,
2765 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002766 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002767 (transceiver->fired_direction() &&
2768 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2769 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2770 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002771 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002772 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002773 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002774 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002775 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002776 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002777 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002778 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002779 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002780 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2781 if (transceiver->mid()) {
2782 auto dtls_transport =
2783 LookupDtlsTransportByMidInternal(*transceiver->mid());
2784 transceiver->internal()->sender_internal()->set_transport(
2785 dtls_transport);
2786 transceiver->internal()->receiver_internal()->set_transport(
2787 dtls_transport);
2788 }
Steve Antondcc3c022017-12-22 16:02:54 -08002789 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002790 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002791 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002792 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002793 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2794 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002795 transceiver->Stop();
2796 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002797 if (!content->rejected &&
2798 RtpTransceiverDirectionHasRecv(local_direction)) {
2799 // Set ssrc to 0 in the case of an unsignalled ssrc.
2800 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002801 if (!media_desc->streams().empty() &&
2802 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002803 ssrc = media_desc->streams()[0].first_ssrc();
2804 }
2805 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002806 }
Steve Antondcc3c022017-12-22 16:02:54 -08002807 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002808 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002809 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002810 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002811 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002812 observer->OnTrack(transceiver);
2813 observer->OnAddTrack(transceiver->receiver(),
2814 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002815 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002816 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002817 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002818 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002819 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002820 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002821 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002822 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002823 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002824 }
Steve Antondcc3c022017-12-22 16:02:54 -08002825 }
2826
Henrik Boströmfdb92012017-11-09 19:55:44 +01002827 const cricket::ContentInfo* audio_content =
2828 GetFirstAudioContent(remote_description()->description());
2829 const cricket::ContentInfo* video_content =
2830 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002831 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002832 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002833 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002834 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002835 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002836 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002837
2838 // Check if the descriptions include streams, just in case the peer supports
2839 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002840 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002841 (audio_desc && !audio_desc->streams().empty()) ||
2842 (video_desc && !video_desc->streams().empty())) {
2843 remote_peer_supports_msid_ = true;
2844 }
deadbeefab9b2d12015-10-14 11:33:11 -07002845
2846 // We wait to signal new streams until we finish processing the description,
2847 // since only at that point will new streams have all their tracks.
2848 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2849
Steve Antondcc3c022017-12-22 16:02:54 -08002850 if (!IsUnifiedPlan()) {
2851 // TODO(steveanton): When removing RTP senders/receivers in response to a
2852 // rejected media section, there is some cleanup logic that expects the
2853 // voice/ video channel to still be set. But in this method the voice/video
2854 // channel would have been destroyed by the SetRemoteDescription caller
2855 // above so the cleanup that relies on them fails to run. The RemoveSenders
2856 // calls should be moved to right before the DestroyChannel calls to fix
2857 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002858
Steve Antondcc3c022017-12-22 16:02:54 -08002859 // Find all audio rtp streams and create corresponding remote AudioTracks
2860 // and MediaStreams.
2861 if (audio_content) {
2862 if (audio_content->rejected) {
2863 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2864 } else {
2865 bool default_audio_track_needed =
2866 !remote_peer_supports_msid_ &&
2867 RtpTransceiverDirectionHasSend(audio_desc->direction());
2868 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2869 default_audio_track_needed, audio_desc->type(),
2870 new_streams);
2871 }
deadbeeffaac4972015-11-12 15:33:07 -08002872 }
deadbeefab9b2d12015-10-14 11:33:11 -07002873
Steve Antondcc3c022017-12-22 16:02:54 -08002874 // Find all video rtp streams and create corresponding remote VideoTracks
2875 // and MediaStreams.
2876 if (video_content) {
2877 if (video_content->rejected) {
2878 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2879 } else {
2880 bool default_video_track_needed =
2881 !remote_peer_supports_msid_ &&
2882 RtpTransceiverDirectionHasSend(video_desc->direction());
2883 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2884 default_video_track_needed, video_desc->type(),
2885 new_streams);
2886 }
deadbeeffaac4972015-11-12 15:33:07 -08002887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888
Steve Antondcc3c022017-12-22 16:02:54 -08002889 // Update the DataChannels with the information from the remote peer.
2890 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002891 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002892 cricket::kMediaProtocolRtpPrefix)) {
2893 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2894 }
deadbeefab9b2d12015-10-14 11:33:11 -07002895 }
deadbeefab9b2d12015-10-14 11:33:11 -07002896
Steve Antondcc3c022017-12-22 16:02:54 -08002897 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002898 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002899 for (size_t i = 0; i < new_streams->count(); ++i) {
2900 MediaStreamInterface* new_stream = new_streams->at(i);
2901 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002902 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002903 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2904 }
deadbeefab9b2d12015-10-14 11:33:11 -07002905
Steve Antondcc3c022017-12-22 16:02:54 -08002906 UpdateEndedRemoteMediaStreams();
2907 }
deadbeefab9b2d12015-10-14 11:33:11 -07002908
Steve Anton8a006912017-12-04 15:25:56 -08002909 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002910}
2911
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002912void PeerConnection::SetAssociatedRemoteStreams(
2913 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2914 const std::vector<std::string>& stream_ids,
2915 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2916 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2917 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2918 for (const std::string& stream_id : stream_ids) {
2919 rtc::scoped_refptr<MediaStreamInterface> stream =
2920 remote_streams_->find(stream_id);
2921 if (!stream) {
2922 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2923 MediaStream::Create(stream_id));
2924 remote_streams_->AddStream(stream);
2925 added_streams->push_back(stream);
2926 }
2927 media_streams.push_back(stream);
2928 }
2929 // Special case: "a=msid" missing, use random stream ID.
2930 if (media_streams.empty() &&
2931 !(remote_description()->description()->msid_signaling() &
2932 cricket::kMsidSignalingMediaSection)) {
2933 if (!missing_msid_default_stream_) {
2934 missing_msid_default_stream_ = MediaStreamProxy::Create(
2935 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2936 added_streams->push_back(missing_msid_default_stream_);
2937 }
2938 media_streams.push_back(missing_msid_default_stream_);
2939 }
2940 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2941 receiver->streams();
2942 // SetStreams() will add/remove the receiver's track to/from the streams. This
2943 // differs from the spec - the spec uses an "addList" and "removeList" to
2944 // update the stream-track relationships in a later step. We do this earlier,
2945 // changing the order of things, but the end-result is the same.
2946 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2947 // instead. https://crbug.com/webrtc/9480
2948 receiver->SetStreams(media_streams);
2949 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2950}
2951
Steve Anton0f5400a2018-07-17 14:25:36 -07002952void PeerConnection::ProcessRemovalOfRemoteTrack(
2953 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2954 transceiver,
2955 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2956 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2957 RTC_DCHECK(transceiver->mid());
2958 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2959 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002960 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002961 transceiver->internal()->receiver_internal()->streams();
2962 // This will remove the remote track from the streams.
2963 transceiver->internal()->receiver_internal()->set_stream_ids({});
2964 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002965 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2966}
2967
2968void PeerConnection::RemoveRemoteStreamsIfEmpty(
2969 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2970 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2971 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2972 // streams, see if the stream was removed by checking if this was the last
2973 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002974 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002975 if (remote_stream->GetAudioTracks().empty() &&
2976 remote_stream->GetVideoTracks().empty()) {
2977 remote_streams_->RemoveStream(remote_stream);
2978 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002979 }
2980 }
2981}
2982
Steve Antondcc3c022017-12-22 16:02:54 -08002983RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2984 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002985 const SessionDescriptionInterface& new_session,
2986 const SessionDescriptionInterface* old_local_description,
2987 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002988 RTC_DCHECK(IsUnifiedPlan());
2989
Steve Anton7464fca2018-01-19 11:10:37 -08002990 const cricket::ContentGroup* bundle_group = nullptr;
2991 if (new_session.GetType() == SdpType::kOffer) {
2992 auto bundle_group_or_error =
2993 GetEarlyBundleGroup(*new_session.description());
2994 if (!bundle_group_or_error.ok()) {
2995 return bundle_group_or_error.MoveError();
2996 }
2997 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002998 }
Steve Antondcc3c022017-12-22 16:02:54 -08002999
Steve Antondcc3c022017-12-22 16:02:54 -08003000 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003001 for (size_t i = 0; i < new_contents.size(); ++i) {
3002 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003003 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003004 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003005 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3006 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003007 const cricket::ContentInfo* old_local_content = nullptr;
3008 if (old_local_description &&
3009 i < old_local_description->description()->contents().size()) {
3010 old_local_content =
3011 &old_local_description->description()->contents()[i];
3012 }
3013 const cricket::ContentInfo* old_remote_content = nullptr;
3014 if (old_remote_description &&
3015 i < old_remote_description->description()->contents().size()) {
3016 old_remote_content =
3017 &old_remote_description->description()->contents()[i];
3018 }
Steve Antondcc3c022017-12-22 16:02:54 -08003019 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003020 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3021 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003022 if (!transceiver_or_error.ok()) {
3023 return transceiver_or_error.MoveError();
3024 }
3025 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003026 RTCError error =
3027 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3028 if (!error.ok()) {
3029 return error;
3030 }
3031 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003032 if (GetDataMid() && new_content.name != *GetDataMid()) {
3033 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003034 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3035 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003036 continue;
3037 }
3038 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3039 if (!error.ok()) {
3040 return error;
3041 }
Steve Antondcc3c022017-12-22 16:02:54 -08003042 } else {
3043 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3044 "Unknown section type.");
3045 }
3046 }
3047
3048 return RTCError::OK();
3049}
3050
3051RTCError PeerConnection::UpdateTransceiverChannel(
3052 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3053 transceiver,
3054 const cricket::ContentInfo& content,
3055 const cricket::ContentGroup* bundle_group) {
3056 RTC_DCHECK(IsUnifiedPlan());
3057 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003058 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003059 if (content.rejected) {
3060 if (channel) {
3061 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003062 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003063 }
3064 } else {
3065 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003066 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003067 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003068 } else {
Steve Anton69470252018-02-09 11:43:08 -08003069 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003070 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003071 }
3072 if (!channel) {
3073 LOG_AND_RETURN_ERROR(
3074 RTCErrorType::INTERNAL_ERROR,
3075 "Failed to create channel for mid=" + content.name);
3076 }
3077 transceiver->internal()->SetChannel(channel);
3078 }
3079 }
3080 return RTCError::OK();
3081}
3082
Steve Antonfa2260d2017-12-28 16:38:23 -08003083RTCError PeerConnection::UpdateDataChannel(
3084 cricket::ContentSource source,
3085 const cricket::ContentInfo& content,
3086 const cricket::ContentGroup* bundle_group) {
3087 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003088 // If data channels are disabled, ignore this media section. CreateAnswer
3089 // will take care of rejecting it.
3090 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003091 }
3092 if (content.rejected) {
3093 DestroyDataChannel();
3094 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003095 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003096 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003097 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3098 "Failed to create data channel.");
3099 }
3100 }
3101 if (source == cricket::CS_REMOTE) {
3102 const MediaContentDescription* data_desc = content.media_description();
3103 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3104 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3105 }
3106 }
3107 }
3108 return RTCError::OK();
3109}
3110
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003111// This method will extract any send encodings that were sent by the remote
3112// connection. This is currently only relevant for Simulcast scenario (where
3113// the number of layers may be communicated by the server).
3114static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3115 const MediaContentDescription& desc) {
3116 if (!desc.HasSimulcast()) {
3117 return {};
3118 }
3119 std::vector<RtpEncodingParameters> result;
3120 const SimulcastDescription& simulcast = desc.simulcast_description();
3121
3122 // This is a remote description, the parameters we are after should appear
3123 // as receive streams.
3124 for (const auto& alternatives : simulcast.receive_layers()) {
3125 RTC_DCHECK(!alternatives.empty());
3126 // There is currently no way to specify or choose from alternatives.
3127 // We will always use the first alternative, which is the most preferred.
3128 const SimulcastLayer& layer = alternatives[0];
3129 RtpEncodingParameters parameters;
3130 parameters.rid = layer.rid;
3131 parameters.active = !layer.is_paused;
3132 result.push_back(parameters);
3133 }
3134
3135 return result;
3136}
3137
3138static RTCError UpdateSimulcastLayerStatusInSender(
3139 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003140 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003141 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003142 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003143 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003144
3145 // The simulcast envelope cannot be changed, only the status of the streams.
3146 // So we will iterate over the send encodings rather than the layers.
3147 for (RtpEncodingParameters& encoding : parameters.encodings) {
3148 auto iter = std::find_if(layers.begin(), layers.end(),
3149 [&encoding](const SimulcastLayer& layer) {
3150 return layer.rid == encoding.rid;
3151 });
3152 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003153 if (iter == layers.end()) {
3154 disabled_layers.push_back(encoding.rid);
3155 continue;
3156 }
3157
3158 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003159 }
3160
Amit Hilbuch619b2942019-02-26 15:55:19 -08003161 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003162 if (result.ok()) {
3163 result = sender->DisableEncodingLayers(disabled_layers);
3164 }
3165
3166 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003167}
3168
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003169static bool SimulcastIsRejected(
3170 const ContentInfo* local_content,
3171 const MediaContentDescription& answer_media_desc) {
3172 bool simulcast_offered = local_content &&
3173 local_content->media_description() &&
3174 local_content->media_description()->HasSimulcast();
3175 bool simulcast_answered = answer_media_desc.HasSimulcast();
3176 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3177 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3178 return simulcast_offered && (!simulcast_answered || !rids_supported);
3179}
3180
Amit Hilbuch2297d332019-02-19 12:49:22 -08003181static RTCError DisableSimulcastInSender(
3182 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003183 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003184 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003185 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003186 return RTCError::OK();
3187 }
3188
Amit Hilbuch2297d332019-02-19 12:49:22 -08003189 std::vector<std::string> disabled_layers;
3190 std::transform(
3191 parameters.encodings.begin() + 1, parameters.encodings.end(),
3192 std::back_inserter(disabled_layers),
3193 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3194 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003195}
3196
Steve Antondcc3c022017-12-22 16:02:54 -08003197RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3198PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003199 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003200 size_t mline_index,
3201 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003202 const ContentInfo* old_local_content,
3203 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003204 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003205 // If this is an offer then the m= section might be recycled. If the m=
3206 // section is being recycled (defined as: rejected in the current local or
3207 // remote description and not rejected in new description), dissociate the
3208 // currently associated RtpTransceiver by setting its mid property to null,
3209 // and discard the mapping between the transceiver and its m= section index.
3210 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3211 old_remote_content)) {
3212 // We want to dissociate the transceiver that has the rejected mid.
3213 const std::string& old_mid =
3214 (old_local_content && old_local_content->rejected)
3215 ? old_local_content->name
3216 : old_remote_content->name;
3217 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003218 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003219 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3220 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003221 old_transceiver->internal()->set_mid(absl::nullopt);
3222 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003223 }
3224 }
3225 const MediaContentDescription* media_desc = content.media_description();
3226 auto transceiver = GetAssociatedTransceiver(content.name);
3227 if (source == cricket::CS_LOCAL) {
3228 // Find the RtpTransceiver that corresponds to this m= section, using the
3229 // mapping between transceivers and m= section indices established when
3230 // creating the offer.
3231 if (!transceiver) {
3232 transceiver = GetTransceiverByMLineIndex(mline_index);
3233 }
3234 if (!transceiver) {
3235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3236 "Unknown transceiver");
3237 }
3238 } else {
3239 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3240 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3241 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003242 // When simulcast is requested, a transceiver cannot be associated because
3243 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003244 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003245 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3246 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003247 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3248 }
3249 // If no RtpTransceiver was found in the previous step, create one with a
3250 // recvonly direction.
3251 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003252 RTC_LOG(LS_INFO) << "Adding "
3253 << cricket::MediaTypeToString(media_desc->type())
3254 << " transceiver for MID=" << content.name
3255 << " at i=" << mline_index
3256 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003257 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003258 std::vector<RtpEncodingParameters> send_encodings =
3259 GetSendEncodingsFromRemoteDescription(*media_desc);
3260 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3261 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003262 std::string receiver_id;
3263 if (!media_desc->streams().empty()) {
3264 receiver_id = media_desc->streams()[0].id;
3265 } else {
3266 receiver_id = rtc::CreateRandomUuid();
3267 }
3268 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003269 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003270 transceiver->internal()->set_direction(
3271 RtpTransceiverDirection::kRecvOnly);
3272 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003273
3274 // Check if the offer indicated simulcast but the answer rejected it.
3275 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003276 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003277 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003278 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003279 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003280 if (!error.ok()) {
3281 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3282 return std::move(error);
3283 }
3284 }
Steve Antondcc3c022017-12-22 16:02:54 -08003285 }
3286 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003287 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003288 LOG_AND_RETURN_ERROR(
3289 RTCErrorType::INVALID_PARAMETER,
3290 "Transceiver type does not match media description type.");
3291 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003292 if (media_desc->HasSimulcast()) {
3293 std::vector<SimulcastLayer> layers =
3294 source == cricket::CS_LOCAL
3295 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3296 : media_desc->simulcast_description()
3297 .receive_layers()
3298 .GetAllLayers();
3299 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003300 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003301 if (!error.ok()) {
3302 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3303 return std::move(error);
3304 }
3305 }
Steve Antondcc3c022017-12-22 16:02:54 -08003306 // Associate the found or created RtpTransceiver with the m= section by
3307 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3308 // section, and establish a mapping between the transceiver and the index of
3309 // the m= section.
3310 transceiver->internal()->set_mid(content.name);
3311 transceiver->internal()->set_mline_index(mline_index);
3312 return std::move(transceiver);
3313}
3314
3315rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3316PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3317 RTC_DCHECK(IsUnifiedPlan());
3318 for (auto transceiver : transceivers_) {
3319 if (transceiver->mid() == mid) {
3320 return transceiver;
3321 }
3322 }
3323 return nullptr;
3324}
3325
3326rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3327PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3328 RTC_DCHECK(IsUnifiedPlan());
3329 for (auto transceiver : transceivers_) {
3330 if (transceiver->internal()->mline_index() == mline_index) {
3331 return transceiver;
3332 }
3333 }
3334 return nullptr;
3335}
3336
3337rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3338PeerConnection::FindAvailableTransceiverToReceive(
3339 cricket::MediaType media_type) const {
3340 RTC_DCHECK(IsUnifiedPlan());
3341 // From JSEP section 5.10 (Applying a Remote Description):
3342 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3343 // the same type that were added to the PeerConnection by addTrack and are not
3344 // associated with any m= section and are not stopped, find the first such
3345 // RtpTransceiver.
3346 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003347 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003348 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3349 !transceiver->stopped()) {
3350 return transceiver;
3351 }
3352 }
3353 return nullptr;
3354}
3355
Steve Antoned10bd92017-12-05 10:52:59 -08003356const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3357 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3358 transceiver,
3359 const SessionDescriptionInterface* sdesc) const {
3360 RTC_DCHECK(transceiver);
3361 RTC_DCHECK(sdesc);
3362 if (IsUnifiedPlan()) {
3363 if (!transceiver->internal()->mid()) {
3364 // This transceiver is not associated with a media section yet.
3365 return nullptr;
3366 }
3367 return sdesc->description()->GetContentByName(
3368 *transceiver->internal()->mid());
3369 } else {
3370 // Plan B only allows at most one audio and one video section, so use the
3371 // first media section of that type.
3372 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003373 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003374 }
3375}
3376
deadbeef46c73892016-11-16 19:42:04 -08003377PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003378 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003379 return configuration_;
3380}
3381
deadbeef293e9262017-01-11 12:28:30 -08003382bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3383 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003384 RTC_DCHECK_RUN_ON(signaling_thread());
3385 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003386 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003387 if (IsClosed()) {
3388 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3389 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3390 }
3391
Qingsi Wanga2d60672018-04-11 16:57:45 -07003392 // According to JSEP, after setLocalDescription, changing the candidate pool
3393 // size is not allowed, and changing the set of ICE servers will not result
3394 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003395 if (local_description() && configuration.ice_candidate_pool_size !=
3396 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003397 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3398 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003399 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003400 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003401
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003402 if (local_description() &&
3403 configuration.use_media_transport != configuration_.use_media_transport) {
3404 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3405 "SetLocalDescription.";
3406 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3407 }
3408
3409 if (remote_description() &&
3410 configuration.use_media_transport != configuration_.use_media_transport) {
3411 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3412 "SetRemoteDescription.";
3413 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3414 }
3415
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003416 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003417 configuration.use_media_transport_for_data_channels !=
3418 configuration_.use_media_transport_for_data_channels) {
3419 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3420 "after calling SetLocalDescription.";
3421 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3422 }
3423
3424 if (remote_description() &&
3425 configuration.use_media_transport_for_data_channels !=
3426 configuration_.use_media_transport_for_data_channels) {
3427 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3428 "after calling SetRemoteDescription.";
3429 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3430 }
3431
3432 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003433 configuration.crypto_options != configuration_.crypto_options) {
3434 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3435 "SetLocalDescription.";
3436 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3437 }
3438
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003439 if (configuration.use_media_transport_for_data_channels ||
3440 configuration.use_media_transport) {
3441 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3442 << "Media transport requires MaxBundle policy.";
3443 }
3444
deadbeef293e9262017-01-11 12:28:30 -08003445 // The simplest (and most future-compatible) way to tell if the config was
3446 // modified in an invalid way is to copy each property we do support
3447 // modifying, then use operator==. There are far more properties we don't
3448 // support modifying than those we do, and more could be added.
3449 RTCConfiguration modified_config = configuration_;
3450 modified_config.servers = configuration.servers;
3451 modified_config.type = configuration.type;
3452 modified_config.ice_candidate_pool_size =
3453 configuration.ice_candidate_pool_size;
3454 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003455 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003456 modified_config.ice_check_interval_strong_connectivity =
3457 configuration.ice_check_interval_strong_connectivity;
3458 modified_config.ice_check_interval_weak_connectivity =
3459 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003460 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3461 modified_config.ice_unwritable_min_checks =
3462 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003463 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003464 modified_config.stun_candidate_keepalive_interval =
3465 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003466 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003467 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003468 modified_config.active_reset_srtp_params =
3469 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003470 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003471 modified_config.use_media_transport_for_data_channels =
3472 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003473 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003474 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003475 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3476 }
3477
Steve Anton038834f2017-07-14 15:59:59 -07003478 // Validate the modified configuration.
3479 RTCError validate_error = ValidateConfiguration(modified_config);
3480 if (!validate_error.ok()) {
3481 return SafeSetError(std::move(validate_error), error);
3482 }
3483
deadbeef293e9262017-01-11 12:28:30 -08003484 // Note that this isn't possible through chromium, since it's an unsigned
3485 // short in WebIDL.
3486 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003487 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003488 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3489 }
3490
3491 // Parse ICE servers before hopping to network thread.
3492 cricket::ServerAddresses stun_servers;
3493 std::vector<cricket::RelayServerConfig> turn_servers;
3494 RTCErrorType parse_error =
3495 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3496 if (parse_error != RTCErrorType::NONE) {
3497 return SafeSetError(parse_error, error);
3498 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003499 // Note if STUN or TURN servers were supplied.
3500 if (!stun_servers.empty()) {
3501 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3502 }
3503 if (!turn_servers.empty()) {
3504 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3505 }
deadbeef293e9262017-01-11 12:28:30 -08003506
3507 // In theory this shouldn't fail.
3508 if (!network_thread()->Invoke<bool>(
3509 RTC_FROM_HERE,
3510 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3511 stun_servers, turn_servers, modified_config.type,
3512 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003513 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003514 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003515 modified_config.stun_candidate_keepalive_interval,
3516 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003517 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003518 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3519 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003520
deadbeefd1a38b52016-12-10 13:15:33 -08003521 // As described in JSEP, calling setConfiguration with new ICE servers or
3522 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3523 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003524 if (modified_config.servers != configuration_.servers ||
3525 modified_config.type != configuration_.type ||
3526 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003527 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003528 }
skvladd1f5fda2017-02-03 16:54:05 -08003529
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003530 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003531 transport_controller_->SetMediaTransportSettings(
3532 modified_config.use_media_transport,
3533 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003534
Zhi Huangb57e1692018-06-12 11:41:11 -07003535 if (configuration_.active_reset_srtp_params !=
3536 modified_config.active_reset_srtp_params) {
3537 transport_controller_->SetActiveResetSrtpParams(
3538 modified_config.active_reset_srtp_params);
3539 }
3540
deadbeef293e9262017-01-11 12:28:30 -08003541 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003542 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003543 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003544}
3545
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003546bool PeerConnection::AddIceCandidate(
3547 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003548 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003549 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003550 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003551 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003552 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003553 return false;
3554 }
Steve Antond25da372017-11-06 14:50:29 -08003555
3556 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003557 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003558 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003559 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003560 return false;
3561 }
3562
3563 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003564 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003565 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003566 return false;
3567 }
3568
3569 bool valid = false;
3570 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3571 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003572 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003573 return false;
3574 }
3575
3576 // Add this candidate to the remote session description.
3577 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003578 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003579 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003580 return false;
3581 }
3582
3583 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003584 bool result = UseCandidate(ice_candidate);
3585 if (result) {
3586 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003587 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3588 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3589 }
3590 if (ice_candidate->candidate().address().IsPrivateIP()) {
3591 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3592 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003593 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3594 } else {
3595 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3596 }
3597 return result;
Steve Antond25da372017-11-06 14:50:29 -08003598 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003599 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003600 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003601 return true;
3602 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003603}
3604
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003605bool PeerConnection::RemoveIceCandidates(
3606 const std::vector<cricket::Candidate>& candidates) {
3607 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003608 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003609 if (IsClosed()) {
3610 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3611 return false;
3612 }
3613
Steve Antond25da372017-11-06 14:50:29 -08003614 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003615 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3616 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003617 return false;
3618 }
3619
3620 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003621 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003622 return false;
3623 }
3624
3625 size_t number_removed =
3626 mutable_remote_description()->RemoveCandidates(candidates);
3627 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003628 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003629 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003630 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003631 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003632 }
3633
3634 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003635 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3636 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003637 RTC_LOG(LS_ERROR)
3638 << "RemoveIceCandidates: Error when removing remote candidates: "
3639 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003640 }
3641 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003642}
3643
Niels Möller0c4f7be2018-05-07 14:01:37 +02003644RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003645 if (!worker_thread()->IsCurrent()) {
3646 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003647 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003648 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003649 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003650
Niels Möller0c4f7be2018-05-07 14:01:37 +02003651 const bool has_min = bitrate.min_bitrate_bps.has_value();
3652 const bool has_start = bitrate.start_bitrate_bps.has_value();
3653 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003654 if (has_min && *bitrate.min_bitrate_bps < 0) {
3655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3656 "min_bitrate_bps <= 0");
3657 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003658 if (has_start) {
3659 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003661 "start_bitrate_bps < min_bitrate_bps");
3662 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003663 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3664 "curent_bitrate_bps < 0");
3665 }
3666 }
3667 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003668 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003669 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003670 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003671 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3672 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3673 "max_bitrate_bps < min_bitrate_bps");
3674 } else if (*bitrate.max_bitrate_bps < 0) {
3675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3676 "max_bitrate_bps < 0");
3677 }
3678 }
3679
zstein4b979802017-06-02 14:37:37 -07003680 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003681 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003682
3683 return RTCError::OK();
3684}
3685
Alex Narest78609d52017-10-20 10:37:47 +02003686void PeerConnection::SetBitrateAllocationStrategy(
3687 std::unique_ptr<rtc::BitrateAllocationStrategy>
3688 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003689 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003690 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3691 // move-capture values in lambdas.
3692 struct Task {
3693 PeerConnection* const pc;
3694 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3695 void operator()() {
3696 RTC_DCHECK_RUN_ON(pc->worker_thread());
3697 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3698 }
3699 };
3700 worker_thread()->Invoke<void>(
3701 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003702 return;
3703 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003704 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003705 RTC_DCHECK(call_.get());
3706 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3707}
3708
henrika5f6bf242017-11-01 11:06:56 +01003709void PeerConnection::SetAudioPlayout(bool playout) {
3710 if (!worker_thread()->IsCurrent()) {
3711 worker_thread()->Invoke<void>(
3712 RTC_FROM_HERE,
3713 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3714 return;
3715 }
3716 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003717 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003718 audio_state->SetPlayout(playout);
3719}
3720
3721void PeerConnection::SetAudioRecording(bool recording) {
3722 if (!worker_thread()->IsCurrent()) {
3723 worker_thread()->Invoke<void>(
3724 RTC_FROM_HERE,
3725 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3726 return;
3727 }
3728 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003729 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003730 audio_state->SetRecording(recording);
3731}
3732
Steve Anton8c0f7a72017-10-03 10:03:10 -07003733std::unique_ptr<rtc::SSLCertificate>
3734PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003735 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3736 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003737 return nullptr;
3738 }
Steve Antonf25303e2018-10-16 15:23:31 -07003739 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003740}
3741
Zhi Huang70b820f2018-01-27 14:16:15 -08003742std::unique_ptr<rtc::SSLCertChain>
3743PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003744 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003745 auto audio_transceiver = GetFirstAudioTransceiver();
3746 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003747 return nullptr;
3748 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003749 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003750 audio_transceiver->internal()->channel()->transport_name());
3751}
3752
3753rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3754PeerConnection::GetFirstAudioTransceiver() const {
3755 for (auto transceiver : transceivers_) {
3756 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3757 return transceiver;
3758 }
3759 }
3760 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003761}
3762
ivoc14d5dbe2016-07-04 07:06:55 -07003763bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3764 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003765 // TODO(eladalon): It would be better to not allow negative values into PC.
3766 const size_t max_size = (max_size_bytes < 0)
3767 ? RtcEventLog::kUnlimitedOutput
3768 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003769 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3770 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3771 output_period_ms = 5000;
3772 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003773 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003774 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003775 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003776}
3777
Bjorn Tereliusde939432017-11-20 17:38:14 +01003778bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3779 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003780 // TODO(eladalon): In C++14, this can be done with a lambda.
3781 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003782 bool operator()() {
3783 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3784 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003785 PeerConnection* const pc;
3786 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003787 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003788 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003789 return worker_thread()->Invoke<bool>(
3790 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003791}
3792
3793void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003794 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003795 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3796}
3797
Harald Alvestrandad88c882018-11-28 16:47:46 +01003798rtc::scoped_refptr<DtlsTransportInterface>
3799PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003800 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003801 return transport_controller_->LookupDtlsTransportByMid(mid);
3802}
3803
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003804rtc::scoped_refptr<DtlsTransport>
3805PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003806 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003807 return transport_controller_->LookupDtlsTransportByMid(mid);
3808}
3809
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003810rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3811 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003812 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003813 return sctp_transport_;
3814}
3815
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003816const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003817 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003818 return pending_local_description_ ? pending_local_description_.get()
3819 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003820}
3821
3822const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003823 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003824 return pending_remote_description_ ? pending_remote_description_.get()
3825 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003826}
3827
deadbeeffe4a8a42016-12-20 17:56:17 -08003828const SessionDescriptionInterface* PeerConnection::current_local_description()
3829 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003830 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003831 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003832}
3833
3834const SessionDescriptionInterface* PeerConnection::current_remote_description()
3835 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003836 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003837 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003838}
3839
3840const SessionDescriptionInterface* PeerConnection::pending_local_description()
3841 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003842 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003843 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003844}
3845
3846const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3847 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003848 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003849 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003850}
3851
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003852void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003853 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003854 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003855 // Update stats here so that we have the most recent stats for tracks and
3856 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003857 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003858
Steve Anton75737c02017-11-06 10:37:17 -08003859 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003860 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003861
Mirko Bonadei739baf02019-01-27 17:29:42 +01003862 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003863 transceiver->Stop();
3864 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003865
3866 // Ensure that all asynchronous stats requests are completed before destroying
3867 // the transport controller below.
3868 if (stats_collector_) {
3869 stats_collector_->WaitForPendingRequest();
3870 }
3871
3872 // Don't destroy BaseChannels until after stats has been cleaned up so that
3873 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003874 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003875
Qingsi Wang93a84392018-01-30 17:13:09 -08003876 // The event log is used in the transport controller, which must be outlived
3877 // by the former. CreateOffer by the peer connection is implemented
3878 // asynchronously and if the peer connection is closed without resetting the
3879 // WebRTC session description factory, the session description factory would
3880 // call the transport controller.
3881 webrtc_session_desc_factory_.reset();
3882 transport_controller_.reset();
3883
deadbeef42a42632017-03-10 15:18:00 -08003884 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003885 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3886 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003887
Steve Anton978b8762017-09-29 12:15:02 -07003888 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003889 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003890 call_.reset();
3891 // The event log must outlive call (and any other object that uses it).
3892 event_log_.reset();
3893 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003894 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003895 // The .h file says that observer can be discarded after close() returns.
3896 // Make sure this is true.
3897 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003898}
3899
Steve Antonad182762018-09-05 20:22:40 +00003900void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003901 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003902 switch (msg->message_id) {
3903 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3904 SetSessionDescriptionMsg* param =
3905 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3906 param->observer->OnSuccess();
3907 delete param;
3908 break;
3909 }
3910 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3911 SetSessionDescriptionMsg* param =
3912 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3913 param->observer->OnFailure(std::move(param->error));
3914 delete param;
3915 break;
3916 }
3917 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3918 CreateSessionDescriptionMsg* param =
3919 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3920 param->observer->OnFailure(std::move(param->error));
3921 delete param;
3922 break;
3923 }
3924 case MSG_GETSTATS: {
3925 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3926 StatsReports reports;
3927 stats_->GetStats(param->track, &reports);
3928 param->observer->OnComplete(reports);
3929 delete param;
3930 break;
3931 }
3932 case MSG_FREE_DATACHANNELS: {
3933 sctp_data_channels_to_free_.clear();
3934 break;
3935 }
3936 case MSG_REPORT_USAGE_PATTERN: {
3937 ReportUsagePattern();
3938 break;
3939 }
3940 default:
3941 RTC_NOTREACHED() << "Not implemented";
3942 break;
3943 }
3944}
3945
Steve Antonafb0bb72018-02-20 11:35:37 -08003946cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3947 RTC_DCHECK(!IsUnifiedPlan());
3948 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3949 GetAudioTransceiver()->internal()->channel());
3950 if (voice_channel) {
3951 return voice_channel->media_channel();
3952 } else {
3953 return nullptr;
3954 }
3955}
3956
3957cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3958 RTC_DCHECK(!IsUnifiedPlan());
3959 auto* video_channel = static_cast<cricket::VideoChannel*>(
3960 GetVideoTransceiver()->internal()->channel());
3961 if (video_channel) {
3962 return video_channel->media_channel();
3963 } else {
3964 return nullptr;
3965 }
3966}
3967
Steve Anton4171afb2017-11-20 10:20:22 -08003968void PeerConnection::CreateAudioReceiver(
3969 MediaStreamInterface* stream,
3970 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003971 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3972 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003973 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3974 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003975 auto* audio_receiver = new AudioRtpReceiver(
3976 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003977 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003978 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3979 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3980 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003981 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003982 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003983 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003984}
3985
Steve Anton4171afb2017-11-20 10:20:22 -08003986void PeerConnection::CreateVideoReceiver(
3987 MediaStreamInterface* stream,
3988 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003989 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3990 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003991 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3992 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003993 auto* video_receiver = new VideoRtpReceiver(
3994 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003995 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003996 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3997 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3998 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003999 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004000 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004001 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004002}
4003
deadbeef70ab1a12015-09-28 16:53:55 -07004004// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4005// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004006rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004007 const RtpSenderInfo& remote_sender_info) {
4008 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4009 if (!receiver) {
4010 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4011 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004012 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004013 }
Steve Anton4171afb2017-11-20 10:20:22 -08004014 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4015 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4016 } else {
4017 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4018 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004019 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004020}
4021
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004022void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4023 MediaStreamInterface* stream) {
4024 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004025 RTC_DCHECK(track);
4026 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004027 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004028 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004029 // We already have a sender for this track, so just change the stream_id
4030 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004031 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004032 return;
4033 }
4034
4035 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004036 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004037 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004038 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004039 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004040 // If the sender has already been configured in SDP, we call SetSsrc,
4041 // which will connect the sender to the underlying transport. This can
4042 // occur if a local session description that contains the ID of the sender
4043 // is set before AddStream is called. It can also occur if the local
4044 // session description is not changed and RemoveStream is called, and
4045 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004046 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004047 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004048 if (sender_info) {
4049 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004050 }
4051}
4052
4053// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4054// indefinitely, when we have unified plan SDP.
4055void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4056 MediaStreamInterface* stream) {
4057 RTC_DCHECK(!IsClosed());
4058 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004059 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004060 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4061 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004062 return;
4063 }
Steve Anton4171afb2017-11-20 10:20:22 -08004064 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004065}
4066
4067void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4068 MediaStreamInterface* stream) {
4069 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004070 RTC_DCHECK(track);
4071 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004072 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004073 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 // We already have a sender for this track, so just change the stream_id
4075 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004076 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004077 return;
4078 }
4079
4080 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004081 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004082 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004083 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004084 GetVideoTransceiver()->internal()->AddSender(new_sender);
4085 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004086 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004087 if (sender_info) {
4088 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004089 }
4090}
4091
4092void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4093 MediaStreamInterface* stream) {
4094 RTC_DCHECK(!IsClosed());
4095 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004096 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004097 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4098 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004099 return;
4100 }
Steve Anton4171afb2017-11-20 10:20:22 -08004101 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004102}
4103
Steve Antonba818672017-11-06 10:21:57 -08004104void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004105 if (ice_connection_state_ == new_state) {
4106 return;
4107 }
4108
deadbeefcbecd352015-09-23 11:50:27 -07004109 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004110 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004111 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004112 return;
4113 }
Steve Antonba818672017-11-06 10:21:57 -08004114
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4116 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004117 RTC_DCHECK(ice_connection_state_ !=
4118 PeerConnectionInterface::kIceConnectionClosed);
4119
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004120 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004121 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004122}
4123
Alex Loiko9289eda2018-11-23 16:18:59 +00004124void PeerConnection::SetStandardizedIceConnectionState(
4125 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004126 if (standardized_ice_connection_state_ == new_state)
4127 return;
4128 if (IsClosed())
4129 return;
4130 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004131 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004132}
4133
Jonas Olsson635474e2018-10-18 15:58:17 +02004134void PeerConnection::SetConnectionState(
4135 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004136 if (connection_state_ == new_state)
4137 return;
4138 if (IsClosed())
4139 return;
4140 connection_state_ = new_state;
4141 Observer()->OnConnectionChange(new_state);
4142}
4143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004144void PeerConnection::OnIceGatheringChange(
4145 PeerConnectionInterface::IceGatheringState new_state) {
4146 if (IsClosed()) {
4147 return;
4148 }
4149 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004150 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004151}
4152
jbauch81bf7b02017-03-25 08:31:12 -07004153void PeerConnection::OnIceCandidate(
4154 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004155 if (IsClosed()) {
4156 return;
4157 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004158 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004159 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4160 candidate->candidate().address().IsPrivateIP()) {
4161 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4162 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004163 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4164 candidate->candidate().address().IsUnresolvedIP()) {
4165 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4166 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004167 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004168}
4169
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004170void PeerConnection::OnIceCandidatesRemoved(
4171 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004172 if (IsClosed()) {
4173 return;
4174 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004175 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004176}
4177
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004178void PeerConnection::ChangeSignalingState(
4179 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004180 if (signaling_state_ == signaling_state) {
4181 return;
4182 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004183 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4184 << GetSignalingStateString(signaling_state_)
4185 << " New state: "
4186 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004187 signaling_state_ = signaling_state;
4188 if (signaling_state == kClosed) {
4189 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004190 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004191 standardized_ice_connection_state_ =
4192 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004193 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4194 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004195 if (ice_gathering_state_ != kIceGatheringComplete) {
4196 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004197 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004198 }
4199 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004200 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004201}
4202
deadbeefeb459812015-12-15 19:24:43 -08004203void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4204 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004205 if (IsClosed()) {
4206 return;
4207 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004208 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004209 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004210}
4211
deadbeefeb459812015-12-15 19:24:43 -08004212void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4213 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004214 if (IsClosed()) {
4215 return;
4216 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004218 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004219}
4220
4221void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4222 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004223 if (IsClosed()) {
4224 return;
4225 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004226 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004227 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004228}
4229
4230void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4231 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004232 if (IsClosed()) {
4233 return;
4234 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004235 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004236 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004237}
4238
Henrik Boström31638672017-11-23 17:48:32 +01004239void PeerConnection::PostSetSessionDescriptionSuccess(
4240 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004241 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4242 signaling_thread()->Post(RTC_FROM_HERE, this,
4243 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004244}
4245
deadbeefab9b2d12015-10-14 11:33:11 -07004246void PeerConnection::PostSetSessionDescriptionFailure(
4247 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004248 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004249 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004250 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4251 msg->error = std::move(error);
4252 signaling_thread()->Post(RTC_FROM_HERE, this,
4253 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004254}
4255
4256void PeerConnection::PostCreateSessionDescriptionFailure(
4257 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004258 RTCError error) {
4259 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004260 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4261 msg->error = std::move(error);
4262 signaling_thread()->Post(RTC_FROM_HERE, this,
4263 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004264}
4265
zhihuang1c378ed2017-08-17 14:10:50 -07004266void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004267 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004268 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004269 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004270
Steve Antondcc3c022017-12-22 16:02:54 -08004271 if (IsUnifiedPlan()) {
4272 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4273 } else {
4274 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4275 }
4276
Steve Antonfa2260d2017-12-28 16:38:23 -08004277 // Intentionally unset the data channel type for RTP data channel with the
4278 // second condition. Otherwise the RTP data channels would be successfully
4279 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4280 // when building with chromium. We want to leave RTP data channels broken, so
4281 // people won't try to use them.
4282 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4283 session_options->data_channel_type = data_channel_type();
4284 }
4285
Steve Antondcc3c022017-12-22 16:02:54 -08004286 // Apply ICE restart flag and renomination flag.
4287 for (auto& options : session_options->media_description_options) {
4288 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4289 options.transport_options.enable_ice_renomination =
4290 configuration_.enable_ice_renomination;
4291 }
4292
4293 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004294 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004295 session_options->pooled_ice_credentials =
4296 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4297 RTC_FROM_HERE,
4298 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4299 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004300 session_options->offer_extmap_allow_mixed =
4301 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004302
4303 if (configuration_.enable_dtls_srtp &&
4304 !configuration_.enable_dtls_srtp.value()) {
4305 session_options->media_transport_settings =
4306 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4307 }
Steve Antondcc3c022017-12-22 16:02:54 -08004308}
4309
4310void PeerConnection::GetOptionsForPlanBOffer(
4311 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4312 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004313 // Figure out transceiver directional preferences.
4314 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4315 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4316
4317 // By default, generate sendrecv/recvonly m= sections.
4318 bool recv_audio = true;
4319 bool recv_video = true;
4320
4321 // By default, only offer a new m= section if we have media to send with it.
4322 bool offer_new_audio_description = send_audio;
4323 bool offer_new_video_description = send_video;
4324 bool offer_new_data_description = HasDataChannels();
4325
4326 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004327 if (offer_answer_options.offer_to_receive_audio !=
4328 RTCOfferAnswerOptions::kUndefined) {
4329 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004330 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004331 offer_new_audio_description ||
4332 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004333 }
Steve Antondcc3c022017-12-22 16:02:54 -08004334 if (offer_answer_options.offer_to_receive_video !=
4335 RTCOfferAnswerOptions::kUndefined) {
4336 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004337 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004338 offer_new_video_description ||
4339 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004340 }
4341
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004342 absl::optional<size_t> audio_index;
4343 absl::optional<size_t> video_index;
4344 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004345 // If a current description exists, generate m= sections in the same order,
4346 // using the first audio/video/data section that appears and rejecting
4347 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004348 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004349 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004350 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004351 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4352 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4353 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004354 }
4355
zhihuang1c378ed2017-08-17 14:10:50 -07004356 // Add audio/video/data m= sections to the end if needed.
4357 if (!audio_index && offer_new_audio_description) {
4358 session_options->media_description_options.push_back(
4359 cricket::MediaDescriptionOptions(
4360 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004361 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4362 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004363 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004364 }
zhihuang1c378ed2017-08-17 14:10:50 -07004365 if (!video_index && offer_new_video_description) {
4366 session_options->media_description_options.push_back(
4367 cricket::MediaDescriptionOptions(
4368 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004369 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4370 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004371 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004372 }
zhihuang1c378ed2017-08-17 14:10:50 -07004373 if (!data_index && offer_new_data_description) {
4374 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004375 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004376 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004377 }
4378
4379 cricket::MediaDescriptionOptions* audio_media_description_options =
4380 !audio_index ? nullptr
4381 : &session_options->media_description_options[*audio_index];
4382 cricket::MediaDescriptionOptions* video_media_description_options =
4383 !video_index ? nullptr
4384 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004385
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004386 AddPlanBRtpSenderOptions(GetSendersInternal(),
4387 audio_media_description_options,
4388 video_media_description_options,
4389 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004390}
4391
Steve Antondcc3c022017-12-22 16:02:54 -08004392static cricket::MediaDescriptionOptions
4393GetMediaDescriptionOptionsForTransceiver(
4394 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4395 transceiver,
4396 const std::string& mid) {
4397 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004398 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004399 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004400 // This behavior is specified in JSEP. The gist is that:
4401 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4402 // sendrecv.
4403 // 2. If the MSID is included, then it must be included in any subsequent
4404 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004405 if (transceiver->stopped() ||
4406 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4407 !transceiver->internal()->has_ever_been_used_to_send())) {
4408 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004409 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004410
4411 cricket::SenderOptions sender_options;
4412 sender_options.track_id = transceiver->sender()->id();
4413 sender_options.stream_ids = transceiver->sender()->stream_ids();
4414
4415 // The following sets up RIDs and Simulcast.
4416 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004417 RtpParameters send_parameters =
4418 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004419 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4420 send_parameters.encodings.end(),
4421 [](const RtpEncodingParameters& encoding) {
4422 return !encoding.rid.empty();
4423 });
4424
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004425 std::vector<RidDescription> send_rids;
4426 SimulcastLayerList send_layers;
4427 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4428 if (encoding.rid.empty()) {
4429 continue;
4430 }
4431 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4432 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4433 }
4434
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004435 if (has_rids) {
4436 sender_options.rids = send_rids;
4437 }
4438
4439 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004440 // When RIDs are configured, we must set num_sim_layers to 0 to.
4441 // Otherwise, num_sim_layers must be 1 because either there is no
4442 // simulcast, or simulcast is acheived by munging the SDP.
4443 sender_options.num_sim_layers = has_rids ? 0 : 1;
4444 media_description_options.sender_options.push_back(sender_options);
4445
Steve Antondcc3c022017-12-22 16:02:54 -08004446 return media_description_options;
4447}
4448
Steve Anton5c72e712018-12-10 14:25:30 -08004449// Returns the ContentInfo at mline index |i|, or null if none exists.
4450static const ContentInfo* GetContentByIndex(
4451 const SessionDescriptionInterface* sdesc,
4452 size_t i) {
4453 if (!sdesc) {
4454 return nullptr;
4455 }
4456 const ContentInfos& contents = sdesc->description()->contents();
4457 return (i < contents.size() ? &contents[i] : nullptr);
4458}
4459
Steve Antondcc3c022017-12-22 16:02:54 -08004460void PeerConnection::GetOptionsForUnifiedPlanOffer(
4461 const RTCOfferAnswerOptions& offer_answer_options,
4462 cricket::MediaSessionOptions* session_options) {
4463 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4464 // Offers) and 5.2.2 (Subsequent Offers).
4465 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4466 const ContentInfos& local_contents =
4467 (local_description() ? local_description()->description()->contents()
4468 : ContentInfos());
4469 const ContentInfos& remote_contents =
4470 (remote_description() ? remote_description()->description()->contents()
4471 : ContentInfos());
4472 // The mline indices that can be recycled. New transceivers should reuse these
4473 // slots first.
4474 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004475 // First, go through each media section that exists in either the local or
4476 // remote description and generate a media section in this offer for the
4477 // associated transceiver. If a media section can be recycled, generate a
4478 // default, rejected media section here that can be later overwritten.
4479 for (size_t i = 0;
4480 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4481 // Either |local_content| or |remote_content| is non-null.
4482 const ContentInfo* local_content =
4483 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004484 const ContentInfo* current_local_content =
4485 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004486 const ContentInfo* remote_content =
4487 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004488 const ContentInfo* current_remote_content =
4489 GetContentByIndex(current_remote_description(), i);
4490 bool had_been_rejected =
4491 (current_local_content && current_local_content->rejected) ||
4492 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004493 const std::string& mid =
4494 (local_content ? local_content->name : remote_content->name);
4495 cricket::MediaType media_type =
4496 (local_content ? local_content->media_description()->type()
4497 : remote_content->media_description()->type());
4498 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4499 media_type == cricket::MEDIA_TYPE_VIDEO) {
4500 auto transceiver = GetAssociatedTransceiver(mid);
4501 RTC_CHECK(transceiver);
4502 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004503 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004504 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004505 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004506 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4507 RtpTransceiverDirection::kInactive,
4508 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004509 recycleable_mline_indices.push(i);
4510 } else {
4511 session_options->media_description_options.push_back(
4512 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4513 // CreateOffer shouldn't really cause any state changes in
4514 // PeerConnection, but we need a way to match new transceivers to new
4515 // media sections in SetLocalDescription and JSEP specifies this is done
4516 // by recording the index of the media section generated for the
4517 // transceiver in the offer.
4518 transceiver->internal()->set_mline_index(i);
4519 }
4520 } else {
4521 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004522 RTC_CHECK(GetDataMid());
4523 if (had_been_rejected || mid != *GetDataMid()) {
4524 session_options->media_description_options.push_back(
4525 GetMediaDescriptionOptionsForRejectedData(mid));
4526 } else {
4527 session_options->media_description_options.push_back(
4528 GetMediaDescriptionOptionsForActiveData(mid));
4529 }
Steve Antondcc3c022017-12-22 16:02:54 -08004530 }
4531 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004532
Steve Antondcc3c022017-12-22 16:02:54 -08004533 // Next, look for transceivers that are newly added (that is, are not stopped
4534 // and not associated). Reuse media sections marked as recyclable first,
4535 // otherwise append to the end of the offer. New media sections should be
4536 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004537 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004538 if (transceiver->mid() || transceiver->stopped()) {
4539 continue;
4540 }
4541 size_t mline_index;
4542 if (!recycleable_mline_indices.empty()) {
4543 mline_index = recycleable_mline_indices.front();
4544 recycleable_mline_indices.pop();
4545 session_options->media_description_options[mline_index] =
4546 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004547 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004548 } else {
4549 mline_index = session_options->media_description_options.size();
4550 session_options->media_description_options.push_back(
4551 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004552 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004553 }
4554 // See comment above for why CreateOffer changes the transceiver's state.
4555 transceiver->internal()->set_mline_index(mline_index);
4556 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004557 // Lastly, add a m-section if we have local data channels and an m section
4558 // does not already exist.
4559 if (!GetDataMid() && HasDataChannels()) {
4560 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004561 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004562 }
Steve Antondcc3c022017-12-22 16:02:54 -08004563}
4564
4565void PeerConnection::GetOptionsForAnswer(
4566 const RTCOfferAnswerOptions& offer_answer_options,
4567 cricket::MediaSessionOptions* session_options) {
4568 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4569
4570 if (IsUnifiedPlan()) {
4571 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4572 } else {
4573 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4574 }
4575
Steve Antonfa2260d2017-12-28 16:38:23 -08004576 // Intentionally unset the data channel type for RTP data channel. Otherwise
4577 // the RTP data channels would be successfully negotiated by default and the
4578 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4579 // We want to leave RTP data channels broken, so people won't try to use them.
4580 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4581 session_options->data_channel_type = data_channel_type();
4582 }
4583
Steve Antondcc3c022017-12-22 16:02:54 -08004584 // Apply ICE renomination flag.
4585 for (auto& options : session_options->media_description_options) {
4586 options.transport_options.enable_ice_renomination =
4587 configuration_.enable_ice_renomination;
4588 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004589
4590 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004591 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004592 session_options->pooled_ice_credentials =
4593 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4594 RTC_FROM_HERE,
4595 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4596 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004597}
4598
Steve Antondcc3c022017-12-22 16:02:54 -08004599void PeerConnection::GetOptionsForPlanBAnswer(
4600 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004601 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004602 // Figure out transceiver directional preferences.
4603 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4604 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4605
4606 // By default, generate sendrecv/recvonly m= sections. The direction is also
4607 // restricted by the direction in the offer.
4608 bool recv_audio = true;
4609 bool recv_video = true;
4610
4611 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004612 if (offer_answer_options.offer_to_receive_audio !=
4613 RTCOfferAnswerOptions::kUndefined) {
4614 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004615 }
Steve Antondcc3c022017-12-22 16:02:54 -08004616 if (offer_answer_options.offer_to_receive_video !=
4617 RTCOfferAnswerOptions::kUndefined) {
4618 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004619 }
4620
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004621 absl::optional<size_t> audio_index;
4622 absl::optional<size_t> video_index;
4623 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004624
4625 // Generate m= sections that match those in the offer.
4626 // Note that mediasession.cc will handle intersection our preferred
4627 // direction with the offered direction.
4628 GenerateMediaDescriptionOptions(
4629 remote_description(),
4630 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4631 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4632 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004633
4634 cricket::MediaDescriptionOptions* audio_media_description_options =
4635 !audio_index ? nullptr
4636 : &session_options->media_description_options[*audio_index];
4637 cricket::MediaDescriptionOptions* video_media_description_options =
4638 !video_index ? nullptr
4639 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004640
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004641 AddPlanBRtpSenderOptions(GetSendersInternal(),
4642 audio_media_description_options,
4643 video_media_description_options,
4644 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004645}
zhihuangaf388472016-11-02 16:49:48 -07004646
Steve Antondcc3c022017-12-22 16:02:54 -08004647void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4648 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4649 cricket::MediaSessionOptions* session_options) {
4650 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4651 // Answers) and 5.3.2 (Subsequent Answers).
4652 RTC_DCHECK(remote_description());
4653 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4654 for (const ContentInfo& content :
4655 remote_description()->description()->contents()) {
4656 cricket::MediaType media_type = content.media_description()->type();
4657 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4658 media_type == cricket::MEDIA_TYPE_VIDEO) {
4659 auto transceiver = GetAssociatedTransceiver(content.name);
4660 RTC_CHECK(transceiver);
4661 session_options->media_description_options.push_back(
4662 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4663 } else {
4664 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004665 // Reject all data sections if data channels are disabled.
4666 // Reject a data section if it has already been rejected.
4667 // Reject all data sections except for the first one.
4668 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4669 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004670 session_options->media_description_options.push_back(
4671 GetMediaDescriptionOptionsForRejectedData(content.name));
4672 } else {
4673 session_options->media_description_options.push_back(
4674 GetMediaDescriptionOptionsForActiveData(content.name));
4675 }
Steve Antondcc3c022017-12-22 16:02:54 -08004676 }
4677 }
htaa2a49d92016-03-04 02:51:39 -08004678}
4679
zhihuang1c378ed2017-08-17 14:10:50 -07004680void PeerConnection::GenerateMediaDescriptionOptions(
4681 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004682 RtpTransceiverDirection audio_direction,
4683 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004684 absl::optional<size_t>* audio_index,
4685 absl::optional<size_t>* video_index,
4686 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004687 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004688 for (const cricket::ContentInfo& content :
4689 session_desc->description()->contents()) {
4690 if (IsAudioContent(&content)) {
4691 // If we already have an audio m= section, reject this extra one.
4692 if (*audio_index) {
4693 session_options->media_description_options.push_back(
4694 cricket::MediaDescriptionOptions(
4695 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004696 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004697 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004698 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004699 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004700 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4701 content.name, audio_direction,
4702 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004703 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004704 }
4705 } else if (IsVideoContent(&content)) {
4706 // If we already have an video m= section, reject this extra one.
4707 if (*video_index) {
4708 session_options->media_description_options.push_back(
4709 cricket::MediaDescriptionOptions(
4710 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004711 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004712 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004713 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004714 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004715 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4716 content.name, video_direction,
4717 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004718 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004719 }
4720 } else {
4721 RTC_DCHECK(IsDataContent(&content));
4722 // If we already have an data m= section, reject this extra one.
4723 if (*data_index) {
4724 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004725 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004726 } else {
4727 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004728 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004729 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004730 }
4731 }
htaa2a49d92016-03-04 02:51:39 -08004732 }
deadbeefab9b2d12015-10-14 11:33:11 -07004733}
4734
Steve Antonfa2260d2017-12-28 16:38:23 -08004735cricket::MediaDescriptionOptions
4736PeerConnection::GetMediaDescriptionOptionsForActiveData(
4737 const std::string& mid) const {
4738 // Direction for data sections is meaningless, but legacy endpoints might
4739 // expect sendrecv.
4740 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4741 RtpTransceiverDirection::kSendRecv,
4742 /*stopped=*/false);
4743 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4744 return options;
4745}
4746
4747cricket::MediaDescriptionOptions
4748PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4749 const std::string& mid) const {
4750 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4751 RtpTransceiverDirection::kInactive,
4752 /*stopped=*/true);
4753 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4754 return options;
4755}
4756
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004757absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004758 switch (data_channel_type_) {
4759 case cricket::DCT_RTP:
4760 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004761 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004762 }
4763 return rtp_data_channel_->content_name();
4764 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004765 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004766 case cricket::DCT_MEDIA_TRANSPORT:
4767 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004768 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004769 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004770 }
4771}
4772
Steve Anton4171afb2017-11-20 10:20:22 -08004773void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4774 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4775 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004776 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004777}
4778
Steve Anton4171afb2017-11-20 10:20:22 -08004779void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004780 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004781 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004782 cricket::MediaType media_type,
4783 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004784 RTC_DCHECK(!IsUnifiedPlan());
4785
Steve Anton4171afb2017-11-20 10:20:22 -08004786 std::vector<RtpSenderInfo>* current_senders =
4787 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004788
Steve Anton4171afb2017-11-20 10:20:22 -08004789 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004790 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004791 for (auto sender_it = current_senders->begin();
4792 sender_it != current_senders->end();
4793 /* incremented manually */) {
4794 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004795 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004796 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004797 std::string params_stream_id;
4798 if (params) {
4799 params_stream_id =
4800 (!params->first_stream_id().empty() ? params->first_stream_id()
4801 : kDefaultStreamId);
4802 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004803 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004804 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004805 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004806 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004807 sender_exists) {
4808 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004809 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004810 OnRemoteSenderRemoved(info, media_type);
4811 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004812 }
4813 }
4814
Steve Anton4171afb2017-11-20 10:20:22 -08004815 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004816 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004817 if (!params.has_ssrcs()) {
4818 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4819 // sender, this means it is coming from a Unified Plan endpoint,so we just
4820 // create a default.
4821 default_sender_needed = true;
4822 break;
4823 }
4824
Seth Hampson845e8782018-03-02 11:34:10 -08004825 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004826 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004827 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4828 // not supported in Plan B, we just take the first here and create the
4829 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004830 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004831 (!params.first_stream_id().empty() ? params.first_stream_id()
4832 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004833 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004834 uint32_t ssrc = params.first_ssrc();
4835
4836 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004837 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004838 if (!stream) {
4839 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004840 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004841 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004842 remote_streams_->AddStream(stream);
4843 new_streams->AddStream(stream);
4844 }
4845
Steve Anton4171afb2017-11-20 10:20:22 -08004846 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004847 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004848 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004849 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004850 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004851 }
4852 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004853
Steve Anton4171afb2017-11-20 10:20:22 -08004854 // Add default sender if necessary.
4855 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004856 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004857 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004858 if (!default_stream) {
4859 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004860 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004861 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004862 remote_streams_->AddStream(default_stream);
4863 new_streams->AddStream(default_stream);
4864 }
Steve Anton4171afb2017-11-20 10:20:22 -08004865 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4866 ? kDefaultAudioSenderId
4867 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004868 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004869 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004870 if (!default_sender_info) {
4871 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004872 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004873 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004874 }
4875 }
deadbeefab9b2d12015-10-14 11:33:11 -07004876}
4877
Steve Anton4171afb2017-11-20 10:20:22 -08004878void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4879 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004880 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4881 << " receiver for track_id=" << sender_info.sender_id
4882 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004883
Steve Anton3d954a62018-04-02 11:27:23 -07004884 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004885 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004886 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004887 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004888 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004889 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004890 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004891 }
4892}
4893
Steve Anton4171afb2017-11-20 10:20:22 -08004894void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4895 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004896 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4897 << " receiver for track_id=" << sender_info.sender_id
4898 << " and stream_id=" << sender_info.stream_id;
4899
Seth Hampson845e8782018-03-02 11:34:10 -08004900 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004901
Henrik Boström933d8b02017-10-10 10:05:16 -07004902 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004903 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004904 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4905 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004906 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004907 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004908 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004909 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004910 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004911 }
4912 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004913 // Stopping or destroying a VideoRtpReceiver will end the
4914 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004915 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004916 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004917 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004918 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004919 // There's no guarantee the track is still available, e.g. the track may
4920 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004921 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004922 }
4923 } else {
nisseede5da42017-01-12 05:15:36 -08004924 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004925 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004926 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004927 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004928 }
deadbeefab9b2d12015-10-14 11:33:11 -07004929}
4930
4931void PeerConnection::UpdateEndedRemoteMediaStreams() {
4932 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4933 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4934 MediaStreamInterface* stream = remote_streams_->at(i);
4935 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4936 streams_to_remove.push_back(stream);
4937 }
4938 }
4939
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004940 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004941 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004942 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004943 }
4944}
4945
Steve Anton4171afb2017-11-20 10:20:22 -08004946void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004947 const std::vector<cricket::StreamParams>& streams,
4948 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004949 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004950
Seth Hampson845e8782018-03-02 11:34:10 -08004951 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004952 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004953 for (auto sender_it = current_senders->begin();
4954 sender_it != current_senders->end();
4955 /* incremented manually */) {
4956 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004957 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004958 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4959 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004960 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004961 OnLocalSenderRemoved(info, media_type);
4962 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004963 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004964 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004965 }
4966 }
4967
Steve Anton4171afb2017-11-20 10:20:22 -08004968 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004969 for (const cricket::StreamParams& params : streams) {
4970 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004971 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004972 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004973 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004974 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004975 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004976 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004977 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004978 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004979 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004980 }
4981 }
4982}
4983
Steve Anton4171afb2017-11-20 10:20:22 -08004984void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4985 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004986 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004987 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004988 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004989 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4990 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004991 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004992 return;
4993 }
4994
deadbeeffac06552015-11-25 11:26:01 -08004995 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004996 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004997 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004998 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004999 }
deadbeeffac06552015-11-25 11:26:01 -08005000
Seth Hampson5b4f0752018-04-02 16:31:36 -07005001 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005002 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005003}
5004
Steve Anton4171afb2017-11-20 10:20:22 -08005005void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5006 cricket::MediaType media_type) {
5007 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005008 if (!sender) {
5009 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005010 // SessionDescriptions has been renegotiated.
5011 return;
5012 }
deadbeeffac06552015-11-25 11:26:01 -08005013
5014 // A sender has been removed from the SessionDescription but it's still
5015 // associated with the PeerConnection. This only occurs if the SDP doesn't
5016 // match with the calls to CreateSender, AddStream and RemoveStream.
5017 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005019 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005020 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005021 }
deadbeeffac06552015-11-25 11:26:01 -08005022
Steve Anton4171afb2017-11-20 10:20:22 -08005023 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005024}
5025
5026void PeerConnection::UpdateLocalRtpDataChannels(
5027 const cricket::StreamParamsVec& streams) {
5028 std::vector<std::string> existing_channels;
5029
5030 // Find new and active data channels.
5031 for (const cricket::StreamParams& params : streams) {
5032 // |it->sync_label| is actually the data channel label. The reason is that
5033 // we use the same naming of data channels as we do for
5034 // MediaStreams and Tracks.
5035 // For MediaStreams, the sync_label is the MediaStream label and the
5036 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005037 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005038 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005039 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005040 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005041 continue;
5042 }
5043 // Set the SSRC the data channel should use for sending.
5044 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5045 existing_channels.push_back(data_channel_it->first);
5046 }
5047
5048 UpdateClosingRtpDataChannels(existing_channels, true);
5049}
5050
5051void PeerConnection::UpdateRemoteRtpDataChannels(
5052 const cricket::StreamParamsVec& streams) {
5053 std::vector<std::string> existing_channels;
5054
5055 // Find new and active data channels.
5056 for (const cricket::StreamParams& params : streams) {
5057 // The data channel label is either the mslabel or the SSRC if the mslabel
5058 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005059 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005060 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005061 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005062 auto data_channel_it = rtp_data_channels_.find(label);
5063 if (data_channel_it == rtp_data_channels_.end()) {
5064 // This is a new data channel.
5065 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5066 } else {
5067 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5068 }
5069 existing_channels.push_back(label);
5070 }
5071
5072 UpdateClosingRtpDataChannels(existing_channels, false);
5073}
5074
5075void PeerConnection::UpdateClosingRtpDataChannels(
5076 const std::vector<std::string>& active_channels,
5077 bool is_local_update) {
5078 auto it = rtp_data_channels_.begin();
5079 while (it != rtp_data_channels_.end()) {
5080 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005081 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005082 ++it;
5083 continue;
5084 }
5085
5086 if (is_local_update) {
5087 data_channel->SetSendSsrc(0);
5088 } else {
5089 data_channel->RemotePeerRequestClose();
5090 }
5091
5092 if (data_channel->state() == DataChannel::kClosed) {
5093 rtp_data_channels_.erase(it);
5094 it = rtp_data_channels_.begin();
5095 } else {
5096 ++it;
5097 }
5098 }
5099}
5100
5101void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5102 uint32_t remote_ssrc) {
5103 rtc::scoped_refptr<DataChannel> channel(
5104 InternalCreateDataChannel(label, nullptr));
5105 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005106 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005107 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005108 return;
5109 }
5110 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005111 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5112 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005113 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005114}
5115
5116rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5117 const std::string& label,
5118 const InternalDataChannelInit* config) {
5119 if (IsClosed()) {
5120 return nullptr;
5121 }
Steve Anton75737c02017-11-06 10:37:17 -08005122 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005123 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005124 << "InternalCreateDataChannel: Data is not supported in this call.";
5125 return nullptr;
5126 }
5127 InternalDataChannelInit new_config =
5128 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005129 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005130 if (new_config.id < 0) {
5131 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005132 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005133 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005134 RTC_LOG(LS_ERROR)
5135 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005136 return nullptr;
5137 }
5138 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005140 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005141 return nullptr;
5142 }
5143 }
5144
Steve Anton75737c02017-11-06 10:37:17 -08005145 rtc::scoped_refptr<DataChannel> channel(
5146 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005147 if (!channel) {
5148 sid_allocator_.ReleaseSid(new_config.id);
5149 return nullptr;
5150 }
5151
5152 if (channel->data_channel_type() == cricket::DCT_RTP) {
5153 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005154 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5155 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005156 return nullptr;
5157 }
5158 rtp_data_channels_[channel->label()] = channel;
5159 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005160 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005161 sctp_data_channels_.push_back(channel);
5162 channel->SignalClosed.connect(this,
5163 &PeerConnection::OnSctpDataChannelClosed);
5164 }
5165
Steve Anton2d8609c2018-01-23 16:38:46 -08005166 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005167 return channel;
5168}
5169
5170bool PeerConnection::HasDataChannels() const {
5171 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5172}
5173
5174void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005175 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005176 for (const auto& channel : sctp_data_channels_) {
5177 if (channel->id() < 0) {
5178 int sid;
5179 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005180 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5181 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005182 continue;
5183 }
5184 channel->SetSctpSid(sid);
5185 }
5186 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005187 // Since closing modifies the list of channels, we have to do the actual
5188 // closing outside the loop.
5189 for (const auto& channel : channels_to_close) {
5190 channel->CloseAbruptly();
5191 }
deadbeefab9b2d12015-10-14 11:33:11 -07005192}
5193
5194void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005195 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005196 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5197 ++it) {
5198 if (it->get() == channel) {
5199 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005200 // After the closing procedure is done, it's safe to use this ID for
5201 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005202 sid_allocator_.ReleaseSid(channel->id());
5203 }
deadbeefbd292462015-12-14 18:15:29 -08005204 // Since this method is triggered by a signal from the DataChannel,
5205 // we can't free it directly here; we need to free it asynchronously.
5206 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005207 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005208 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5209 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005210 return;
5211 }
5212 }
5213}
5214
deadbeefab9b2d12015-10-14 11:33:11 -07005215void PeerConnection::OnDataChannelDestroyed() {
5216 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5217 // DataChannel may callback to us and try to modify the list.
5218 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5219 temp_rtp_dcs.swap(rtp_data_channels_);
5220 for (const auto& kv : temp_rtp_dcs) {
5221 kv.second->OnTransportChannelDestroyed();
5222 }
5223
5224 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5225 temp_sctp_dcs.swap(sctp_data_channels_);
5226 for (const auto& channel : temp_sctp_dcs) {
5227 channel->OnTransportChannelDestroyed();
5228 }
5229}
5230
5231void PeerConnection::OnDataChannelOpenMessage(
5232 const std::string& label,
5233 const InternalDataChannelInit& config) {
5234 rtc::scoped_refptr<DataChannel> channel(
5235 InternalCreateDataChannel(label, &config));
5236 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005237 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005238 return;
5239 }
5240
deadbeefa601f5c2016-06-06 14:27:39 -07005241 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5242 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005243 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005244 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005245}
5246
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005247bool PeerConnection::HandleOpenMessage_s(
5248 const cricket::ReceiveDataParams& params,
5249 const rtc::CopyOnWriteBuffer& buffer) {
5250 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5251 // Received OPEN message; parse and signal that a new data channel should
5252 // be created.
5253 std::string label;
5254 InternalDataChannelInit config;
5255 config.id = params.ssrc;
5256 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5257 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5258 << params.ssrc;
5259 return true;
5260 }
5261 config.open_handshake_role = InternalDataChannelInit::kAcker;
5262 OnDataChannelOpenMessage(label, config);
5263 return true;
5264 }
5265 return false;
5266}
5267
Steve Anton4171afb2017-11-20 10:20:22 -08005268rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5269PeerConnection::GetAudioTransceiver() const {
5270 // This method only works with Plan B SDP, where there is a single
5271 // audio/video transceiver.
5272 RTC_DCHECK(!IsUnifiedPlan());
5273 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005274 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005275 return transceiver;
5276 }
5277 }
5278 RTC_NOTREACHED();
5279 return nullptr;
5280}
5281
5282rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5283PeerConnection::GetVideoTransceiver() const {
5284 // This method only works with Plan B SDP, where there is a single
5285 // audio/video transceiver.
5286 RTC_DCHECK(!IsUnifiedPlan());
5287 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005288 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005289 return transceiver;
5290 }
5291 }
5292 RTC_NOTREACHED();
5293 return nullptr;
5294}
5295
5296// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5297// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005298bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005299 switch (type) {
5300 case cricket::MEDIA_TYPE_AUDIO:
5301 return !GetAudioTransceiver()->internal()->senders().empty();
5302 case cricket::MEDIA_TYPE_VIDEO:
5303 return !GetVideoTransceiver()->internal()->senders().empty();
5304 case cricket::MEDIA_TYPE_DATA:
5305 return false;
5306 }
5307 RTC_NOTREACHED();
5308 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005309}
5310
Steve Anton4171afb2017-11-20 10:20:22 -08005311rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5312PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005313 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005314 for (auto sender : transceiver->internal()->senders()) {
5315 if (sender->track() == track) {
5316 return sender;
5317 }
5318 }
5319 }
5320 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005321}
5322
Steve Anton4171afb2017-11-20 10:20:22 -08005323rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5324PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005325 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005326 for (auto sender : transceiver->internal()->senders()) {
5327 if (sender->id() == sender_id) {
5328 return sender;
5329 }
5330 }
5331 }
5332 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005333}
5334
Steve Anton4171afb2017-11-20 10:20:22 -08005335rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5336PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005337 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005338 for (auto receiver : transceiver->internal()->receivers()) {
5339 if (receiver->id() == receiver_id) {
5340 return receiver;
5341 }
5342 }
5343 }
5344 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005345}
5346
Steve Anton4171afb2017-11-20 10:20:22 -08005347std::vector<PeerConnection::RtpSenderInfo>*
5348PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5349 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5350 media_type == cricket::MEDIA_TYPE_VIDEO);
5351 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5352 ? &remote_audio_sender_infos_
5353 : &remote_video_sender_infos_;
5354}
5355
5356std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005357 cricket::MediaType media_type) {
5358 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5359 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005360 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5361 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005362}
5363
Steve Anton4171afb2017-11-20 10:20:22 -08005364const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5365 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005366 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005367 const std::string sender_id) const {
5368 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005369 if (sender_info.stream_id == stream_id &&
5370 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005371 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005372 }
5373 }
5374 return nullptr;
5375}
5376
5377DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5378 for (const auto& channel : sctp_data_channels_) {
5379 if (channel->id() == sid) {
5380 return channel;
5381 }
5382 }
5383 return nullptr;
5384}
5385
Karl Wibergfb3be392019-03-22 14:13:22 +01005386PeerConnection::InitializePortAllocatorResult
5387PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005388 const cricket::ServerAddresses& stun_servers,
5389 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005390 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005391 RTC_DCHECK_RUN_ON(network_thread());
5392
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005393 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005394 // To handle both internal and externally created port allocator, we will
5395 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005396 int port_allocator_flags = port_allocator_->flags();
5397 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5398 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5399 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005400 // If the disable-IPv6 flag was specified, we'll not override it
5401 // by experiment.
5402 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005403 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005404 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5405 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005406 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005407 }
5408
zhihuangb09b3f92017-03-07 14:40:51 -08005409 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005410 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005411 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005412 }
5413
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005414 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005415 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005416 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005417 }
5418
honghaiz60347052016-05-31 18:29:12 -07005419 if (configuration.candidate_network_policy ==
5420 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005421 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005422 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005423 }
5424
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005425 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005426 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005427 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5428 }
5429
Karl Wibergfb3be392019-03-22 14:13:22 +01005430 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005431 // No step delay is used while allocating ports.
5432 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005433 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005434 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005435 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005436
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005437 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005438 for (auto& turn_server : turn_servers_copy) {
5439 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005440 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005441 // Call this last since it may create pooled allocator sessions using the
5442 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005443 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005444 stun_servers, std::move(turn_servers_copy),
5445 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5446 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005447 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005448
5449 InitializePortAllocatorResult res;
5450 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5451 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005452}
5453
deadbeef91dd5672016-05-18 16:55:30 -07005454bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005455 const cricket::ServerAddresses& stun_servers,
5456 const std::vector<cricket::RelayServerConfig>& turn_servers,
5457 IceTransportsType type,
5458 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005459 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005460 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005461 absl::optional<int> stun_candidate_keepalive_interval,
5462 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005463 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005464 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005465 // According to JSEP, after setLocalDescription, changing the candidate pool
5466 // size is not allowed, and changing the set of ICE servers will not result
5467 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005468 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005469 port_allocator_->FreezeCandidatePool();
5470 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005471 // Add the custom tls turn servers if they exist.
5472 auto turn_servers_copy = turn_servers;
5473 for (auto& turn_server : turn_servers_copy) {
5474 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5475 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005476 // Call this last since it may create pooled allocator sessions using the
5477 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005478 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005479 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5480 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005481}
5482
Steve Antonba818672017-11-06 10:21:57 -08005483cricket::ChannelManager* PeerConnection::channel_manager() const {
5484 return factory_->channel_manager();
5485}
5486
Elad Alon99c3fe52017-10-13 16:29:40 +02005487bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005488 std::unique_ptr<RtcEventLogOutput> output,
5489 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005490 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005491 if (!event_log_) {
5492 return false;
5493 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005494 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005495}
5496
5497void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005498 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005499 if (event_log_) {
5500 event_log_->StopLogging();
5501 }
ivoc14d5dbe2016-07-04 07:06:55 -07005502}
nisseeaabdf62017-05-05 02:23:02 -07005503
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005504cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005505 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005506 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005507 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005508 if (channel && channel->content_name() == content_name) {
5509 return channel;
5510 }
Steve Anton75737c02017-11-06 10:37:17 -08005511 }
5512 if (rtp_data_channel() &&
5513 rtp_data_channel()->content_name() == content_name) {
5514 return rtp_data_channel();
5515 }
5516 return nullptr;
5517}
5518
5519bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005520 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005521 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005522 RTC_LOG(LS_INFO)
5523 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005524 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005525 return false;
5526 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005527 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005528 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005529 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005530 return false;
5531 }
5532
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005533 absl::optional<rtc::SSLRole> dtls_role;
5534 if (sctp_mid_) {
5535 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5536 } else if (is_caller_) {
5537 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5538 }
Zhi Huange830e682018-03-30 10:48:35 -07005539 if (dtls_role) {
5540 *role = *dtls_role;
5541 return true;
5542 }
5543 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005544}
5545
5546bool PeerConnection::GetSslRole(const std::string& content_name,
5547 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005548 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005549 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005550 RTC_LOG(LS_INFO)
5551 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005552 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005553 return false;
5554 }
5555
Zhi Huange830e682018-03-30 10:48:35 -07005556 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5557 if (dtls_role) {
5558 *role = *dtls_role;
5559 return true;
5560 }
5561 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005562}
5563
Steve Antonf8470812017-12-04 10:46:21 -08005564void PeerConnection::SetSessionError(SessionError error,
5565 const std::string& error_desc) {
5566 RTC_DCHECK_RUN_ON(signaling_thread());
5567 if (error != session_error_) {
5568 session_error_ = error;
5569 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005570 }
5571}
5572
Zhi Huange830e682018-03-30 10:48:35 -07005573RTCError PeerConnection::UpdateSessionState(
5574 SdpType type,
5575 cricket::ContentSource source,
5576 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005577 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005578
5579 // If there's already a pending error then no state transition should happen.
5580 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005581 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005582
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005583 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005584 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005585 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005586 }
5587
5588 // Update the signaling state according to the specified state machine (see
5589 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005590 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005591 ChangeSignalingState(source == cricket::CS_LOCAL
5592 ? PeerConnectionInterface::kHaveLocalOffer
5593 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005594 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005595 ChangeSignalingState(source == cricket::CS_LOCAL
5596 ? PeerConnectionInterface::kHaveLocalPrAnswer
5597 : PeerConnectionInterface::kHaveRemotePrAnswer);
5598 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005599 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005600 ChangeSignalingState(PeerConnectionInterface::kStable);
5601 }
5602
5603 // Update internal objects according to the session description's media
5604 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005605 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005606 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005607 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005608 }
5609
Steve Anton8a006912017-12-04 15:25:56 -08005610 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005611}
5612
Steve Anton8a006912017-12-04 15:25:56 -08005613RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005614 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005615 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005616 const SessionDescriptionInterface* sdesc =
5617 (source == cricket::CS_LOCAL ? local_description()
5618 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005619 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005620
5621 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005622 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005623 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005624 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005625 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005626 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005627 continue;
5628 }
5629 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005630 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005631 if (!content_desc) {
5632 continue;
5633 }
5634 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005635 bool success = (source == cricket::CS_LOCAL)
5636 ? channel->SetLocalContent(content_desc, type, &error)
5637 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005638 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005639 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005640 }
5641 }
5642
5643 // If using the RtpDataChannel, push down the new SDP section for it too.
5644 if (rtp_data_channel_) {
5645 const ContentInfo* data_content =
5646 cricket::GetFirstDataContent(sdesc->description());
5647 if (data_content && !data_content->rejected) {
5648 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005649 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005650 if (data_desc) {
5651 std::string error;
5652 bool success =
5653 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005654 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005655 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005656 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005657 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005658 }
Steve Anton75737c02017-11-06 10:37:17 -08005659 }
5660 }
5661 }
Steve Antoned10bd92017-12-05 10:52:59 -08005662
Steve Anton75737c02017-11-06 10:37:17 -08005663 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5664 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5665 if (sctp_transport_ && local_description() && remote_description() &&
5666 cricket::GetFirstDataContent(local_description()->description()) &&
5667 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005668 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005669 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 11:37:28 +02005670 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5671 GetSctpPort(local_description()->description()),
5672 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 15:25:56 -08005673 if (!success) {
5674 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5675 "Failed to push down SCTP parameters.");
5676 }
Steve Anton75737c02017-11-06 10:37:17 -08005677 }
Steve Antoned10bd92017-12-05 10:52:59 -08005678
Steve Anton8a006912017-12-04 15:25:56 -08005679 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005680}
5681
Karl Wiberg739506e2019-04-03 11:37:28 +02005682bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5683 int local_sctp_port,
5684 int remote_sctp_port) {
5685 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005686 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5687 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 11:37:28 +02005688 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 10:37:17 -08005689}
5690
Steve Anton8a006912017-12-04 15:25:56 -08005691RTCError PeerConnection::PushdownTransportDescription(
5692 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005693 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005694 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005695
Zhi Huange830e682018-03-30 10:48:35 -07005696 if (source == cricket::CS_LOCAL) {
5697 const SessionDescriptionInterface* sdesc = local_description();
5698 RTC_DCHECK(sdesc);
5699 return transport_controller_->SetLocalDescription(type,
5700 sdesc->description());
5701 } else {
5702 const SessionDescriptionInterface* sdesc = remote_description();
5703 RTC_DCHECK(sdesc);
5704 return transport_controller_->SetRemoteDescription(type,
5705 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005706 }
Steve Anton75737c02017-11-06 10:37:17 -08005707}
5708
5709bool PeerConnection::GetTransportDescription(
5710 const SessionDescription* description,
5711 const std::string& content_name,
5712 cricket::TransportDescription* tdesc) {
5713 if (!description || !tdesc) {
5714 return false;
5715 }
5716 const TransportInfo* transport_info =
5717 description->GetTransportInfoByName(content_name);
5718 if (!transport_info) {
5719 return false;
5720 }
5721 *tdesc = transport_info->description;
5722 return true;
5723}
5724
Steve Anton75737c02017-11-06 10:37:17 -08005725cricket::IceConfig PeerConnection::ParseIceConfig(
5726 const PeerConnectionInterface::RTCConfiguration& config) const {
5727 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005728 switch (config.continual_gathering_policy) {
5729 case PeerConnectionInterface::GATHER_ONCE:
5730 gathering_policy = cricket::GATHER_ONCE;
5731 break;
5732 case PeerConnectionInterface::GATHER_CONTINUALLY:
5733 gathering_policy = cricket::GATHER_CONTINUALLY;
5734 break;
5735 default:
5736 RTC_NOTREACHED();
5737 gathering_policy = cricket::GATHER_ONCE;
5738 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005739
Steve Anton75737c02017-11-06 10:37:17 -08005740 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005741 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5742 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005743 ice_config.prioritize_most_likely_candidate_pairs =
5744 config.prioritize_most_likely_ice_candidate_pairs;
5745 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005746 RTCConfigurationToIceConfigOptionalInt(
5747 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005748 ice_config.continual_gathering_policy = gathering_policy;
5749 ice_config.presume_writable_when_fully_relayed =
5750 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005751 ice_config.ice_check_interval_strong_connectivity =
5752 config.ice_check_interval_strong_connectivity;
5753 ice_config.ice_check_interval_weak_connectivity =
5754 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005755 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005756 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5757 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005758 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005759 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005760 ice_config.regather_all_networks_interval_range =
5761 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005762 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005763 return ice_config;
5764}
5765
Steve Anton75737c02017-11-06 10:37:17 -08005766bool PeerConnection::SendData(const cricket::SendDataParams& params,
5767 const rtc::CopyOnWriteBuffer& payload,
5768 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005769 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005770 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5771 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5772 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005773 return false;
5774 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005775 if (media_transport_) {
5776 SendDataParams send_params;
5777 send_params.type = ToWebrtcDataMessageType(params.type);
5778 send_params.ordered = params.ordered;
5779 if (params.max_rtx_count >= 0) {
5780 send_params.max_rtx_count = params.max_rtx_count;
5781 } else if (params.max_rtx_ms >= 0) {
5782 send_params.max_rtx_ms = params.max_rtx_ms;
5783 }
5784 return media_transport_->SendData(params.sid, send_params, payload).ok();
5785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 return rtp_data_channel_
5787 ? rtp_data_channel_->SendData(params, payload, result)
5788 : network_thread()->Invoke<bool>(
5789 RTC_FROM_HERE,
5790 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005791 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005792}
5793
5794bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005795 RTC_DCHECK_RUN_ON(signaling_thread());
5796 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005797 // Don't log an error here, because DataChannels are expected to call
5798 // ConnectDataChannel in this state. It's the only way to initially tell
5799 // whether or not the underlying transport is ready.
5800 return false;
5801 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005802 if (media_transport_) {
5803 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5804 &DataChannel::OnChannelReady);
5805 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5806 &DataChannel::OnDataReceived);
5807 SignalMediaTransportChannelClosing_s.connect(
5808 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5809 SignalMediaTransportChannelClosed_s.connect(
5810 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5811 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005812 rtp_data_channel_->SignalReadyToSendData.connect(
5813 webrtc_data_channel, &DataChannel::OnChannelReady);
5814 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5815 &DataChannel::OnDataReceived);
5816 } else {
5817 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5818 &DataChannel::OnChannelReady);
5819 SignalSctpDataReceived.connect(webrtc_data_channel,
5820 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005821 SignalSctpClosingProcedureStartedRemotely.connect(
5822 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5823 SignalSctpClosingProcedureComplete.connect(
5824 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005825 }
5826 return true;
5827}
5828
5829void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005830 RTC_DCHECK_RUN_ON(signaling_thread());
5831 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005832 RTC_LOG(LS_ERROR)
5833 << "DisconnectDataChannel called when rtp_data_channel_ and "
5834 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005835 return;
5836 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005837 if (media_transport_) {
5838 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5839 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5840 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5841 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5842 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005843 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5844 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5845 } else {
5846 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5847 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005848 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5849 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005850 }
5851}
5852
5853void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005854 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005855 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005856 return;
5857 }
Steve Anton75737c02017-11-06 10:37:17 -08005858 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005859 RTC_LOG(LS_ERROR)
5860 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005861 return;
5862 }
5863 network_thread()->Invoke<void>(
5864 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005865 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005866}
5867
5868void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005869 if (media_transport_) {
5870 media_transport_->CloseChannel(sid);
5871 return;
5872 }
Steve Anton75737c02017-11-06 10:37:17 -08005873 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005874 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005875 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005876 return;
5877 }
5878 network_thread()->Invoke<void>(
5879 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005880 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005881}
5882
5883bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005884 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005885 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005886 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005887 sctp_ready_to_send_data_;
5888}
5889
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005890void PeerConnection::OnDataReceived(int channel_id,
5891 DataMessageType type,
5892 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005893 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005894 cricket::ReceiveDataParams params;
5895 params.sid = channel_id;
5896 params.type = ToCricketDataMessageType(type);
5897 media_transport_invoker_->AsyncInvoke<void>(
5898 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5899 RTC_DCHECK_RUN_ON(signaling_thread());
5900 if (!HandleOpenMessage_s(params, buffer)) {
5901 SignalMediaTransportReceivedData_s(params, buffer);
5902 }
5903 });
5904}
5905
5906void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005907 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005908 media_transport_invoker_->AsyncInvoke<void>(
5909 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5910 RTC_DCHECK_RUN_ON(signaling_thread());
5911 SignalMediaTransportChannelClosing_s(channel_id);
5912 });
5913}
5914
5915void PeerConnection::OnChannelClosed(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 SignalMediaTransportChannelClosed_s(channel_id);
5921 });
5922}
5923
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005924absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005925 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005926 if (sctp_mid_ && transport_controller_) {
5927 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5928 if (dtls_transport) {
5929 return dtls_transport->transport_name();
5930 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005931 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005932 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005933 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005934}
5935
Qingsi Wang72a43a12018-02-20 16:03:18 -08005936cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5937 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005938 network_thread()->Invoke<void>(
5939 RTC_FROM_HERE,
5940 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5941 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005942 return candidate_states_list;
5943}
5944
Steve Anton5dfde182018-02-06 10:34:40 -08005945std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5946 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005947 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005948 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005949 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005950 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005951 if (channel) {
5952 transport_names_by_mid[channel->content_name()] =
5953 channel->transport_name();
5954 }
Steve Anton75737c02017-11-06 10:37:17 -08005955 }
Steve Anton5dfde182018-02-06 10:34:40 -08005956 if (rtp_data_channel_) {
5957 transport_names_by_mid[rtp_data_channel_->content_name()] =
5958 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005959 }
5960 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005961 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005962 RTC_DCHECK(transport_name);
5963 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005964 }
Steve Anton5dfde182018-02-06 10:34:40 -08005965 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005966}
5967
Steve Anton5dfde182018-02-06 10:34:40 -08005968std::map<std::string, cricket::TransportStats>
5969PeerConnection::GetTransportStatsByNames(
5970 const std::set<std::string>& transport_names) {
5971 if (!network_thread()->IsCurrent()) {
5972 return network_thread()
5973 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5974 RTC_FROM_HERE,
5975 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005976 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005977 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005978 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5979 for (const std::string& transport_name : transport_names) {
5980 cricket::TransportStats transport_stats;
5981 bool success =
5982 transport_controller_->GetStats(transport_name, &transport_stats);
5983 if (success) {
5984 transport_stats_by_name[transport_name] = std::move(transport_stats);
5985 } else {
5986 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5987 << transport_name;
5988 }
5989 }
5990 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005991}
5992
5993bool PeerConnection::GetLocalCertificate(
5994 const std::string& transport_name,
5995 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005996 if (!certificate) {
5997 return false;
5998 }
5999 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6000 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006001}
6002
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006003std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006004 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006005 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006006}
6007
6008cricket::DataChannelType PeerConnection::data_channel_type() const {
6009 return data_channel_type_;
6010}
6011
6012bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006013 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006014 return pending_ice_restarts_.find(content_name) !=
6015 pending_ice_restarts_.end();
6016}
6017
Steve Anton75737c02017-11-06 10:37:17 -08006018bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6019 return transport_controller_->NeedsIceRestart(content_name);
6020}
6021
6022void PeerConnection::OnCertificateReady(
6023 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6024 transport_controller_->SetLocalCertificate(certificate);
6025}
6026
6027void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006028 SetSessionError(SessionError::kTransport,
6029 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006030}
6031
Alex Loiko9289eda2018-11-23 16:18:59 +00006032void PeerConnection::OnTransportControllerConnectionState(
6033 cricket::IceConnectionState state) {
6034 switch (state) {
6035 case cricket::kIceConnectionConnecting:
6036 // If the current state is Connected or Completed, then there were
6037 // writable channels but now there are not, so the next state must
6038 // be Disconnected.
6039 // kIceConnectionConnecting is currently used as the default,
6040 // un-connected state by the TransportController, so its only use is
6041 // detecting disconnections.
6042 if (ice_connection_state_ ==
6043 PeerConnectionInterface::kIceConnectionConnected ||
6044 ice_connection_state_ ==
6045 PeerConnectionInterface::kIceConnectionCompleted) {
6046 SetIceConnectionState(
6047 PeerConnectionInterface::kIceConnectionDisconnected);
6048 }
6049 break;
6050 case cricket::kIceConnectionFailed:
6051 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6052 break;
6053 case cricket::kIceConnectionConnected:
6054 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6055 "all transports are writable.";
6056 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6057 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6058 break;
6059 case cricket::kIceConnectionCompleted:
6060 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6061 "all transports are complete.";
6062 if (ice_connection_state_ !=
6063 PeerConnectionInterface::kIceConnectionConnected) {
6064 // If jumping directly from "checking" to "connected",
6065 // signal "connected" first.
6066 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6067 }
6068 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6069 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6070 ReportTransportStats();
6071 break;
6072 default:
6073 RTC_NOTREACHED();
6074 }
6075}
6076
Steve Anton75737c02017-11-06 10:37:17 -08006077void PeerConnection::OnTransportControllerCandidatesGathered(
6078 const std::string& transport_name,
6079 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006080 int sdp_mline_index;
6081 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006082 RTC_LOG(LS_ERROR)
6083 << "OnTransportControllerCandidatesGathered: content name "
6084 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006085 return;
6086 }
6087
6088 for (cricket::Candidates::const_iterator citer = candidates.begin();
6089 citer != candidates.end(); ++citer) {
6090 // Use transport_name as the candidate media id.
6091 std::unique_ptr<JsepIceCandidate> candidate(
6092 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6093 if (local_description()) {
6094 mutable_local_description()->AddCandidate(candidate.get());
6095 }
6096 OnIceCandidate(std::move(candidate));
6097 }
6098}
6099
6100void PeerConnection::OnTransportControllerCandidatesRemoved(
6101 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006102 // Sanity check.
6103 for (const cricket::Candidate& candidate : candidates) {
6104 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006105 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006106 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006107 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006108 return;
6109 }
6110 }
6111
6112 if (local_description()) {
6113 mutable_local_description()->RemoveCandidates(candidates);
6114 }
6115 OnIceCandidatesRemoved(candidates);
6116}
6117
6118void PeerConnection::OnTransportControllerDtlsHandshakeError(
6119 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006120 RTC_HISTOGRAM_ENUMERATION(
6121 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6122 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006123}
6124
Steve Antoned10bd92017-12-05 10:52:59 -08006125void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006126 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006127 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006128 if (channel && !channel->enabled()) {
6129 channel->Enable(true);
6130 }
Steve Anton75737c02017-11-06 10:37:17 -08006131 }
6132
Steve Anton4171afb2017-11-20 10:20:22 -08006133 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006134 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006135 }
Steve Anton75737c02017-11-06 10:37:17 -08006136}
6137
6138// Returns the media index for a local ice candidate given the content name.
6139bool PeerConnection::GetLocalCandidateMediaIndex(
6140 const std::string& content_name,
6141 int* sdp_mline_index) {
6142 if (!local_description() || !sdp_mline_index) {
6143 return false;
6144 }
6145
6146 bool content_found = false;
6147 const ContentInfos& contents = local_description()->description()->contents();
6148 for (size_t index = 0; index < contents.size(); ++index) {
6149 if (contents[index].name == content_name) {
6150 *sdp_mline_index = static_cast<int>(index);
6151 content_found = true;
6152 break;
6153 }
6154 }
6155 return content_found;
6156}
6157
6158bool PeerConnection::UseCandidatesInSessionDescription(
6159 const SessionDescriptionInterface* remote_desc) {
6160 if (!remote_desc) {
6161 return true;
6162 }
6163 bool ret = true;
6164
6165 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6166 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6167 for (size_t n = 0; n < candidates->count(); ++n) {
6168 const IceCandidateInterface* candidate = candidates->at(n);
6169 bool valid = false;
6170 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6171 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006172 RTC_LOG(LS_INFO)
6173 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006174 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006175 }
6176 continue;
6177 }
6178 ret = UseCandidate(candidate);
6179 if (!ret) {
6180 break;
6181 }
6182 }
6183 }
6184 return ret;
6185}
6186
6187bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6188 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6189 size_t remote_content_size =
6190 remote_description()->description()->contents().size();
6191 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006192 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006193 return false;
6194 }
6195
6196 cricket::ContentInfo content =
6197 remote_description()->description()->contents()[mediacontent_index];
6198 std::vector<cricket::Candidate> candidates;
6199 candidates.push_back(candidate->candidate());
6200 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006201 RTCError error =
6202 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006203 if (error.ok()) {
6204 // Candidates successfully submitted for checking.
6205 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6206 ice_connection_state_ ==
6207 PeerConnectionInterface::kIceConnectionDisconnected) {
6208 // If state is New, then the session has just gotten its first remote ICE
6209 // candidates, so go to Checking.
6210 // If state is Disconnected, the session is re-using old candidates or
6211 // receiving additional ones, so go to Checking.
6212 // If state is Connected, stay Connected.
6213 // TODO(bemasc): If state is Connected, and the new candidates are for a
6214 // newly added transport, then the state actually _should_ move to
6215 // checking. Add a way to distinguish that case.
6216 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6217 }
6218 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006219 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006220 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006221 }
6222 return true;
6223}
6224
6225void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006226 // Destroy video channel first since it may have a pointer to the
6227 // voice channel.
6228 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006229 if (!video_info || video_info->rejected) {
6230 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006231 }
6232
Steve Anton6fec8802017-12-04 10:37:29 -08006233 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6234 if (!audio_info || audio_info->rejected) {
6235 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006236 }
6237
6238 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6239 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006240 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006241 }
6242}
6243
Steve Antondcc3c022017-12-22 16:02:54 -08006244RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6245 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006246 const cricket::ContentGroup* bundle_group = nullptr;
6247 if (configuration_.bundle_policy ==
6248 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006249 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006250 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6252 "max-bundle configured but session description "
6253 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006254 }
6255 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006256 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006257}
6258
6259RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006260 // Creating the media channels. Transports should already have been created
6261 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006262 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006263 if (voice && !voice->rejected &&
6264 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006265 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006266 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006267 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6268 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006269 }
6270 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6271 }
6272
Steve Antondcc3c022017-12-22 16:02:54 -08006273 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006274 if (video && !video->rejected &&
6275 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006276 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006277 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006278 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6279 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006280 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006281 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006282 }
6283
Steve Antondcc3c022017-12-22 16:02:54 -08006284 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006285 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006286 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006287 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006288 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6289 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006290 }
6291 }
6292
Steve Anton8a006912017-12-04 15:25:56 -08006293 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006294}
6295
Steve Anton4171afb2017-11-20 10:20:22 -08006296// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006297cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006298 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006299 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006300 MediaTransportInterface* media_transport = nullptr;
6301 if (configuration_.use_media_transport) {
6302 media_transport = GetMediaTransport(mid);
6303 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006304
Steve Anton75737c02017-11-06 10:37:17 -08006305 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006306 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006307 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006308 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006309 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006310 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006311 }
Steve Anton75737c02017-11-06 10:37:17 -08006312 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6313 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006314 voice_channel->SignalSentPacket.connect(this,
6315 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006316 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006317
Steve Antoneda6ccd2017-12-04 10:21:55 -08006318 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006319}
6320
Steve Anton4171afb2017-11-20 10:20:22 -08006321// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006322cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006323 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006324 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006325 MediaTransportInterface* media_transport = nullptr;
6326 if (configuration_.use_media_transport) {
6327 media_transport = GetMediaTransport(mid);
6328 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006329
Steve Anton75737c02017-11-06 10:37:17 -08006330 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006331 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006332 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02006333 &ssrc_generator_, video_options_, video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006334 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006335 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006336 }
Steve Anton75737c02017-11-06 10:37:17 -08006337 video_channel->SignalDtlsSrtpSetupFailure.connect(
6338 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006339 video_channel->SignalSentPacket.connect(this,
6340 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006341 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006342
Steve Antoneda6ccd2017-12-04 10:21:55 -08006343 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006344}
6345
Zhi Huange830e682018-03-30 10:48:35 -07006346bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006347 switch (data_channel_type_) {
6348 case cricket::DCT_MEDIA_TRANSPORT:
6349 if (network_thread()->Invoke<bool>(
6350 RTC_FROM_HERE,
6351 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6352 this, mid))) {
6353 for (const auto& channel : sctp_data_channels_) {
6354 channel->OnTransportChannelCreated();
6355 }
6356 return true;
6357 }
Steve Anton75737c02017-11-06 10:37:17 -08006358 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006359 case cricket::DCT_SCTP:
6360 if (!sctp_factory_) {
6361 RTC_LOG(LS_ERROR)
6362 << "Trying to create SCTP transport, but didn't compile with "
6363 "SCTP support (HAVE_SCTP)";
6364 return false;
6365 }
6366 if (!network_thread()->Invoke<bool>(
6367 RTC_FROM_HERE,
6368 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6369 return false;
6370 }
6371 for (const auto& channel : sctp_data_channels_) {
6372 channel->OnTransportChannelCreated();
6373 }
6374 return true;
6375 case cricket::DCT_RTP:
6376 default:
6377 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6378 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6379 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006380 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006381 if (!rtp_data_channel_) {
6382 return false;
6383 }
6384 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6385 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6386 rtp_data_channel_->SignalSentPacket.connect(
6387 this, &PeerConnection::OnSentPacket_w);
6388 rtp_data_channel_->SetRtpTransport(rtp_transport);
6389 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006390 }
6391
Steve Anton75737c02017-11-06 10:37:17 -08006392 return true;
6393}
6394
6395Call::Stats PeerConnection::GetCallStats() {
6396 if (!worker_thread()->IsCurrent()) {
6397 return worker_thread()->Invoke<Call::Stats>(
6398 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6399 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006400 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006401 if (call_) {
6402 return call_->GetStats();
6403 } else {
6404 return Call::Stats();
6405 }
6406}
6407
Zhi Huange830e682018-03-30 10:48:35 -07006408bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006409 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006410 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006411 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6412 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006413 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006414 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006415 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006416 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6417 sctp_factory_->CreateSctpTransport(dtls_transport);
6418 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006419 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006420 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006421 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006422 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006423 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006424 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6425 // another thread. Would be nice if there was a helper class similar to
6426 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6427 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006428 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006429 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006430 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006431 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006432 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006433 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6434 std::move(cricket_sctp_transport));
6435 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006436 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006437}
6438
6439void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006440 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006441 sctp_transport_->Clear();
6442 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006443 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006444 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006445}
6446
6447void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006448 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006449 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006450 // Note: Cannot use rtc::Bind here because it will grab a reference to
6451 // PeerConnection and potentially cause PeerConnection to live longer than
6452 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6453 // be destroyed before PeerConnection is destroyed, and at that point all
6454 // pending tasks will be cleared.
6455 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6456 OnSctpTransportReadyToSendData_s(true);
6457 });
6458}
6459
6460void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006461 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006462 sctp_ready_to_send_data_ = ready;
6463 SignalSctpReadyToSendData(ready);
6464}
6465
6466void PeerConnection::OnSctpTransportDataReceived_n(
6467 const cricket::ReceiveDataParams& params,
6468 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006469 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006470 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006471 // Note: Cannot use rtc::Bind here because it will grab a reference to
6472 // PeerConnection and potentially cause PeerConnection to live longer than
6473 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6474 // be destroyed before PeerConnection is destroyed, and at that point all
6475 // pending tasks will be cleared.
6476 sctp_invoker_->AsyncInvoke<void>(
6477 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6478 OnSctpTransportDataReceived_s(params, payload);
6479 });
6480}
6481
6482void PeerConnection::OnSctpTransportDataReceived_s(
6483 const cricket::ReceiveDataParams& params,
6484 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006485 RTC_DCHECK_RUN_ON(signaling_thread());
6486 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006487 SignalSctpDataReceived(params, payload);
6488 }
6489}
6490
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006491void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006492 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006493 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006494 sctp_invoker_->AsyncInvoke<void>(
6495 RTC_FROM_HERE, signaling_thread(),
6496 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006497 &SignalSctpClosingProcedureStartedRemotely, sid));
6498}
6499
6500void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006501 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006502 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006503 sctp_invoker_->AsyncInvoke<void>(
6504 RTC_FROM_HERE, signaling_thread(),
6505 rtc::Bind(&sigslot::signal1<int>::operator(),
6506 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006507}
6508
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006509bool PeerConnection::SetupMediaTransportForDataChannels_n(
6510 const std::string& mid) {
6511 media_transport_ = transport_controller_->GetMediaTransport(mid);
6512 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006513 RTC_LOG(LS_ERROR)
6514 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006515 return false;
6516 }
6517
6518 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6519 media_transport_->SetDataSink(this);
6520 media_transport_data_mid_ = mid;
6521 transport_controller_->SignalMediaTransportStateChanged.connect(
6522 this, &PeerConnection::OnMediaTransportStateChanged_n);
6523 // Check the initial state right away, in case transport is already writable.
6524 OnMediaTransportStateChanged_n();
6525 return true;
6526}
6527
6528void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6529 if (!media_transport_) {
6530 return;
6531 }
6532 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6533 media_transport_data_mid_.reset();
6534 media_transport_->SetDataSink(nullptr);
6535 media_transport_invoker_ = nullptr;
6536 media_transport_ = nullptr;
6537}
6538
6539void PeerConnection::OnMediaTransportStateChanged_n() {
6540 if (!media_transport_data_mid_ ||
6541 transport_controller_->GetMediaTransportState(
6542 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6543 return;
6544 }
6545 media_transport_invoker_->AsyncInvoke<void>(
6546 RTC_FROM_HERE, signaling_thread(), [this] {
6547 RTC_DCHECK_RUN_ON(signaling_thread());
6548 media_transport_ready_to_send_data_ = true;
6549 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6550 });
6551}
6552
Steve Anton75737c02017-11-06 10:37:17 -08006553// Returns false if bundle is enabled and rtcp_mux is disabled.
6554bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6555 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6556 if (!bundle_enabled)
6557 return true;
6558
6559 const cricket::ContentGroup* bundle_group =
6560 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6561 RTC_DCHECK(bundle_group != NULL);
6562
6563 const cricket::ContentInfos& contents = desc->contents();
6564 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6565 citer != contents.end(); ++citer) {
6566 const cricket::ContentInfo* content = (&*citer);
6567 RTC_DCHECK(content != NULL);
6568 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006569 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006570 if (!HasRtcpMuxEnabled(content))
6571 return false;
6572 }
6573 }
6574 // RTCP-MUX is enabled in all the contents.
6575 return true;
6576}
6577
6578bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006579 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006580}
6581
Steve Anton06817cd2018-12-18 15:55:30 -08006582static RTCError ValidateMids(const cricket::SessionDescription& description) {
6583 std::set<std::string> mids;
6584 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006585 if (content.name.empty()) {
6586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6587 "A media section is missing a MID attribute.");
6588 }
Steve Anton06817cd2018-12-18 15:55:30 -08006589 if (!mids.insert(content.name).second) {
6590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6591 "Duplicate a=mid value '" + content.name + "'.");
6592 }
6593 }
6594 return RTCError::OK();
6595}
6596
Steve Anton8a006912017-12-04 15:25:56 -08006597RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006598 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006599 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006600 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006601 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603
6604 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006606 }
6607
Steve Anton3828c062017-12-06 10:34:51 -08006608 SdpType type = sdesc->GetType();
6609 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6610 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006611 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006612 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006613 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006614 }
6615
Steve Anton06817cd2018-12-18 15:55:30 -08006616 RTCError error = ValidateMids(*sdesc->description());
6617 if (!error.ok()) {
6618 return error;
6619 }
6620
Steve Anton75737c02017-11-06 10:37:17 -08006621 // Verify crypto settings.
6622 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006623 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6624 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006625 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006626 if (!crypto_error.ok()) {
6627 return crypto_error;
6628 }
Steve Anton75737c02017-11-06 10:37:17 -08006629 }
6630
6631 // Verify ice-ufrag and ice-pwd.
6632 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006633 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6634 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006635 }
6636
6637 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006638 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6639 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006640 }
6641
6642 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6643 // m-lines that do not rtcp-mux enabled.
6644
6645 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006646 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006647 // With an answer we want to compare the new answer session description with
6648 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006649 const cricket::SessionDescription* offer_desc =
6650 (source == cricket::CS_LOCAL) ? remote_description()->description()
6651 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006652 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6653 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6654 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6656 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006657 }
6658 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006659 // The re-offers should respect the order of m= sections in current
6660 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006661 // With a re-offer, either the current local or current remote descriptions
6662 // could be the most up to date, so we would like to check against both of
6663 // them if they exist. It could be the case that one of them has a 0 port
6664 // for a media section, but the other does not. This is important to check
6665 // against in the case that we are recycling an m= section.
6666 const cricket::SessionDescription* current_desc = nullptr;
6667 const cricket::SessionDescription* secondary_current_desc = nullptr;
6668 if (local_description()) {
6669 current_desc = local_description()->description();
6670 if (remote_description()) {
6671 secondary_current_desc = remote_description()->description();
6672 }
6673 } else if (remote_description()) {
6674 current_desc = remote_description()->description();
6675 }
Steve Anton75737c02017-11-06 10:37:17 -08006676 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006677 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6678 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006679 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6680 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006681 }
6682 }
6683
Steve Antonba42e992018-04-09 14:10:01 -07006684 if (IsUnifiedPlan()) {
6685 // Ensure that each audio and video media section has at most one
6686 // "StreamParams". This will return an error if receiving a session
6687 // description from a "Plan B" endpoint which adds multiple tracks of the
6688 // same type. With Unified Plan, there can only be at most one track per
6689 // media section.
6690 for (const ContentInfo& content : sdesc->description()->contents()) {
6691 const MediaContentDescription& desc = *content.description;
6692 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6693 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6694 desc.streams().size() > 1u) {
6695 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6696 "Media section has more than one track specified "
6697 "with a=ssrc lines which is not supported with "
6698 "Unified Plan.");
6699 }
6700 }
6701 }
6702
Steve Anton8a006912017-12-04 15:25:56 -08006703 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006704}
6705
Steve Anton3828c062017-12-06 10:34:51 -08006706bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006707 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006708 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006709 return (state == PeerConnectionInterface::kStable) ||
6710 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006711 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006712 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006713 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6714 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6715 }
6716}
6717
Steve Anton3828c062017-12-06 10:34:51 -08006718bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006719 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006720 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006721 return (state == PeerConnectionInterface::kStable) ||
6722 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006723 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006724 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006725 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6726 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6727 }
6728}
6729
Steve Antonf8470812017-12-04 10:46:21 -08006730const char* PeerConnection::SessionErrorToString(SessionError error) const {
6731 switch (error) {
6732 case SessionError::kNone:
6733 return "ERROR_NONE";
6734 case SessionError::kContent:
6735 return "ERROR_CONTENT";
6736 case SessionError::kTransport:
6737 return "ERROR_TRANSPORT";
6738 }
6739 RTC_NOTREACHED();
6740 return "";
6741}
6742
Steve Anton75737c02017-11-06 10:37:17 -08006743std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006744 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006745 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6746 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006747 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006748}
6749
Steve Anton8e20f172018-03-06 10:55:04 -08006750void PeerConnection::ReportSdpFormatReceived(
6751 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006752 int num_audio_mlines = 0;
6753 int num_video_mlines = 0;
6754 int num_audio_tracks = 0;
6755 int num_video_tracks = 0;
6756 for (const ContentInfo& content : remote_offer.description()->contents()) {
6757 cricket::MediaType media_type = content.media_description()->type();
6758 int num_tracks = std::max(
6759 1, static_cast<int>(content.media_description()->streams().size()));
6760 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6761 num_audio_mlines += 1;
6762 num_audio_tracks += num_tracks;
6763 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6764 num_video_mlines += 1;
6765 num_video_tracks += num_tracks;
6766 }
6767 }
6768 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6769 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6770 format = kSdpFormatReceivedComplexUnifiedPlan;
6771 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6772 format = kSdpFormatReceivedComplexPlanB;
6773 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6774 format = kSdpFormatReceivedSimple;
6775 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006776 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6777 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006778}
6779
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006780void PeerConnection::NoteUsageEvent(UsageEvent event) {
6781 RTC_DCHECK_RUN_ON(signaling_thread());
6782 usage_event_accumulator_ |= static_cast<int>(event);
6783}
6784
6785void PeerConnection::ReportUsagePattern() const {
6786 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006787 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6788 usage_event_accumulator_,
6789 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006790 const int bad_bits =
6791 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6792 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6793 const int good_bits =
6794 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6795 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6796 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6797 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6798 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006799 // If called after close(), we can't report, because observer may have
6800 // been deallocated, and therefore pointer is null. Write to log instead.
6801 if (observer_) {
6802 Observer()->OnInterestingUsage(usage_event_accumulator_);
6803 } else {
6804 RTC_LOG(LS_INFO) << "Interesting usage signature "
6805 << usage_event_accumulator_
6806 << " observed after observer shutdown";
6807 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006808 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006809}
6810
Steve Anton0ffaaa22018-02-23 10:31:30 -08006811void PeerConnection::ReportNegotiatedSdpSemantics(
6812 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006813 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006814 switch (answer.description()->msid_signaling()) {
6815 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006816 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006817 break;
6818 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006819 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006820 break;
6821 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006822 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006823 break;
6824 case cricket::kMsidSignalingMediaSection |
6825 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006826 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006827 break;
6828 default:
6829 RTC_NOTREACHED();
6830 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006831 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6832 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006833}
6834
Steve Anton75737c02017-11-06 10:37:17 -08006835// We need to check the local/remote description for the Transport instead of
6836// the session, because a new Transport added during renegotiation may have
6837// them unset while the session has them set from the previous negotiation.
6838// Not doing so may trigger the auto generation of transport description and
6839// mess up DTLS identity information, ICE credential, etc.
6840bool PeerConnection::ReadyToUseRemoteCandidate(
6841 const IceCandidateInterface* candidate,
6842 const SessionDescriptionInterface* remote_desc,
6843 bool* valid) {
6844 *valid = true;
6845
6846 const SessionDescriptionInterface* current_remote_desc =
6847 remote_desc ? remote_desc : remote_description();
6848
6849 if (!current_remote_desc) {
6850 return false;
6851 }
6852
6853 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6854 size_t remote_content_size =
6855 current_remote_desc->description()->contents().size();
6856 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006857 RTC_LOG(LS_ERROR)
6858 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6859 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006860
6861 *valid = false;
6862 return false;
6863 }
6864
6865 cricket::ContentInfo content =
6866 current_remote_desc->description()->contents()[mediacontent_index];
6867
6868 const std::string transport_name = GetTransportName(content.name);
6869 if (transport_name.empty()) {
6870 return false;
6871 }
Zhi Huange830e682018-03-30 10:48:35 -07006872 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006873}
6874
6875bool PeerConnection::SrtpRequired() const {
6876 return dtls_enabled_ ||
6877 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6878}
6879
6880void PeerConnection::OnTransportControllerGatheringState(
6881 cricket::IceGatheringState state) {
6882 RTC_DCHECK(signaling_thread()->IsCurrent());
6883 if (state == cricket::kIceGatheringGathering) {
6884 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6885 } else if (state == cricket::kIceGatheringComplete) {
6886 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6887 }
6888}
6889
6890void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006891 std::map<std::string, std::set<cricket::MediaType>>
6892 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006893 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006894 if (transceiver->internal()->channel()) {
6895 const std::string& transport_name =
6896 transceiver->internal()->channel()->transport_name();
6897 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006898 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006899 }
Steve Anton75737c02017-11-06 10:37:17 -08006900 }
6901 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006902 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6903 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006904 }
Zhi Huange830e682018-03-30 10:48:35 -07006905
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006906 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006907 if (transport_name) {
6908 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006909 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006910 }
Zhi Huange830e682018-03-30 10:48:35 -07006911
Steve Antonc7b964c2018-02-01 14:39:45 -08006912 for (const auto& entry : media_types_by_transport_name) {
6913 const std::string& transport_name = entry.first;
6914 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006915 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006916 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006917 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006918 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006919 }
6920 }
6921}
6922// Walk through the ConnectionInfos to gather best connection usage
6923// for IPv4 and IPv6.
6924void PeerConnection::ReportBestConnectionState(
6925 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006926 for (const cricket::TransportChannelStats& channel_stats :
6927 stats.channel_stats) {
6928 for (const cricket::ConnectionInfo& connection_info :
6929 channel_stats.connection_infos) {
6930 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006931 continue;
6932 }
6933
Steve Antonc7b964c2018-02-01 14:39:45 -08006934 const cricket::Candidate& local = connection_info.local_candidate;
6935 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006936
6937 // Increment the counter for IceCandidatePairType.
6938 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6939 (local.type() == RELAY_PORT_TYPE &&
6940 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006941 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6942 GetIceCandidatePairCounter(local, remote),
6943 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006944 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006945 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6946 GetIceCandidatePairCounter(local, remote),
6947 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006948 } else {
6949 RTC_CHECK(0);
6950 }
Steve Anton75737c02017-11-06 10:37:17 -08006951
6952 // Increment the counter for IP type.
6953 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006954 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6955 kBestConnections_IPv4,
6956 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006957 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006958 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6959 kBestConnections_IPv6,
6960 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006961 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006962 RTC_CHECK(!local.address().hostname().empty() &&
6963 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006964 }
6965
6966 return;
6967 }
6968 }
6969}
6970
6971void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006972 const cricket::TransportStats& stats,
6973 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006974 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6975 return;
6976 }
6977
6978 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6979 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6980 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6981 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6982 return;
6983 }
6984
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006985 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6986 for (cricket::MediaType media_type : media_types) {
6987 switch (media_type) {
6988 case cricket::MEDIA_TYPE_AUDIO:
6989 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6990 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6991 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6992 break;
6993 case cricket::MEDIA_TYPE_VIDEO:
6994 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6995 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6996 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6997 break;
6998 case cricket::MEDIA_TYPE_DATA:
6999 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7000 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7001 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7002 break;
7003 default:
7004 RTC_NOTREACHED();
7005 continue;
7006 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007007 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007008 }
7009
7010 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7011 for (cricket::MediaType media_type : media_types) {
7012 switch (media_type) {
7013 case cricket::MEDIA_TYPE_AUDIO:
7014 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7015 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7016 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7017 break;
7018 case cricket::MEDIA_TYPE_VIDEO:
7019 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7020 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7021 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7022 break;
7023 case cricket::MEDIA_TYPE_DATA:
7024 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7025 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7026 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7027 break;
7028 default:
7029 RTC_NOTREACHED();
7030 continue;
7031 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007032 }
Steve Anton75737c02017-11-06 10:37:17 -08007033 }
7034}
7035
7036void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007037 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007038 RTC_DCHECK(call_);
7039 call_->OnSentPacket(sent_packet);
7040}
7041
7042const std::string PeerConnection::GetTransportName(
7043 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007044 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007045 if (channel) {
7046 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007047 }
Steve Anton6fec8802017-12-04 10:37:29 -08007048 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007049 RTC_DCHECK(sctp_mid_);
7050 if (content_name == *sctp_mid_) {
7051 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007052 }
7053 }
7054 // Return an empty string if failed to retrieve the transport name.
7055 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007056}
7057
Steve Anton6fec8802017-12-04 10:37:29 -08007058void PeerConnection::DestroyTransceiverChannel(
7059 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7060 transceiver) {
7061 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007062
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007063 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007064 if (channel) {
7065 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007066 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007067 }
7068}
7069
7070void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007071 if (rtp_data_channel_) {
7072 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007073 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007074 rtp_data_channel_ = nullptr;
7075 }
7076
7077 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7078 // grab a reference to this PeerConnection. If this is called from the
7079 // PeerConnection destructor, the RefCountedObject vtable will have already
7080 // been destroyed (since it is a subclass of PeerConnection) and using
7081 // rtc::Bind will cause "Pure virtual function called" error to appear.
7082
7083 if (sctp_transport_) {
7084 OnDataChannelDestroyed();
7085 network_thread()->Invoke<void>(RTC_FROM_HERE,
7086 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007087 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007088 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007089
7090 if (media_transport_) {
7091 OnDataChannelDestroyed();
7092 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7093 RTC_DCHECK_RUN_ON(network_thread());
7094 TeardownMediaTransportForDataChannels_n();
7095 });
7096 }
Steve Anton6fec8802017-12-04 10:37:29 -08007097}
7098
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007099void PeerConnection::DestroyChannelInterface(
7100 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007101 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007102 switch (channel->media_type()) {
7103 case cricket::MEDIA_TYPE_AUDIO:
7104 channel_manager()->DestroyVoiceChannel(
7105 static_cast<cricket::VoiceChannel*>(channel));
7106 break;
7107 case cricket::MEDIA_TYPE_VIDEO:
7108 channel_manager()->DestroyVideoChannel(
7109 static_cast<cricket::VideoChannel*>(channel));
7110 break;
7111 case cricket::MEDIA_TYPE_DATA:
7112 channel_manager()->DestroyRtpDataChannel(
7113 static_cast<cricket::RtpDataChannel*>(channel));
7114 break;
7115 default:
7116 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7117 break;
7118 }
Zhi Huange830e682018-03-30 10:48:35 -07007119}
Steve Anton6fec8802017-12-04 10:37:29 -08007120
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007121bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007122 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007123 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007124 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007125 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007126 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007127 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007128 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007129 auto base_channel = GetChannel(mid);
7130 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007131 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007132 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007133 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007134 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007135 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007136
Karl Wiberg5966c502019-02-21 23:55:09 +01007137 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007138 // Only pass media transport to call object if media transport is used
7139 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007140 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007141 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007142
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007143 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007144}
7145
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007146PeerConnectionObserver* PeerConnection::Observer() const {
7147 // In earlier production code, the pointer was not cleared on close,
7148 // which might have led to undefined behavior if the observer was not
7149 // deallocated, or strange crashes if it was.
7150 // We use CHECK in order to catch such behavior if it exists.
7151 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7152 RTC_CHECK(observer_);
7153 return observer_;
7154}
7155
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007156CryptoOptions PeerConnection::GetCryptoOptions() {
7157 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7158 // after it has been removed.
7159 return configuration_.crypto_options.has_value()
7160 ? *configuration_.crypto_options
7161 : factory_->options().crypto_options;
7162}
7163
Harald Alvestrand89061872018-01-02 14:08:34 +01007164void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007165 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007166 if (stats_collector_) {
7167 stats_collector_->ClearCachedStatsReport();
7168 }
7169}
7170
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007171void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007172 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7173 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007174}
7175
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007176void PeerConnection::UpdateNegotiationNeeded() {
7177 RTC_DCHECK_RUN_ON(signaling_thread());
7178 if (!IsUnifiedPlan()) {
7179 Observer()->OnRenegotiationNeeded();
7180 return;
7181 }
7182
7183 // If connection's [[IsClosed]] slot is true, abort these steps.
7184 if (IsClosed())
7185 return;
7186
7187 // If connection's signaling state is not "stable", abort these steps.
7188 if (signaling_state() != kStable)
7189 return;
7190
7191 // NOTE
7192 // The negotiation-needed flag will be updated once the state transitions to
7193 // "stable", as part of the steps for setting an RTCSessionDescription.
7194
7195 // If the result of checking if negotiation is needed is false, clear the
7196 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7197 // to false, and abort these steps.
7198 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7199 if (!is_negotiation_needed) {
7200 is_negotiation_needed_ = false;
7201 return;
7202 }
7203
7204 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7205 // steps.
7206 if (is_negotiation_needed_)
7207 return;
7208
7209 // Set connection's [[NegotiationNeeded]] slot to true.
7210 is_negotiation_needed_ = true;
7211
7212 // Queue a task that runs the following steps:
7213 // If connection's [[IsClosed]] slot is true, abort these steps.
7214 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7215 // Fire an event named negotiationneeded at connection.
7216 Observer()->OnRenegotiationNeeded();
7217}
7218
7219bool PeerConnection::CheckIfNegotiationIsNeeded() {
7220 RTC_DCHECK_RUN_ON(signaling_thread());
7221 // 1. If any implementation-specific negotiation is required, as described at
7222 // the start of this section, return true.
7223
7224 // 2. Let description be connection.[[CurrentLocalDescription]].
7225 const SessionDescriptionInterface* description = current_local_description();
7226 if (!description)
7227 return true;
7228
7229 // 3. If connection has created any RTCDataChannels, and no m= section in
7230 // description has been negotiated yet for data, return true.
7231 if (!sctp_data_channels_.empty()) {
7232 if (!cricket::GetFirstDataContent(description->description()->contents()))
7233 return true;
7234 }
7235
7236 // 4. For each transceiver in connection's set of transceivers, perform the
7237 // following checks:
7238 for (const auto& transceiver : transceivers_) {
7239 const ContentInfo* current_local_msection =
7240 FindTransceiverMSection(transceiver.get(), description);
7241
7242 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7243 transceiver.get(), current_remote_description());
7244
7245 // 4.3 If transceiver is stopped and is associated with an m= section,
7246 // but the associated m= section is not yet rejected in
7247 // connection.[[CurrentLocalDescription]] or
7248 // connection.[[CurrentRemoteDescription]], return true.
7249 if (transceiver->stopped()) {
7250 if (current_local_msection && !current_local_msection->rejected &&
7251 ((current_remote_msection && !current_remote_msection->rejected) ||
7252 !current_remote_msection)) {
7253 return true;
7254 }
7255 continue;
7256 }
7257
7258 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7259 // section in description, return true.
7260 if (!current_local_msection)
7261 return true;
7262
7263 const MediaContentDescription* current_local_media_description =
7264 current_local_msection->media_description();
7265 // 4.2 If transceiver isn't stopped and is associated with an m= section
7266 // in description then perform the following checks:
7267
7268 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7269 // associated m= section in description either doesn't contain a single
7270 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7271 // m= section, or the MSID values themselves, differ from what is in
7272 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7273 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7274 if (current_local_media_description->streams().size() == 0)
7275 return true;
7276
7277 std::vector<std::string> msection_msids;
7278 for (const auto& stream : current_local_media_description->streams()) {
7279 for (const std::string& msid : stream.stream_ids())
7280 msection_msids.push_back(msid);
7281 }
7282
7283 std::vector<std::string> transceiver_msids =
7284 transceiver->sender()->stream_ids();
7285 if (msection_msids.size() != transceiver_msids.size())
7286 return true;
7287
7288 absl::c_sort(transceiver_msids);
7289 absl::c_sort(msection_msids);
7290 if (transceiver_msids != msection_msids)
7291 return true;
7292 }
7293
7294 // 4.2.2 If description is of type "offer", and the direction of the
7295 // associated m= section in neither connection.[[CurrentLocalDescription]]
7296 // nor connection.[[CurrentRemoteDescription]] matches
7297 // transceiver.[[Direction]], return true.
7298 if (description->GetType() == SdpType::kOffer) {
7299 if (!current_remote_description())
7300 return true;
7301
7302 if (!current_remote_msection)
7303 return true;
7304
7305 RtpTransceiverDirection current_local_direction =
7306 current_local_media_description->direction();
7307 RtpTransceiverDirection current_remote_direction =
7308 current_remote_msection->media_description()->direction();
7309 if (transceiver->direction() != current_local_direction &&
7310 transceiver->direction() !=
7311 RtpTransceiverDirectionReversed(current_remote_direction)) {
7312 return true;
7313 }
7314 }
7315
7316 // 4.2.3 If description is of type "answer", and the direction of the
7317 // associated m= section in the description does not match
7318 // transceiver.[[Direction]] intersected with the offered direction (as
7319 // described in [JSEP] (section 5.3.1.)), return true.
7320 if (description->GetType() == SdpType::kAnswer) {
7321 if (!remote_description())
7322 return true;
7323
7324 const ContentInfo* offered_remote_msection =
7325 FindTransceiverMSection(transceiver.get(), remote_description());
7326
7327 RtpTransceiverDirection offered_direction =
7328 offered_remote_msection
7329 ? offered_remote_msection->media_description()->direction()
7330 : RtpTransceiverDirection::kInactive;
7331
7332 if (current_local_media_description->direction() !=
7333 (RtpTransceiverDirectionIntersection(
7334 transceiver->direction(),
7335 RtpTransceiverDirectionReversed(offered_direction)))) {
7336 return true;
7337 }
7338 }
7339 }
7340
7341 // If all the preceding checks were performed and true was not returned,
7342 // nothing remains to be negotiated; return false.
7343 return false;
7344}
7345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007346} // namespace webrtc