blob: 08fbe419491ee4d59e65c34bf47b4191c747af13 [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>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Steve Antondcc3c022017-12-22 16:02:54 -080016#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080017#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080018#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020
Steve Anton64b626b2019-01-28 17:25:26 -080021#include "absl/algorithm/container.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"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.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"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.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
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800613void ReportSimulcastApiVersion(const char* name,
614 const SessionDescription& session) {
615 bool has_legacy = false;
616 bool has_spec_compliant = false;
617 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200618 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800619 continue;
620 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200621 has_spec_compliant |= content.media_description()->HasSimulcast();
622 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800623 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
624 }
625 }
626
627 if (has_legacy) {
628 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
629 kSimulcastApiVersionMax);
630 }
631 if (has_spec_compliant) {
632 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
633 kSimulcastApiVersionMax);
634 }
635 if (!has_legacy && !has_spec_compliant) {
636 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
637 kSimulcastApiVersionMax);
638 }
639}
640
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200641const ContentInfo* FindTransceiverMSection(
642 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
643 const SessionDescriptionInterface* session_description) {
644 return transceiver->mid()
645 ? session_description->description()->GetContentByName(
646 *transceiver->mid())
647 : nullptr;
648}
649
Steve Anton75737c02017-11-06 10:37:17 -0800650} // namespace
651
Henrik Boström79b69802019-07-18 11:16:56 +0200652class PeerConnection::LocalIceCredentialsToReplace {
653 public:
654 // Sets the ICE credentials that need restarting to the ICE credentials of
655 // the current and pending descriptions.
656 void SetIceCredentialsFromLocalDescriptions(
657 const SessionDescriptionInterface* current_local_description,
658 const SessionDescriptionInterface* pending_local_description) {
659 ice_credentials_.clear();
660 if (current_local_description) {
661 AppendIceCredentialsFromSessionDescription(*current_local_description);
662 }
663 if (pending_local_description) {
664 AppendIceCredentialsFromSessionDescription(*pending_local_description);
665 }
666 }
667
668 void ClearIceCredentials() { ice_credentials_.clear(); }
669
670 // Returns true if we have ICE credentials that need restarting.
671 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
672
673 // Returns true if |local_description| shares no ICE credentials with the
674 // ICE credentials that need restarting.
675 bool SatisfiesIceRestart(
676 const SessionDescriptionInterface& local_description) const {
677 for (const auto& transport_info :
678 local_description.description()->transport_infos()) {
679 if (ice_credentials_.find(std::make_pair(
680 transport_info.description.ice_ufrag,
681 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
682 return false;
683 }
684 }
685 return true;
686 }
687
688 private:
689 void AppendIceCredentialsFromSessionDescription(
690 const SessionDescriptionInterface& desc) {
691 for (const auto& transport_info : desc.description()->transport_infos()) {
692 ice_credentials_.insert(
693 std::make_pair(transport_info.description.ice_ufrag,
694 transport_info.description.ice_pwd));
695 }
696 }
697
698 std::set<std::pair<std::string, std::string>> ice_credentials_;
699};
700
Henrik Boström31638672017-11-23 17:48:32 +0100701// Upon completion, posts a task to execute the callback of the
702// SetSessionDescriptionObserver asynchronously on the same thread. At this
703// point, the state of the peer connection might no longer reflect the effects
704// of the SetRemoteDescription operation, as the peer connection could have been
705// modified during the post.
706// TODO(hbos): Remove this class once we remove the version of
707// PeerConnectionInterface::SetRemoteDescription() that takes a
708// SetSessionDescriptionObserver as an argument.
709class PeerConnection::SetRemoteDescriptionObserverAdapter
710 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
711 public:
712 SetRemoteDescriptionObserverAdapter(
713 rtc::scoped_refptr<PeerConnection> pc,
714 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
715 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
716
717 // SetRemoteDescriptionObserverInterface implementation.
718 void OnSetRemoteDescriptionComplete(RTCError error) override {
719 if (error.ok())
720 pc_->PostSetSessionDescriptionSuccess(wrapper_);
721 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100722 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100723 }
724
725 private:
726 rtc::scoped_refptr<PeerConnection> pc_;
727 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
728};
729
deadbeef293e9262017-01-11 12:28:30 -0800730bool PeerConnectionInterface::RTCConfiguration::operator==(
731 const PeerConnectionInterface::RTCConfiguration& o) const {
732 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800734 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000735 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800737 BundlePolicy bundle_policy;
738 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700739 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
740 int ice_candidate_pool_size;
741 bool disable_ipv6;
742 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700743 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100744 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200746 absl::optional<int> screencast_min_bitrate;
747 absl::optional<bool> combined_audio_video_bwe;
748 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800749 TcpCandidatePolicy tcp_candidate_policy;
750 CandidateNetworkPolicy candidate_network_policy;
751 int audio_jitter_buffer_max_packets;
752 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800755 int ice_connection_receiving_timeout;
756 int ice_backup_candidate_pair_ping_interval;
757 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800758 bool prioritize_most_likely_ice_candidate_pairs;
759 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800760 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700761 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800762 bool presume_writable_when_fully_relayed;
763 bool enable_ice_renomination;
764 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700765 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200766 absl::optional<int> ice_check_interval_strong_connectivity;
767 absl::optional<int> ice_check_interval_weak_connectivity;
768 absl::optional<int> ice_check_min_interval;
769 absl::optional<int> ice_unwritable_timeout;
770 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800771 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200772 absl::optional<int> stun_candidate_keepalive_interval;
773 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200774 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800775 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200776 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700777 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700778 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700779 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700780 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700781 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700782 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700783 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100784 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200785 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300786 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 12:23:02 +0200787 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800788 };
789 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
790 "Did you add something to RTCConfiguration and forget to "
791 "update operator==?");
792 return type == o.type && servers == o.servers &&
793 bundle_policy == o.bundle_policy &&
794 rtcp_mux_policy == o.rtcp_mux_policy &&
795 tcp_candidate_policy == o.tcp_candidate_policy &&
796 candidate_network_policy == o.candidate_network_policy &&
797 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
798 audio_jitter_buffer_fast_accelerate ==
799 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100800 audio_jitter_buffer_min_delay_ms ==
801 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100802 audio_jitter_buffer_enable_rtx_handling ==
803 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800804 ice_connection_receiving_timeout ==
805 o.ice_connection_receiving_timeout &&
806 ice_backup_candidate_pair_ping_interval ==
807 o.ice_backup_candidate_pair_ping_interval &&
808 continual_gathering_policy == o.continual_gathering_policy &&
809 certificates == o.certificates &&
810 prioritize_most_likely_ice_candidate_pairs ==
811 o.prioritize_most_likely_ice_candidate_pairs &&
812 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800813 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700814 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100815 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800816 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800817 screencast_min_bitrate == o.screencast_min_bitrate &&
818 combined_audio_video_bwe == o.combined_audio_video_bwe &&
819 enable_dtls_srtp == o.enable_dtls_srtp &&
820 ice_candidate_pool_size == o.ice_candidate_pool_size &&
821 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700822 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800823 presume_writable_when_fully_relayed ==
824 o.presume_writable_when_fully_relayed &&
825 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800826 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700827 surface_ice_candidates_on_ice_transport_type_changed ==
828 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800829 ice_check_interval_strong_connectivity ==
830 o.ice_check_interval_strong_connectivity &&
831 ice_check_interval_weak_connectivity ==
832 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700833 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700834 ice_unwritable_timeout == o.ice_unwritable_timeout &&
835 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800836 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800837 stun_candidate_keepalive_interval ==
838 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200839 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800840 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800841 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700842 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700843 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700844 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700845 use_media_transport_for_data_channels ==
846 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700847 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700848 use_datagram_transport_for_data_channels ==
849 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700850 use_datagram_transport_for_data_channels_receive_only ==
851 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100852 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200853 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300854 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 12:23:02 +0200855 enable_implicit_rollback == o.enable_implicit_rollback &&
856 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800857}
858
859bool PeerConnectionInterface::RTCConfiguration::operator!=(
860 const PeerConnectionInterface::RTCConfiguration& o) const {
861 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800862}
863
zhihuang8f65cdf2016-05-06 18:40:30 -0700864// Generate a RTCP CNAME when a PeerConnection is created.
865std::string GenerateRtcpCname() {
866 std::string cname;
867 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100868 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800869 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700870 }
871 return cname;
872}
873
zhihuang1c378ed2017-08-17 14:10:50 -0700874bool ValidateOfferAnswerOptions(
875 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
876 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
877 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700878}
879
zhihuang1c378ed2017-08-17 14:10:50 -0700880// From |rtc_options|, fill parts of |session_options| shared by all generated
881// m= sections (in other words, nothing that involves a map/array).
882void ExtractSharedMediaSessionOptions(
883 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
884 cricket::MediaSessionOptions* session_options) {
885 session_options->vad_enabled = rtc_options.voice_activity_detection;
886 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200887 session_options->raw_packetization_for_video =
888 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700889}
zhihuanga77e6bb2017-08-14 18:17:48 -0700890
zhihuang38ede132017-06-15 12:52:32 -0700891PeerConnection::PeerConnection(PeerConnectionFactory* factory,
892 std::unique_ptr<RtcEventLog> event_log,
893 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700895 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100896 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700897 datagram_transport_config_(
898 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700899 datagram_transport_data_channel_config_(
900 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700901 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700902 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700903 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100904 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200905 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -0700906 data_channel_transport_(nullptr),
Henrik Boström49c08802019-10-25 09:54:38 +0000907 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908
909PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100910 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800911 RTC_DCHECK_RUN_ON(signaling_thread());
912
Steve Anton8af21862017-12-15 11:20:13 -0800913 // Need to stop transceivers before destroying the stats collector because
914 // AudioRtpSender has a reference to the StatsCollector it will update when
915 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100916 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800917 transceiver->Stop();
918 }
Steve Anton4171afb2017-11-20 10:20:22 -0800919
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700920 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800921 if (stats_collector_) {
922 stats_collector_->WaitForPendingRequest();
923 stats_collector_ = nullptr;
924 }
Steve Anton75737c02017-11-06 10:37:17 -0800925
Steve Anton8af21862017-12-15 11:20:13 -0800926 // Don't destroy BaseChannels until after stats has been cleaned up so that
927 // the last stats request can still read from the channels.
928 DestroyAllChannels();
929
Mirko Bonadei675513b2017-11-09 11:09:25 +0100930 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800931
932 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800933 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700934 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800935 transport_controller_.reset();
936
deadbeef91dd5672016-05-18 16:55:30 -0700937 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100938 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
939 RTC_DCHECK_RUN_ON(network_thread());
940 port_allocator_.reset();
941 });
eladalon248fd4f2017-09-06 05:18:15 -0700942 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700943 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100944 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700945 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800946 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700947 event_log_.reset();
948 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949}
950
Steve Anton8af21862017-12-15 11:20:13 -0800951void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800952 // Destroy video channels first since they may have a pointer to a voice
953 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100954 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800955 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800956 DestroyTransceiverChannel(transceiver);
957 }
958 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100959 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800960 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800961 DestroyTransceiverChannel(transceiver);
962 }
963 }
964 DestroyDataChannel();
965}
966
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000968 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100970 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100971 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100972 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700973
974 RTCError config_error = ValidateConfiguration(configuration);
975 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100976 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700977 return false;
978 }
979
Benjamin Wrightcab58882018-05-02 15:12:47 -0700980 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100981 RTC_LOG(LS_ERROR)
982 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100983 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800984 return false;
985 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200986
Benjamin Wrightcab58882018-05-02 15:12:47 -0700987 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800988 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100989 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100990 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800991 return false;
992 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700993
Benjamin Wrightcab58882018-05-02 15:12:47 -0700994 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700995 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700996 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700997 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800998
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200999 cricket::ServerAddresses stun_servers;
1000 std::vector<cricket::RelayServerConfig> turn_servers;
1001
1002 RTCErrorType parse_error =
1003 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1004 if (parse_error != RTCErrorType::NONE) {
1005 return false;
1006 }
1007
Jonas Oreland3c028422019-08-22 16:16:35 +02001008 // Add the turn logging id to all turn servers
1009 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1010 turn_server.turn_logging_id = configuration.turn_logging_id;
1011 }
1012
deadbeef91dd5672016-05-18 16:55:30 -07001013 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001014 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001015 const auto pa_result =
1016 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001017 RTC_FROM_HERE,
1018 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001019 stun_servers, turn_servers, configuration));
1020
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001021 // If initialization was successful, note if STUN or TURN servers
1022 // were supplied.
1023 if (!stun_servers.empty()) {
1024 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1025 }
1026 if (!turn_servers.empty()) {
1027 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1028 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001030 // Send information about IPv4/IPv6 status.
1031 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001032 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001033 address_family = kPeerConnection_IPv6;
1034 } else {
1035 address_family = kPeerConnection_IPv4;
1036 }
1037 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1038 kPeerConnectionAddressFamilyCounter_Max);
1039
Zhi Huange830e682018-03-30 10:48:35 -07001040 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1041
Steve Anton75737c02017-11-06 10:37:17 -08001042 // RFC 3264: The numeric value of the session id and version in the
1043 // o line MUST be representable with a "64 bit signed integer".
1044 // Due to this constraint session id |session_id_| is max limited to
1045 // LLONG_MAX.
1046 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001047 JsepTransportController::Config config;
1048 config.redetermine_role_on_ice_restart =
1049 configuration.redetermine_role_on_ice_restart;
1050 config.ssl_max_version = factory_->options().ssl_max_version;
1051 config.disable_encryption = options.disable_encryption;
1052 config.bundle_policy = configuration.bundle_policy;
1053 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001054 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1055 // stub.
1056 config.crypto_options = configuration.crypto_options.has_value()
1057 ? *configuration.crypto_options
1058 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001059 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001060 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1061 // since the JsepTransportController instance is owned by this PeerConnection
1062 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1063 // pointer.
1064 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1065 int64_t packet_time_us) {
1066 RTC_DCHECK_RUN_ON(network_thread());
1067 rtcp_invoker_.AsyncInvoke<void>(
1068 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1069 RTC_DCHECK_RUN_ON(worker_thread());
1070 // |call_| is reset on the worker thread in the PeerConnection
1071 // destructor, so we check that it's still valid before propagating
1072 // the packet.
1073 if (call_) {
1074 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1075 packet_time_us);
1076 }
1077 });
1078 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001079 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001080#if defined(ENABLE_EXTERNAL_AUTH)
1081 config.enable_external_auth = true;
1082#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001083 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001084
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001085 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001086 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001087 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001088 use_datagram_transport_for_data_channels_ =
1089 datagram_transport_data_channel_config_.enabled &&
1090 configuration.use_datagram_transport_for_data_channels.value_or(
1091 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001092 use_datagram_transport_for_data_channels_receive_only_ =
1093 configuration.use_datagram_transport_for_data_channels_receive_only
1094 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001095 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1096 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001097 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001098 if (!factory_->media_transport_factory()) {
1099 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001100 << "PeerConnecton is initialized with use_media_transport = true or "
1101 << "use_media_transport_for_data_channels = true "
1102 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001103 return false;
1104 }
1105
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001106 if (configuration.use_media_transport ||
1107 configuration.use_media_transport_for_data_channels) {
1108 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1109 // RTP media transport is introduced. But until then, we require SDES to
1110 // be enabled.
1111 if (configuration.enable_dtls_srtp.has_value() &&
1112 configuration.enable_dtls_srtp.value()) {
1113 RTC_LOG(LS_WARNING)
1114 << "When media transport is used, SDES must be enabled. Set "
1115 "configuration.enable_dtls_srtp to false. use_media_transport="
1116 << configuration.use_media_transport
1117 << ", use_media_transport_for_data_channels="
1118 << configuration.use_media_transport_for_data_channels;
1119 return false;
1120 }
1121 }
1122
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001123 config.use_media_transport_for_media = configuration.use_media_transport;
1124 config.use_media_transport_for_data_channels =
1125 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001126 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001127 config.use_datagram_transport_for_data_channels =
1128 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001129 config.use_datagram_transport_for_data_channels_receive_only =
1130 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001131 config.media_transport_factory = factory_->media_transport_factory();
1132 }
1133
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001134 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1135 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1136 if (!configuration.certificates.empty()) {
1137 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1138 // just picking the first one. The decision should be made based on the DTLS
1139 // handshake. The DTLS negotiations need to know about all certificates.
1140 certificate = configuration.certificates[0];
1141 }
1142
1143 if (options.disable_encryption) {
1144 dtls_enabled_ = false;
1145 } else {
1146 // Enable DTLS by default if we have an identity store or a certificate.
1147 dtls_enabled_ = (dependencies.cert_generator || certificate);
1148 // |configuration| can override the default |dtls_enabled_| value.
1149 if (configuration.enable_dtls_srtp) {
1150 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1151 }
1152 }
1153
1154 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1155
1156 if (use_datagram_transport_for_data_channels_) {
1157 if (configuration.enable_rtp_data_channel) {
1158 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1159 "use_datagram_transport_for_data_channels are "
1160 "incompatible and cannot both be set to true";
1161 return false;
1162 }
1163 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1164 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1165 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1166 } else {
1167 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1168 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1169 config.sctp_factory = sctp_factory_.get();
1170 }
1171 } else if (configuration.use_media_transport_for_data_channels) {
1172 if (configuration.enable_rtp_data_channel) {
1173 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1174 "use_media_transport_for_data_channels are "
1175 "incompatible and cannot both be set to true";
1176 return false;
1177 }
1178 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1179 } else if (configuration.enable_rtp_data_channel) {
1180 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1181 // set. It takes precendence over the disable_sctp_data_channels
1182 // PeerConnectionFactoryInterface::Options.
1183 data_channel_type_ = cricket::DCT_RTP;
1184 } else {
1185 // DTLS has to be enabled to use SCTP.
1186 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1187 data_channel_type_ = cricket::DCT_SCTP;
1188 config.sctp_factory = sctp_factory_.get();
1189 }
1190 }
1191
Zhi Huange830e682018-03-30 10:48:35 -07001192 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001193 signaling_thread(), network_thread(), port_allocator_.get(),
1194 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001195 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001196 this, &PeerConnection::OnTransportControllerConnectionState);
1197 transport_controller_->SignalStandardizedIceConnectionState.connect(
1198 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001199 transport_controller_->SignalConnectionState.connect(
1200 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001201 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001202 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001203 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001204 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001205 transport_controller_->SignalIceCandidateError.connect(
1206 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001207 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001208 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1209 transport_controller_->SignalDtlsHandshakeError.connect(
1210 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001211 transport_controller_->SignalIceCandidatePairChanged.connect(
1212 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001213
deadbeefab9b2d12015-10-14 11:33:11 -07001214 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001215 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216
Steve Antonba818672017-11-06 10:21:57 -08001217 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001218 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001219
Steve Antond25da372017-11-06 14:50:29 -08001220 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001221
Steve Anton75737c02017-11-06 10:37:17 -08001222 video_options_.screencast_min_bitrate_kbps =
1223 configuration.screencast_min_bitrate;
1224 audio_options_.combined_audio_video_bwe =
1225 configuration.combined_audio_video_bwe;
1226
1227 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001228 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001229
1230 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001231 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001232
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001233 audio_options_.audio_jitter_buffer_min_delay_ms =
1234 configuration.audio_jitter_buffer_min_delay_ms;
1235
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001236 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1237 configuration.audio_jitter_buffer_enable_rtx_handling;
1238
Steve Anton75737c02017-11-06 10:37:17 -08001239 // Whether the certificate generator/certificate is null or not determines
1240 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1241 // the right instructions by clearing the variables if needed.
1242 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001243 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001244 certificate = nullptr;
1245 } else if (certificate) {
1246 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001247 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001248 }
1249
1250 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1251 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001252 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001253 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1254 this, &PeerConnection::OnCertificateReady);
1255
1256 if (options.disable_encryption) {
1257 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1258 }
1259
1260 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001261 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001262 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263
Steve Anton4171afb2017-11-20 10:20:22 -08001264 // Add default audio/video transceivers for Plan B SDP.
1265 if (!IsUnifiedPlan()) {
1266 transceivers_.push_back(
1267 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1268 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1269 transceivers_.push_back(
1270 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1271 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1272 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001273 int delay_ms =
1274 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001275 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1276 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001277
1278 if (dependencies.video_bitrate_allocator_factory) {
1279 video_bitrate_allocator_factory_ =
1280 std::move(dependencies.video_bitrate_allocator_factory);
1281 } else {
1282 video_bitrate_allocator_factory_ =
1283 CreateBuiltinVideoBitrateAllocatorFactory();
1284 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 return true;
1286}
1287
Steve Anton038834f2017-07-14 15:59:59 -07001288RTCError PeerConnection::ValidateConfiguration(
1289 const RTCConfiguration& config) const {
1290 if (config.ice_regather_interval_range &&
1291 config.continual_gathering_policy == GATHER_ONCE) {
1292 return RTCError(RTCErrorType::INVALID_PARAMETER,
1293 "ice_regather_interval_range specified but continual "
1294 "gathering policy is GATHER_ONCE");
1295 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001296 auto result =
1297 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1298 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001299}
1300
Yves Gerey665174f2018-06-19 15:03:05 +02001301rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001302 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001303 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1304 "Plan SdpSemantics. Please use GetSenders "
1305 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001306 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307}
1308
Yves Gerey665174f2018-06-19 15:03:05 +02001309rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001310 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001311 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1312 "Plan SdpSemantics. Please use GetReceivers "
1313 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001314 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315}
1316
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001317bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001318 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001319 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1320 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001321 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 if (IsClosed()) {
1323 return false;
1324 }
deadbeefab9b2d12015-10-14 11:33:11 -07001325 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 return false;
1327 }
deadbeefab9b2d12015-10-14 11:33:11 -07001328
1329 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001330 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1331 observer->SignalAudioTrackAdded.connect(this,
1332 &PeerConnection::OnAudioTrackAdded);
1333 observer->SignalAudioTrackRemoved.connect(
1334 this, &PeerConnection::OnAudioTrackRemoved);
1335 observer->SignalVideoTrackAdded.connect(this,
1336 &PeerConnection::OnVideoTrackAdded);
1337 observer->SignalVideoTrackRemoved.connect(
1338 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001339 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001340
deadbeefab9b2d12015-10-14 11:33:11 -07001341 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001342 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001343 }
1344 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001345 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001346 }
1347
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001348 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001349 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001350 return true;
1351}
1352
1353void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001354 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001355 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1356 "Plan SdpSemantics. Please use RemoveTrack "
1357 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001358 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001359 if (!IsClosed()) {
1360 for (const auto& track : local_stream->GetAudioTracks()) {
1361 RemoveAudioTrack(track.get(), local_stream);
1362 }
1363 for (const auto& track : local_stream->GetVideoTracks()) {
1364 RemoveVideoTrack(track.get(), local_stream);
1365 }
deadbeefab9b2d12015-10-14 11:33:11 -07001366 }
deadbeefab9b2d12015-10-14 11:33:11 -07001367 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001368 stream_observers_.erase(
1369 std::remove_if(
1370 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001371 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001372 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001373 }),
1374 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 if (IsClosed()) {
1377 return;
1378 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001379 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380}
1381
Steve Anton2d6c76a2018-01-05 17:10:52 -08001382RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001383 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001384 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001385 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001386 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001387 if (!track) {
1388 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1389 }
1390 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1391 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1393 "Track has invalid kind: " + track->kind());
1394 }
Steve Antonf9381f02017-12-14 10:23:57 -08001395 if (IsClosed()) {
1396 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1397 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001398 }
Steve Anton4171afb2017-11-20 10:20:22 -08001399 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001400 LOG_AND_RETURN_ERROR(
1401 RTCErrorType::INVALID_PARAMETER,
1402 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001403 }
Steve Antonf9381f02017-12-14 10:23:57 -08001404 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001405 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1406 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001407 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001408 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001409 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001410 }
1411 return sender_or_error;
1412}
deadbeefe1f9d832016-01-14 15:35:42 -08001413
Steve Antonf9381f02017-12-14 10:23:57 -08001414RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1415PeerConnection::AddTrackPlanB(
1416 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001417 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001418 if (stream_ids.size() > 1u) {
1419 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1420 "AddTrack with more than one stream is not "
1421 "supported with Plan B semantics.");
1422 }
1423 std::vector<std::string> adjusted_stream_ids = stream_ids;
1424 if (adjusted_stream_ids.empty()) {
1425 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1426 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001427 cricket::MediaType media_type =
1428 (track->kind() == MediaStreamTrackInterface::kAudioKind
1429 ? cricket::MEDIA_TYPE_AUDIO
1430 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001431 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001432 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001433 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001434 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001435 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001436 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001437 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001438 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001439 if (sender_info) {
1440 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001441 }
Steve Antonf9381f02017-12-14 10:23:57 -08001442 } else {
1443 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001444 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001445 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001446 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001447 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001448 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001449 if (sender_info) {
1450 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001451 }
deadbeefe1f9d832016-01-14 15:35:42 -08001452 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001453 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001454}
deadbeefe1f9d832016-01-14 15:35:42 -08001455
Steve Antonf9381f02017-12-14 10:23:57 -08001456RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1457PeerConnection::AddTrackUnifiedPlan(
1458 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001459 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001460 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1461 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001462 RTC_LOG(LS_INFO) << "Reusing an existing "
1463 << cricket::MediaTypeToString(transceiver->media_type())
1464 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001465 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001466 transceiver->internal()->set_direction(
1467 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001468 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001469 transceiver->internal()->set_direction(
1470 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001471 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001472 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001473 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001474 } else {
1475 cricket::MediaType media_type =
1476 (track->kind() == MediaStreamTrackInterface::kAudioKind
1477 ? cricket::MEDIA_TYPE_AUDIO
1478 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001479 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1480 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001481 std::string sender_id = track->id();
1482 // Avoid creating a sender with an existing ID by generating a random ID.
1483 // This can happen if this is the second time AddTrack has created a sender
1484 // for this track.
1485 if (FindSenderById(sender_id)) {
1486 sender_id = rtc::CreateRandomUuid();
1487 }
Florent Castelli892acf02018-10-01 22:47:20 +02001488 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1490 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001491 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001492 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001493 }
Steve Antonf9381f02017-12-14 10:23:57 -08001494 return transceiver->sender();
1495}
1496
1497rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1498PeerConnection::FindFirstTransceiverForAddedTrack(
1499 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1500 RTC_DCHECK(track);
1501 for (auto transceiver : transceivers_) {
1502 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001503 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001504 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001505 !transceiver->internal()->has_ever_been_used_to_send() &&
1506 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001507 return transceiver;
1508 }
1509 }
1510 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001511}
1512
1513bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1514 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001515 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001516}
1517
Steve Anton24db5732018-07-23 10:27:33 -07001518RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001519 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001520 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001521 if (!sender) {
1522 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1523 }
deadbeefe1f9d832016-01-14 15:35:42 -08001524 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001525 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1526 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001527 }
Steve Antonf9381f02017-12-14 10:23:57 -08001528 if (IsUnifiedPlan()) {
1529 auto transceiver = FindTransceiverBySender(sender);
1530 if (!transceiver || !sender->track()) {
1531 return RTCError::OK();
1532 }
1533 sender->SetTrack(nullptr);
1534 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001535 transceiver->internal()->set_direction(
1536 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001537 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001538 transceiver->internal()->set_direction(
1539 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001540 }
Steve Anton4171afb2017-11-20 10:20:22 -08001541 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001542 bool removed;
1543 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1544 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1545 } else {
1546 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1547 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1548 }
1549 if (!removed) {
1550 LOG_AND_RETURN_ERROR(
1551 RTCErrorType::INVALID_PARAMETER,
1552 "Couldn't find sender " + sender->id() + " to remove.");
1553 }
Steve Anton4171afb2017-11-20 10:20:22 -08001554 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001555 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001556 return RTCError::OK();
1557}
1558
1559rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1560PeerConnection::FindTransceiverBySender(
1561 rtc::scoped_refptr<RtpSenderInterface> sender) {
1562 for (auto transceiver : transceivers_) {
1563 if (transceiver->sender() == sender) {
1564 return transceiver;
1565 }
1566 }
1567 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001568}
1569
Steve Anton9158ef62017-11-27 13:01:52 -08001570RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1571PeerConnection::AddTransceiver(
1572 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1573 return AddTransceiver(track, RtpTransceiverInit());
1574}
1575
1576RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1577PeerConnection::AddTransceiver(
1578 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1579 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001580 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001581 RTC_CHECK(IsUnifiedPlan())
1582 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001583 if (!track) {
1584 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1585 }
1586 cricket::MediaType media_type;
1587 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1588 media_type = cricket::MEDIA_TYPE_AUDIO;
1589 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1590 media_type = cricket::MEDIA_TYPE_VIDEO;
1591 } else {
1592 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1593 "Track kind is not audio or video");
1594 }
1595 return AddTransceiver(media_type, track, init);
1596}
1597
1598RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1599PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1600 return AddTransceiver(media_type, RtpTransceiverInit());
1601}
1602
1603RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1604PeerConnection::AddTransceiver(cricket::MediaType media_type,
1605 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001606 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001607 RTC_CHECK(IsUnifiedPlan())
1608 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001609 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1610 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1611 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1612 "media type is not audio or video");
1613 }
1614 return AddTransceiver(media_type, nullptr, init);
1615}
1616
1617RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1618PeerConnection::AddTransceiver(
1619 cricket::MediaType media_type,
1620 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001621 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001622 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001623 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1624 media_type == cricket::MEDIA_TYPE_VIDEO));
1625 if (track) {
1626 RTC_DCHECK_EQ(media_type,
1627 (track->kind() == MediaStreamTrackInterface::kAudioKind
1628 ? cricket::MEDIA_TYPE_AUDIO
1629 : cricket::MEDIA_TYPE_VIDEO));
1630 }
1631
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001632 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1633 init.send_encodings.size(), 0, 7, 8);
1634
Amit Hilbuchaa584152019-02-06 17:09:52 -08001635 size_t num_rids = absl::c_count_if(init.send_encodings,
1636 [](const RtpEncodingParameters& encoding) {
1637 return !encoding.rid.empty();
1638 });
1639 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001640 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001641 RTCErrorType::INVALID_PARAMETER,
1642 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001643 }
1644
Amit Hilbuchf4770402019-04-08 14:11:57 -07001645 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1646 [](const RtpEncodingParameters& encoding) {
1647 return !IsLegalRsidName(encoding.rid);
1648 })) {
1649 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1650 "Invalid RID value provided.");
1651 }
1652
Amit Hilbuchaa584152019-02-06 17:09:52 -08001653 if (absl::c_any_of(init.send_encodings,
1654 [](const RtpEncodingParameters& encoding) {
1655 return encoding.ssrc.has_value();
1656 })) {
1657 LOG_AND_RETURN_ERROR(
1658 RTCErrorType::UNSUPPORTED_PARAMETER,
1659 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001660 }
1661
1662 RtpParameters parameters;
1663 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001664
1665 // Encodings are dropped from the tail if too many are provided.
1666 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1667 parameters.encodings.erase(
1668 parameters.encodings.begin() + kMaxSimulcastStreams,
1669 parameters.encodings.end());
1670 }
1671
1672 // Single RID should be removed.
1673 if (parameters.encodings.size() == 1 &&
1674 !parameters.encodings[0].rid.empty()) {
1675 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1676 parameters.encodings[0].rid.clear();
1677 }
1678
1679 // If RIDs were not provided, they are generated for simulcast scenario.
1680 if (parameters.encodings.size() > 1 && num_rids == 0) {
1681 rtc::UniqueStringGenerator rid_generator;
1682 for (RtpEncodingParameters& encoding : parameters.encodings) {
1683 encoding.rid = rid_generator();
1684 }
1685 }
1686
Florent Castelli892acf02018-10-01 22:47:20 +02001687 if (UnimplementedRtpParameterHasValue(parameters)) {
1688 LOG_AND_RETURN_ERROR(
1689 RTCErrorType::UNSUPPORTED_PARAMETER,
1690 "Attempted to set an unimplemented parameter of RtpParameters.");
1691 }
Steve Anton9158ef62017-11-27 13:01:52 -08001692
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001693 auto result = cricket::CheckRtpParametersValues(parameters);
1694 if (!result.ok()) {
1695 LOG_AND_RETURN_ERROR(result.type(), result.message());
1696 }
1697
Steve Anton3d954a62018-04-02 11:27:23 -07001698 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1699 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001700 // Set the sender ID equal to the track ID if the track is specified unless
1701 // that sender ID is already in use.
1702 std::string sender_id =
1703 (track && !FindSenderById(track->id()) ? track->id()
1704 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001705 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001706 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001707 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1708 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1709 transceiver->internal()->set_direction(init.direction);
1710
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001711 if (update_negotiation_needed) {
1712 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001713 }
Steve Antonf9381f02017-12-14 10:23:57 -08001714
1715 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1716}
1717
Steve Anton02ee47c2018-01-10 16:26:06 -08001718rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1719PeerConnection::CreateSender(
1720 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001721 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001722 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001723 const std::vector<std::string>& stream_ids,
1724 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001725 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001726 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001727 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1728 RTC_DCHECK(!track ||
1729 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1730 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1731 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001732 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001733 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001734 } else {
1735 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1736 RTC_DCHECK(!track ||
1737 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1738 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001739 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001740 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001741 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001742 bool set_track_succeeded = sender->SetTrack(track);
1743 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001744 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001745 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001746 return sender;
1747}
1748
1749rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1750PeerConnection::CreateReceiver(cricket::MediaType media_type,
1751 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001752 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1753 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001754 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001755 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001756 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1757 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001758 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001759 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001760 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001761 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001762 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1763 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001764 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001765 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001766 return receiver;
1767}
1768
1769rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1770PeerConnection::CreateAndAddTransceiver(
1771 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1772 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1773 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001774 // Ensure that the new sender does not have an ID that is already in use by
1775 // another sender.
1776 // Allow receiver IDs to conflict since those come from remote SDP (which
1777 // could be invalid, but should not cause a crash).
1778 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001779 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001780 signaling_thread(),
1781 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001782 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001783 transceiver->internal()->SignalNegotiationNeeded.connect(
1784 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001785 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001786}
1787
Steve Anton52d86772018-02-20 15:48:12 -08001788void PeerConnection::OnNegotiationNeeded() {
1789 RTC_DCHECK_RUN_ON(signaling_thread());
1790 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001791 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001792}
1793
deadbeeffac06552015-11-25 11:26:01 -08001794rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001795 const std::string& kind,
1796 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001797 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001798 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1799 "Plan SdpSemantics. Please use AddTransceiver "
1800 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001801 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001802 if (IsClosed()) {
1803 return nullptr;
1804 }
Steve Anton4171afb2017-11-20 10:20:22 -08001805
Seth Hampson5b4f0752018-04-02 16:31:36 -07001806 // Internally we need to have one stream with Plan B semantics, so we
1807 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001808 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001809 if (stream_id.empty()) {
1810 stream_ids.push_back(rtc::CreateRandomUuid());
1811 RTC_LOG(LS_INFO)
1812 << "No stream_id specified for sender. Generated stream ID: "
1813 << stream_ids[0];
1814 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001815 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001816 }
1817
Steve Anton4171afb2017-11-20 10:20:22 -08001818 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001819 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001820 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001821 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001822 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001823 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001824 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001825 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001826 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001827 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001828 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001829 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001830 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001831 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001832 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001833 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001834 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001835 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001836 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001837 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001838 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001839
deadbeefe1f9d832016-01-14 15:35:42 -08001840 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001841}
1842
deadbeef70ab1a12015-09-28 16:53:55 -07001843std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1844 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001845 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001846 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001847 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001848 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001849 }
1850 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001851}
1852
Steve Anton4171afb2017-11-20 10:20:22 -08001853std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1854PeerConnection::GetSendersInternal() const {
1855 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1856 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001857 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001858 auto senders = transceiver->internal()->senders();
1859 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1860 }
1861 return all_senders;
1862}
1863
deadbeef70ab1a12015-09-28 16:53:55 -07001864std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1865PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001866 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001867 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001868 for (const auto& receiver : GetReceiversInternal()) {
1869 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001870 }
1871 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001872}
1873
Steve Anton4171afb2017-11-20 10:20:22 -08001874std::vector<
1875 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1876PeerConnection::GetReceiversInternal() const {
1877 std::vector<
1878 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1879 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001880 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001881 auto receivers = transceiver->internal()->receivers();
1882 all_receivers.insert(all_receivers.end(), receivers.begin(),
1883 receivers.end());
1884 }
1885 return all_receivers;
1886}
1887
Steve Anton9158ef62017-11-27 13:01:52 -08001888std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1889PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001890 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001891 RTC_CHECK(IsUnifiedPlan())
1892 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001893 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001894 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001895 all_transceivers.push_back(transceiver);
1896 }
1897 return all_transceivers;
1898}
1899
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001901 MediaStreamTrackInterface* track,
1902 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001903 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001904 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001905 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001906 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 return false;
1908 }
1909
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001910 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001911 // The StatsCollector is used to tell if a track is valid because it may
1912 // remember tracks that the PeerConnection previously removed.
1913 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001914 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1915 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001916 return false;
1917 }
Steve Antonad182762018-09-05 20:22:40 +00001918 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1919 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920 return true;
1921}
1922
hbos74e1a4f2016-09-15 23:33:01 -07001923void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001924 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001925 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001926 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001927 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001928 stats_collector_->GetStatsReport(callback);
1929}
1930
Henrik Boström1df1bf82018-03-20 13:24:20 +01001931void PeerConnection::GetStats(
1932 rtc::scoped_refptr<RtpSenderInterface> selector,
1933 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1934 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001935 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001936 RTC_DCHECK(callback);
1937 RTC_DCHECK(stats_collector_);
1938 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1939 if (selector) {
1940 for (const auto& proxy_transceiver : transceivers_) {
1941 for (const auto& proxy_sender :
1942 proxy_transceiver->internal()->senders()) {
1943 if (proxy_sender == selector) {
1944 internal_sender = proxy_sender->internal();
1945 break;
1946 }
1947 }
1948 if (internal_sender)
1949 break;
1950 }
1951 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001952 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001953 // belong to the PeerConnection (in Plan B, senders can be removed from the
1954 // PeerConnection). This means that "all the stats objects representing the
1955 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1956 // produces an empty stats report.
1957 stats_collector_->GetStatsReport(internal_sender, callback);
1958}
1959
1960void PeerConnection::GetStats(
1961 rtc::scoped_refptr<RtpReceiverInterface> selector,
1962 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1963 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001964 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001965 RTC_DCHECK(callback);
1966 RTC_DCHECK(stats_collector_);
1967 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1968 if (selector) {
1969 for (const auto& proxy_transceiver : transceivers_) {
1970 for (const auto& proxy_receiver :
1971 proxy_transceiver->internal()->receivers()) {
1972 if (proxy_receiver == selector) {
1973 internal_receiver = proxy_receiver->internal();
1974 break;
1975 }
1976 }
1977 if (internal_receiver)
1978 break;
1979 }
1980 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001981 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001982 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1983 // the PeerConnection). This means that "all the stats objects representing
1984 // the selector" is an empty set. Invoking GetStatsReport() with a null
1985 // selector produces an empty stats report.
1986 stats_collector_->GetStatsReport(internal_receiver, callback);
1987}
1988
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001990 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 return signaling_state_;
1992}
1993
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001994PeerConnectionInterface::IceConnectionState
1995PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001996 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 return ice_connection_state_;
1998}
1999
Alex Loiko9289eda2018-11-23 16:18:59 +00002000PeerConnectionInterface::IceConnectionState
2001PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002002 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002003 return standardized_ice_connection_state_;
2004}
2005
Jonas Olsson635474e2018-10-18 15:58:17 +02002006PeerConnectionInterface::PeerConnectionState
2007PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002008 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002009 return connection_state_;
2010}
2011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012PeerConnectionInterface::IceGatheringState
2013PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002014 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 return ice_gathering_state_;
2016}
2017
Yves Gerey665174f2018-06-19 15:03:05 +02002018rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019 const std::string& label,
2020 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002021 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002022 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002023
deadbeefab9b2d12015-10-14 11:33:11 -07002024 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002025
kwibergd1fe2812016-04-27 06:47:29 -07002026 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002027 if (config) {
2028 internal_config.reset(new InternalDataChannelInit(*config));
2029 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002030 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002031 InternalCreateDataChannel(label, internal_config.get()));
2032 if (!channel.get()) {
2033 return nullptr;
2034 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002036 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2037 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002038 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002039 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002040 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002041 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 return DataChannelProxy::Create(signaling_thread(), channel.get());
2043}
2044
Henrik Boström79b69802019-07-18 11:16:56 +02002045void PeerConnection::RestartIce() {
2046 RTC_DCHECK_RUN_ON(signaling_thread());
2047 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2048 current_local_description_.get(), pending_local_description_.get());
2049 UpdateNegotiationNeeded();
2050}
2051
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002052void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002053 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002054 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström49c08802019-10-25 09:54:38 +00002055 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002056
nisse7ce109a2017-01-31 00:57:56 -08002057 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002058 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002059 return;
2060 }
deadbeefab9b2d12015-10-14 11:33:11 -07002061
Steve Anton8d3444d2017-10-20 15:30:51 -07002062 if (IsClosed()) {
2063 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002064 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002065 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002066 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002067 return;
2068 }
2069
Steve Anton25ca0ac2019-06-25 10:40:48 -07002070 // If a session error has occurred the PeerConnection is in a possibly
2071 // inconsistent state so fail right away.
2072 if (session_error() != SessionError::kNone) {
2073 std::string error_message = GetSessionErrorMsg();
2074 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2075 PostCreateSessionDescriptionFailure(
2076 observer,
2077 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2078 return;
2079 }
2080
zhihuang1c378ed2017-08-17 14:10:50 -07002081 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002082 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002083 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002084 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002085 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002086 return;
2087 }
2088
Steve Anton22da89f2018-01-25 13:58:07 -08002089 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2090 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2091 if (IsUnifiedPlan()) {
2092 RTCError error = HandleLegacyOfferOptions(options);
2093 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002094 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002095 return;
2096 }
2097 }
2098
zhihuang1c378ed2017-08-17 14:10:50 -07002099 cricket::MediaSessionOptions session_options;
2100 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002101 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102}
2103
Steve Anton22da89f2018-01-25 13:58:07 -08002104RTCError PeerConnection::HandleLegacyOfferOptions(
2105 const RTCOfferAnswerOptions& options) {
2106 RTC_DCHECK(IsUnifiedPlan());
2107
2108 if (options.offer_to_receive_audio == 0) {
2109 RemoveRecvDirectionFromReceivingTransceiversOfType(
2110 cricket::MEDIA_TYPE_AUDIO);
2111 } else if (options.offer_to_receive_audio == 1) {
2112 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2113 } else if (options.offer_to_receive_audio > 1) {
2114 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2115 "offer_to_receive_audio > 1 is not supported.");
2116 }
2117
2118 if (options.offer_to_receive_video == 0) {
2119 RemoveRecvDirectionFromReceivingTransceiversOfType(
2120 cricket::MEDIA_TYPE_VIDEO);
2121 } else if (options.offer_to_receive_video == 1) {
2122 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2123 } else if (options.offer_to_receive_video > 1) {
2124 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2125 "offer_to_receive_video > 1 is not supported.");
2126 }
2127
2128 return RTCError::OK();
2129}
2130
2131void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2132 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002133 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002134 RtpTransceiverDirection new_direction =
2135 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2136 if (new_direction != transceiver->direction()) {
2137 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2138 << " transceiver (MID="
2139 << transceiver->mid().value_or("<not set>") << ") from "
2140 << RtpTransceiverDirectionToString(
2141 transceiver->direction())
2142 << " to "
2143 << RtpTransceiverDirectionToString(new_direction)
2144 << " since CreateOffer specified offer_to_receive=0";
2145 transceiver->internal()->set_direction(new_direction);
2146 }
Steve Anton22da89f2018-01-25 13:58:07 -08002147 }
2148}
2149
2150void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2151 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002152 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002153 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002154 RTC_LOG(LS_INFO)
2155 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2156 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002157 RtpTransceiverInit init;
2158 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002159 AddTransceiver(media_type, nullptr, init,
2160 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002161 }
2162}
2163
2164std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2165PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2166 std::vector<
2167 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2168 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002169 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002170 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002171 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2172 receiving_transceivers.push_back(transceiver);
2173 }
2174 }
2175 return receiving_transceivers;
2176}
2177
htaa2a49d92016-03-04 02:51:39 -08002178void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2179 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002180 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström49c08802019-10-25 09:54:38 +00002181 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002182 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002183 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002184 return;
2185 }
2186
Steve Anton25ca0ac2019-06-25 10:40:48 -07002187 // If a session error has occurred the PeerConnection is in a possibly
2188 // inconsistent state so fail right away.
2189 if (session_error() != SessionError::kNone) {
2190 std::string error_message = GetSessionErrorMsg();
2191 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2192 PostCreateSessionDescriptionFailure(
2193 observer,
2194 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2195 return;
2196 }
2197
Steve Antondffead82018-02-06 10:31:29 -08002198 if (!(signaling_state_ == kHaveRemoteOffer ||
2199 signaling_state_ == kHaveLocalPrAnswer)) {
2200 std::string error =
2201 "PeerConnection cannot create an answer in a state other than "
2202 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002203 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002204 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002205 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002206 return;
2207 }
2208
Steve Antondffead82018-02-06 10:31:29 -08002209 // The remote description should be set if we're in the right state.
2210 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002211
Steve Anton22da89f2018-01-25 13:58:07 -08002212 if (IsUnifiedPlan()) {
2213 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2214 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2215 "supported with Unified Plan semantics. Use the "
2216 "RtpTransceiver API instead.";
2217 }
2218 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2219 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2220 "supported with Unified Plan semantics. Use the "
2221 "RtpTransceiver API instead.";
2222 }
2223 }
2224
htaa2a49d92016-03-04 02:51:39 -08002225 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002226 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002227
Steve Antond25da372017-11-06 14:50:29 -08002228 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229}
2230
2231void PeerConnection::SetLocalDescription(
2232 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002233 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002234 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström49c08802019-10-25 09:54:38 +00002235 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002236
Henrik Boström49c08802019-10-25 09:54:38 +00002237 // The SetLocalDescription contract is that we take ownership of the session
2238 // description regardless of the outcome, so wrap it in a unique_ptr right
2239 // away. Ideally, SetLocalDescription's signature will be changed to take the
2240 // description as a unique_ptr argument to formalize this agreement.
2241 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
Steve Anton80dd7b52018-02-16 17:08:42 -08002242
nisse7ce109a2017-01-31 00:57:56 -08002243 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002244 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245 return;
2246 }
Steve Anton8a006912017-12-04 15:25:56 -08002247
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002249 PostSetSessionDescriptionFailure(
2250 observer,
2251 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 return;
2253 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002254
Steve Anton80dd7b52018-02-16 17:08:42 -08002255 // If a session error has occurred the PeerConnection is in a possibly
2256 // inconsistent state so fail right away.
2257 if (session_error() != SessionError::kNone) {
2258 std::string error_message = GetSessionErrorMsg();
2259 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002260 PostSetSessionDescriptionFailure(
2261 observer,
2262 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002263 return;
2264 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002265
Eldar Rello5ab79e62019-10-09 18:29:44 +03002266 // For SLD we support only explicit rollback.
2267 if (desc->GetType() == SdpType::kRollback) {
2268 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002269 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002270 if (error.ok()) {
2271 PostSetSessionDescriptionSuccess(observer);
2272 } else {
2273 PostSetSessionDescriptionFailure(observer, std::move(error));
2274 }
2275 } else {
2276 PostSetSessionDescriptionFailure(
2277 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2278 "Rollback not supported in Plan B"));
2279 }
2280 return;
2281 }
2282
Steve Anton80dd7b52018-02-16 17:08:42 -08002283 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2284 if (!error.ok()) {
2285 std::string error_message = GetSetDescriptionErrorMessage(
2286 cricket::CS_LOCAL, desc->GetType(), error);
2287 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002288 PostSetSessionDescriptionFailure(
2289 observer,
2290 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002291 return;
2292 }
2293
2294 // Grab the description type before moving ownership to ApplyLocalDescription,
2295 // which may destroy it before returning.
2296 const SdpType type = desc->GetType();
2297
2298 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002299 // |desc| may be destroyed at this point.
2300
2301 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002302 // If ApplyLocalDescription fails, the PeerConnection could be in an
2303 // inconsistent state, so act conservatively here and set the session error
2304 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2305 SetSessionError(SessionError::kContent, error.message());
2306 std::string error_message =
2307 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2308 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002309 PostSetSessionDescriptionFailure(
2310 observer,
2311 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002312 return;
2313 }
Steve Anton8a006912017-12-04 15:25:56 -08002314 RTC_DCHECK(local_description());
2315
2316 PostSetSessionDescriptionSuccess(observer);
2317
Steve Antonad182762018-09-05 20:22:40 +00002318 // MaybeStartGathering needs to be called after posting
2319 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2320 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002321 transport_controller_->MaybeStartGathering();
2322
Steve Antona3a92c22017-12-07 10:27:41 -08002323 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002324 // TODO(deadbeef): We already had to hop to the network thread for
2325 // MaybeStartGathering...
2326 network_thread()->Invoke<void>(
2327 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2328 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002329 // Make UMA notes about what was agreed to.
2330 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002331 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002332
2333 if (IsUnifiedPlan()) {
2334 bool was_negotiation_needed = is_negotiation_needed_;
2335 UpdateNegotiationNeeded();
2336 if (signaling_state() == kStable && was_negotiation_needed &&
2337 is_negotiation_needed_) {
2338 Observer()->OnRenegotiationNeeded();
2339 }
2340 }
2341
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002342 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002343}
2344
2345RTCError PeerConnection::ApplyLocalDescription(
2346 std::unique_ptr<SessionDescriptionInterface> desc) {
2347 RTC_DCHECK_RUN_ON(signaling_thread());
2348 RTC_DCHECK(desc);
2349
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350 // Update stats here so that we have the most recent stats for tracks and
2351 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002352 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002353
Steve Antondcc3c022017-12-22 16:02:54 -08002354 // Take a reference to the old local description since it's used below to
2355 // compare against the new local description. When setting the new local
2356 // description, grab ownership of the replaced session description in case it
2357 // is the same as |old_local_description|, to keep it alive for the duration
2358 // of the method.
2359 const SessionDescriptionInterface* old_local_description =
2360 local_description();
2361 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002362 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002363 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002364 replaced_local_description = pending_local_description_
2365 ? std::move(pending_local_description_)
2366 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002367 current_local_description_ = std::move(desc);
2368 pending_local_description_ = nullptr;
2369 current_remote_description_ = std::move(pending_remote_description_);
2370 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002371 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002372 pending_local_description_ = std::move(desc);
2373 }
2374 // The session description to apply now must be accessed by
2375 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002376 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002377
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002378 // Report statistics about any use of simulcast.
2379 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2380 *local_description()->description());
2381
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002382 if (!is_caller_) {
2383 if (remote_description()) {
2384 // Remote description was applied first, so this PC is the callee.
2385 is_caller_ = false;
2386 } else {
2387 // Local description is applied first, so this PC is the caller.
2388 is_caller_ = true;
2389 }
2390 }
2391
Zhi Huange830e682018-03-30 10:48:35 -07002392 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2393 if (!error.ok()) {
2394 return error;
2395 }
2396
Steve Antondcc3c022017-12-22 16:02:54 -08002397 if (IsUnifiedPlan()) {
2398 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002399 cricket::CS_LOCAL, *local_description(), old_local_description,
2400 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002401 if (!error.ok()) {
2402 return error;
2403 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002404 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2405 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002406 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002407 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2408 // Note that code paths that don't set MID won't be able to use
2409 // information about DTLS transports.
2410 if (transceiver->mid()) {
2411 auto dtls_transport =
2412 LookupDtlsTransportByMidInternal(*transceiver->mid());
2413 transceiver->internal()->sender_internal()->set_transport(
2414 dtls_transport);
2415 transceiver->internal()->receiver_internal()->set_transport(
2416 dtls_transport);
2417 }
2418
Steve Antondcc3c022017-12-22 16:02:54 -08002419 const ContentInfo* content =
2420 FindMediaSectionForTransceiver(transceiver, local_description());
2421 if (!content) {
2422 continue;
2423 }
2424 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002425 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2426 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002427 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002428 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2429 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2430 // "recvonly", process the removal of a remote track for the media
2431 // description, given transceiver, removeList, and muteTracks.
2432 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2433 (transceiver->internal()->fired_direction() &&
2434 RtpTransceiverDirectionHasRecv(
2435 *transceiver->internal()->fired_direction()))) {
2436 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2437 &removed_streams);
2438 }
2439 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2440 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002441 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002442 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002443 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002444 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002445 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002446 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002447 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002448 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002449 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002450 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002451 }
2452 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002453 // Media channels will be created only when offer is set. These may use new
2454 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002455 if (type == SdpType::kOffer) {
2456 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2457 // description is applied. Restore back to old description.
2458 RTCError error = CreateChannels(*local_description()->description());
2459 if (!error.ok()) {
2460 return error;
2461 }
2462 }
Steve Antondcc3c022017-12-22 16:02:54 -08002463 // Remove unused channels if MediaContentDescription is rejected.
2464 RemoveUnusedChannels(local_description()->description());
2465 }
Steve Anton8a006912017-12-04 15:25:56 -08002466
Zhi Huange830e682018-03-30 10:48:35 -07002467 error = UpdateSessionState(type, cricket::CS_LOCAL,
2468 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002469 if (!error.ok()) {
2470 return error;
2471 }
Steve Antondcc3c022017-12-22 16:02:54 -08002472
Steve Anton8a006912017-12-04 15:25:56 -08002473 if (remote_description()) {
2474 // Now that we have a local description, we can push down remote candidates.
2475 UseCandidatesInSessionDescription(remote_description());
2476 }
2477
2478 pending_ice_restarts_.clear();
2479 if (session_error() != SessionError::kNone) {
2480 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2481 }
2482
deadbeefab9b2d12015-10-14 11:33:11 -07002483 // If setting the description decided our SSL role, allocate any necessary
2484 // SCTP sids.
2485 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002486 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002487 AllocateSctpSids(role);
2488 }
2489
Steve Antond3679212018-01-17 17:41:02 -08002490 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002491 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002492 const ContentInfo* content =
2493 FindMediaSectionForTransceiver(transceiver, local_description());
2494 if (!content) {
2495 continue;
2496 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002497 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2498 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002499 // 0 is a special value meaning "this sender has no associated send
2500 // stream". Need to call this so the sender won't attempt to configure
2501 // a no longer existing stream and run into DCHECKs in the lower
2502 // layers.
2503 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002504 } else {
2505 // Get the StreamParams from the channel which could generate SSRCs.
2506 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002507 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002508 streams[0].stream_ids());
2509 transceiver->internal()->sender_internal()->SetSsrc(
2510 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002511 }
2512 }
2513 } else {
2514 // Plan B semantics.
2515
Steve Antondcc3c022017-12-22 16:02:54 -08002516 // Update state and SSRC of local MediaStreams and DataChannels based on the
2517 // local session description.
2518 const cricket::ContentInfo* audio_content =
2519 GetFirstAudioContent(local_description()->description());
2520 if (audio_content) {
2521 if (audio_content->rejected) {
2522 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2523 } else {
2524 const cricket::AudioContentDescription* audio_desc =
2525 audio_content->media_description()->as_audio();
2526 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2527 }
deadbeeffaac4972015-11-12 15:33:07 -08002528 }
deadbeefab9b2d12015-10-14 11:33:11 -07002529
Steve Antondcc3c022017-12-22 16:02:54 -08002530 const cricket::ContentInfo* video_content =
2531 GetFirstVideoContent(local_description()->description());
2532 if (video_content) {
2533 if (video_content->rejected) {
2534 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2535 } else {
2536 const cricket::VideoContentDescription* video_desc =
2537 video_content->media_description()->as_video();
2538 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2539 }
deadbeeffaac4972015-11-12 15:33:07 -08002540 }
deadbeefab9b2d12015-10-14 11:33:11 -07002541 }
2542
2543 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002544 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002545 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002546 const cricket::RtpDataContentDescription* rtp_data_desc =
2547 data_content->media_description()->as_rtp_data();
2548 // rtp_data_desc will be null if this is an SCTP description.
2549 if (rtp_data_desc) {
2550 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002551 }
2552 }
2553
Henrik Boström79b69802019-07-18 11:16:56 +02002554 if (type == SdpType::kAnswer &&
2555 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2556 *current_local_description_)) {
2557 local_ice_credentials_to_replace_->ClearIceCredentials();
2558 }
2559
Steve Anton8a006912017-12-04 15:25:56 -08002560 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002561}
2562
Steve Anton06817cd2018-12-18 15:55:30 -08002563// The SDP parser used to populate these values by default for the 'content
2564// name' if an a=mid line was absent.
2565static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2566 switch (media_type) {
2567 case cricket::MEDIA_TYPE_AUDIO:
2568 return cricket::CN_AUDIO;
2569 case cricket::MEDIA_TYPE_VIDEO:
2570 return cricket::CN_VIDEO;
2571 case cricket::MEDIA_TYPE_DATA:
2572 return cricket::CN_DATA;
2573 }
2574 RTC_NOTREACHED();
2575 return "";
2576}
2577
2578void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002579 cricket::SessionDescription* new_remote_description) {
2580 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002581 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002582 const cricket::ContentInfos& local_contents =
2583 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002584 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002585 const cricket::ContentInfos& remote_contents =
2586 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002587 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002588 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2589 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002590 if (!content.name.empty()) {
2591 continue;
2592 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002593 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002594 absl::string_view source_explanation;
2595 if (IsUnifiedPlan()) {
2596 if (i < local_contents.size()) {
2597 new_mid = local_contents[i].name;
2598 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002599 } else if (i < remote_contents.size()) {
2600 new_mid = remote_contents[i].name;
2601 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002602 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002603 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002604 source_explanation = "generated just now";
2605 }
2606 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002607 new_mid = std::string(
2608 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002609 source_explanation = "to match pre-existing behavior";
2610 }
Steve Antond7180cc2019-02-07 10:44:53 -08002611 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002612 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002613 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002614 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2615 << " is missing an a=mid line. Filling in the value '"
2616 << new_mid << "' " << source_explanation << ".";
2617 }
2618}
2619
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002621 SetSessionDescriptionObserver* observer,
Henrik Boström49c08802019-10-25 09:54:38 +00002622 SessionDescriptionInterface* desc) {
2623 SetRemoteDescription(
2624 std::unique_ptr<SessionDescriptionInterface>(desc),
2625 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2626 new SetRemoteDescriptionObserverAdapter(this, observer)));
Henrik Boström31638672017-11-23 17:48:32 +01002627}
2628
2629void PeerConnection::SetRemoteDescription(
2630 std::unique_ptr<SessionDescriptionInterface> desc,
2631 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002632 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström49c08802019-10-25 09:54:38 +00002633 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002634
nisse7ce109a2017-01-31 00:57:56 -08002635 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002636 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002637 return;
2638 }
Steve Anton8a006912017-12-04 15:25:56 -08002639
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002640 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002641 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002642 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643 return;
2644 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002645
Steve Anton80dd7b52018-02-16 17:08:42 -08002646 // If a session error has occurred the PeerConnection is in a possibly
2647 // inconsistent state so fail right away.
2648 if (session_error() != SessionError::kNone) {
2649 std::string error_message = GetSessionErrorMsg();
2650 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2651 observer->OnSetRemoteDescriptionComplete(
2652 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2653 return;
2654 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03002655 if (IsUnifiedPlan()) {
2656 if (configuration_.enable_implicit_rollback) {
2657 if (desc->GetType() == SdpType::kOffer &&
2658 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002659 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002660 }
2661 }
2662 // Explicit rollback.
2663 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002664 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03002665 return;
2666 }
2667 } else if (desc->GetType() == SdpType::kRollback) {
2668 observer->OnSetRemoteDescriptionComplete(
2669 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2670 "Rollback not supported in Plan B"));
2671 return;
2672 }
Steve Antonba42e992018-04-09 14:10:01 -07002673 if (desc->GetType() == SdpType::kOffer) {
2674 // Report to UMA the format of the received offer.
2675 ReportSdpFormatReceived(*desc);
2676 }
2677
Steve Anton06817cd2018-12-18 15:55:30 -08002678 // Handle remote descriptions missing a=mid lines for interop with legacy end
2679 // points.
2680 FillInMissingRemoteMids(desc->description());
2681
Steve Anton80dd7b52018-02-16 17:08:42 -08002682 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002683 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002684 std::string error_message = GetSetDescriptionErrorMessage(
2685 cricket::CS_REMOTE, desc->GetType(), error);
2686 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002687 observer->OnSetRemoteDescriptionComplete(
2688 RTCError(error.type(), std::move(error_message)));
2689 return;
2690 }
Steve Anton71439a62018-02-15 11:53:06 -08002691
Steve Anton80dd7b52018-02-16 17:08:42 -08002692 // Grab the description type before moving ownership to
2693 // ApplyRemoteDescription, which may destroy it before returning.
2694 const SdpType type = desc->GetType();
2695
2696 error = ApplyRemoteDescription(std::move(desc));
2697 // |desc| may be destroyed at this point.
2698
2699 if (!error.ok()) {
2700 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2701 // inconsistent state, so act conservatively here and set the session error
2702 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2703 SetSessionError(SessionError::kContent, error.message());
2704 std::string error_message =
2705 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2706 RTC_LOG(LS_ERROR) << error_message;
2707 observer->OnSetRemoteDescriptionComplete(
2708 RTCError(error.type(), std::move(error_message)));
2709 return;
2710 }
2711 RTC_DCHECK(remote_description());
2712
2713 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002714 // TODO(deadbeef): We already had to hop to the network thread for
2715 // MaybeStartGathering...
2716 network_thread()->Invoke<void>(
2717 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2718 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002719 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002720 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002721 }
2722
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002723 if (IsUnifiedPlan()) {
2724 bool was_negotiation_needed = is_negotiation_needed_;
2725 UpdateNegotiationNeeded();
2726 if (signaling_state() == kStable && was_negotiation_needed &&
2727 is_negotiation_needed_) {
2728 Observer()->OnRenegotiationNeeded();
2729 }
2730 }
2731
Steve Anton8a006912017-12-04 15:25:56 -08002732 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002733 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002734}
2735
2736RTCError PeerConnection::ApplyRemoteDescription(
2737 std::unique_ptr<SessionDescriptionInterface> desc) {
2738 RTC_DCHECK_RUN_ON(signaling_thread());
2739 RTC_DCHECK(desc);
2740
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741 // Update stats here so that we have the most recent stats for tracks and
2742 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002743 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002744
Steve Antondcc3c022017-12-22 16:02:54 -08002745 // Take a reference to the old remote description since it's used below to
2746 // compare against the new remote description. When setting the new remote
2747 // description, grab ownership of the replaced session description in case it
2748 // is the same as |old_remote_description|, to keep it alive for the duration
2749 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002750 const SessionDescriptionInterface* old_remote_description =
2751 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002752 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002753 SdpType type = desc->GetType();
2754 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002755 replaced_remote_description = pending_remote_description_
2756 ? std::move(pending_remote_description_)
2757 : std::move(current_remote_description_);
2758 current_remote_description_ = std::move(desc);
2759 pending_remote_description_ = nullptr;
2760 current_local_description_ = std::move(pending_local_description_);
2761 } else {
2762 replaced_remote_description = std::move(pending_remote_description_);
2763 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002764 }
Steve Anton8a006912017-12-04 15:25:56 -08002765 // The session description to apply now must be accessed by
2766 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002767 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002769 // Report statistics about any use of simulcast.
2770 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2771 *remote_description()->description());
2772
Zhi Huange830e682018-03-30 10:48:35 -07002773 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2774 if (!error.ok()) {
2775 return error;
2776 }
Steve Anton8a006912017-12-04 15:25:56 -08002777 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002778 if (IsUnifiedPlan()) {
2779 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002780 cricket::CS_REMOTE, *remote_description(), local_description(),
2781 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002782 if (!error.ok()) {
2783 return error;
2784 }
Steve Antondcc3c022017-12-22 16:02:54 -08002785 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002786 // Media channels will be created only when offer is set. These may use new
2787 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002788 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002789 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002790 // description is applied. Restore back to old description.
2791 RTCError error = CreateChannels(*remote_description()->description());
2792 if (!error.ok()) {
2793 return error;
2794 }
2795 }
Steve Antondcc3c022017-12-22 16:02:54 -08002796 // Remove unused channels if MediaContentDescription is rejected.
2797 RemoveUnusedChannels(remote_description()->description());
2798 }
Steve Anton8a006912017-12-04 15:25:56 -08002799
Zhi Huange830e682018-03-30 10:48:35 -07002800 // NOTE: Candidates allocation will be initiated only when
2801 // SetLocalDescription is called.
2802 error = UpdateSessionState(type, cricket::CS_REMOTE,
2803 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002804 if (!error.ok()) {
2805 return error;
2806 }
2807
2808 if (local_description() &&
2809 !UseCandidatesInSessionDescription(remote_description())) {
2810 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2811 }
2812
2813 if (old_remote_description) {
2814 for (const cricket::ContentInfo& content :
2815 old_remote_description->description()->contents()) {
2816 // Check if this new SessionDescription contains new ICE ufrag and
2817 // password that indicates the remote peer requests an ICE restart.
2818 // TODO(deadbeef): When we start storing both the current and pending
2819 // remote description, this should reset pending_ice_restarts and compare
2820 // against the current description.
2821 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2822 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002823 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002824 pending_ice_restarts_.insert(content.name);
2825 }
2826 } else {
2827 // We retain all received candidates only if ICE is not restarted.
2828 // When ICE is restarted, all previous candidates belong to an old
2829 // generation and should not be kept.
2830 // TODO(deadbeef): This goes against the W3C spec which says the remote
2831 // description should only contain candidates from the last set remote
2832 // description plus any candidates added since then. We should remove
2833 // this once we're sure it won't break anything.
2834 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2835 old_remote_description, content.name, mutable_remote_description());
2836 }
2837 }
2838 }
2839
2840 if (session_error() != SessionError::kNone) {
2841 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2842 }
2843
2844 // Set the the ICE connection state to connecting since the connection may
2845 // become writable with peer reflexive candidates before any remote candidate
2846 // is signaled.
2847 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2848 // is to have a new signal the indicates a change in checking state from the
2849 // transport and expose a new checking() member from transport that can be
2850 // read to determine the current checking state. The existing SignalConnecting
2851 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002852 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002853 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002854 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2855 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2856 }
2857
deadbeefab9b2d12015-10-14 11:33:11 -07002858 // If setting the description decided our SSL role, allocate any necessary
2859 // SCTP sids.
2860 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002861 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002862 AllocateSctpSids(role);
2863 }
2864
Steve Antondcc3c022017-12-22 16:02:54 -08002865 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002866 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002867 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002868 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002869 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002870 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002871 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002872 const ContentInfo* content =
2873 FindMediaSectionForTransceiver(transceiver, remote_description());
2874 if (!content) {
2875 continue;
2876 }
2877 const MediaContentDescription* media_desc = content->media_description();
2878 RtpTransceiverDirection local_direction =
2879 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002880 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2881 // RTCSessionDescription: Set the associated remote streams given
2882 // transceiver.[[Receiver]], msids, addList, and removeList".
2883 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2884 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2885 std::vector<std::string> stream_ids;
2886 if (!media_desc->streams().empty()) {
2887 // The remote description has signaled the stream IDs.
2888 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002889 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002890 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2891 << " (" << GetStreamIdsString(stream_ids) << ").";
2892 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2893 stream_ids, &added_streams,
2894 &removed_streams);
2895 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2896 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2897 // and transceiver's current direction is neither sendrecv nor recvonly,
2898 // process the addition of a remote track for the media description.
2899 if (!transceiver->fired_direction() ||
2900 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2901 RTC_LOG(LS_INFO)
2902 << "Processing the addition of a remote track for MID="
2903 << content->name << ".";
2904 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002905 }
Steve Antondcc3c022017-12-22 16:02:54 -08002906 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002907 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002908 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2909 // removal of a remote track for the media description, given transceiver,
2910 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002911 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002912 (transceiver->fired_direction() &&
2913 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2914 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2915 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002916 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002917 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002918 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002919 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002920 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002921 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002922 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002923 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002924 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002925 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2926 if (transceiver->mid()) {
2927 auto dtls_transport =
2928 LookupDtlsTransportByMidInternal(*transceiver->mid());
2929 transceiver->internal()->sender_internal()->set_transport(
2930 dtls_transport);
2931 transceiver->internal()->receiver_internal()->set_transport(
2932 dtls_transport);
2933 }
Steve Antondcc3c022017-12-22 16:02:54 -08002934 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002935 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002936 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002937 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002938 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2939 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002940 transceiver->Stop();
2941 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002942 if (!content->rejected &&
2943 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002944 if (!media_desc->streams().empty() &&
2945 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07002946 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
2947 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
2948 } else {
2949 transceiver->internal()
2950 ->receiver_internal()
2951 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002952 }
Steve Antond3679212018-01-17 17:41:02 -08002953 }
Steve Antondcc3c022017-12-22 16:02:54 -08002954 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002955 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002956 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002957 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002958 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002959 observer->OnTrack(transceiver);
2960 observer->OnAddTrack(transceiver->receiver(),
2961 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002962 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002963 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002964 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002965 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002966 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002967 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002968 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002969 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002970 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002971 }
Steve Antondcc3c022017-12-22 16:02:54 -08002972 }
2973
Henrik Boströmfdb92012017-11-09 19:55:44 +01002974 const cricket::ContentInfo* audio_content =
2975 GetFirstAudioContent(remote_description()->description());
2976 const cricket::ContentInfo* video_content =
2977 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002978 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002979 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002980 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002981 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002982 const cricket::RtpDataContentDescription* rtp_data_desc =
2983 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002984
2985 // Check if the descriptions include streams, just in case the peer supports
2986 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002987 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002988 (audio_desc && !audio_desc->streams().empty()) ||
2989 (video_desc && !video_desc->streams().empty())) {
2990 remote_peer_supports_msid_ = true;
2991 }
deadbeefab9b2d12015-10-14 11:33:11 -07002992
2993 // We wait to signal new streams until we finish processing the description,
2994 // since only at that point will new streams have all their tracks.
2995 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2996
Steve Antondcc3c022017-12-22 16:02:54 -08002997 if (!IsUnifiedPlan()) {
2998 // TODO(steveanton): When removing RTP senders/receivers in response to a
2999 // rejected media section, there is some cleanup logic that expects the
3000 // voice/ video channel to still be set. But in this method the voice/video
3001 // channel would have been destroyed by the SetRemoteDescription caller
3002 // above so the cleanup that relies on them fails to run. The RemoveSenders
3003 // calls should be moved to right before the DestroyChannel calls to fix
3004 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003005
Steve Antondcc3c022017-12-22 16:02:54 -08003006 // Find all audio rtp streams and create corresponding remote AudioTracks
3007 // and MediaStreams.
3008 if (audio_content) {
3009 if (audio_content->rejected) {
3010 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3011 } else {
3012 bool default_audio_track_needed =
3013 !remote_peer_supports_msid_ &&
3014 RtpTransceiverDirectionHasSend(audio_desc->direction());
3015 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3016 default_audio_track_needed, audio_desc->type(),
3017 new_streams);
3018 }
deadbeeffaac4972015-11-12 15:33:07 -08003019 }
deadbeefab9b2d12015-10-14 11:33:11 -07003020
Steve Antondcc3c022017-12-22 16:02:54 -08003021 // Find all video rtp streams and create corresponding remote VideoTracks
3022 // and MediaStreams.
3023 if (video_content) {
3024 if (video_content->rejected) {
3025 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3026 } else {
3027 bool default_video_track_needed =
3028 !remote_peer_supports_msid_ &&
3029 RtpTransceiverDirectionHasSend(video_desc->direction());
3030 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3031 default_video_track_needed, video_desc->type(),
3032 new_streams);
3033 }
deadbeeffaac4972015-11-12 15:33:07 -08003034 }
deadbeefab9b2d12015-10-14 11:33:11 -07003035
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003036 // If this is an RTP data transport, update the DataChannels with the
3037 // information from the remote peer.
3038 if (rtp_data_desc) {
3039 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003040 }
deadbeefab9b2d12015-10-14 11:33:11 -07003041
Steve Antondcc3c022017-12-22 16:02:54 -08003042 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003043 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003044 for (size_t i = 0; i < new_streams->count(); ++i) {
3045 MediaStreamInterface* new_stream = new_streams->at(i);
3046 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003047 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003048 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3049 }
deadbeefab9b2d12015-10-14 11:33:11 -07003050
Steve Antondcc3c022017-12-22 16:02:54 -08003051 UpdateEndedRemoteMediaStreams();
3052 }
deadbeefab9b2d12015-10-14 11:33:11 -07003053
Henrik Boström79b69802019-07-18 11:16:56 +02003054 if (type == SdpType::kAnswer &&
3055 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3056 *current_local_description_)) {
3057 local_ice_credentials_to_replace_->ClearIceCredentials();
3058 }
3059
Steve Anton8a006912017-12-04 15:25:56 -08003060 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003061}
3062
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003063void PeerConnection::SetAssociatedRemoteStreams(
3064 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3065 const std::vector<std::string>& stream_ids,
3066 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3067 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3068 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3069 for (const std::string& stream_id : stream_ids) {
3070 rtc::scoped_refptr<MediaStreamInterface> stream =
3071 remote_streams_->find(stream_id);
3072 if (!stream) {
3073 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3074 MediaStream::Create(stream_id));
3075 remote_streams_->AddStream(stream);
3076 added_streams->push_back(stream);
3077 }
3078 media_streams.push_back(stream);
3079 }
3080 // Special case: "a=msid" missing, use random stream ID.
3081 if (media_streams.empty() &&
3082 !(remote_description()->description()->msid_signaling() &
3083 cricket::kMsidSignalingMediaSection)) {
3084 if (!missing_msid_default_stream_) {
3085 missing_msid_default_stream_ = MediaStreamProxy::Create(
3086 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3087 added_streams->push_back(missing_msid_default_stream_);
3088 }
3089 media_streams.push_back(missing_msid_default_stream_);
3090 }
3091 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3092 receiver->streams();
3093 // SetStreams() will add/remove the receiver's track to/from the streams. This
3094 // differs from the spec - the spec uses an "addList" and "removeList" to
3095 // update the stream-track relationships in a later step. We do this earlier,
3096 // changing the order of things, but the end-result is the same.
3097 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3098 // instead. https://crbug.com/webrtc/9480
3099 receiver->SetStreams(media_streams);
3100 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3101}
3102
Steve Anton0f5400a2018-07-17 14:25:36 -07003103void PeerConnection::ProcessRemovalOfRemoteTrack(
3104 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3105 transceiver,
3106 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3107 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3108 RTC_DCHECK(transceiver->mid());
3109 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3110 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003111 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003112 transceiver->internal()->receiver_internal()->streams();
3113 // This will remove the remote track from the streams.
3114 transceiver->internal()->receiver_internal()->set_stream_ids({});
3115 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003116 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3117}
3118
3119void PeerConnection::RemoveRemoteStreamsIfEmpty(
3120 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3121 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3122 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3123 // streams, see if the stream was removed by checking if this was the last
3124 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003125 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003126 if (remote_stream->GetAudioTracks().empty() &&
3127 remote_stream->GetVideoTracks().empty()) {
3128 remote_streams_->RemoveStream(remote_stream);
3129 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003130 }
3131 }
3132}
3133
Steve Antondcc3c022017-12-22 16:02:54 -08003134RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3135 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003136 const SessionDescriptionInterface& new_session,
3137 const SessionDescriptionInterface* old_local_description,
3138 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003139 RTC_DCHECK(IsUnifiedPlan());
3140
Steve Anton7464fca2018-01-19 11:10:37 -08003141 const cricket::ContentGroup* bundle_group = nullptr;
3142 if (new_session.GetType() == SdpType::kOffer) {
3143 auto bundle_group_or_error =
3144 GetEarlyBundleGroup(*new_session.description());
3145 if (!bundle_group_or_error.ok()) {
3146 return bundle_group_or_error.MoveError();
3147 }
3148 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003149 }
Steve Antondcc3c022017-12-22 16:02:54 -08003150
Steve Antondcc3c022017-12-22 16:02:54 -08003151 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003152 for (size_t i = 0; i < new_contents.size(); ++i) {
3153 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003154 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003155 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003156 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3157 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003158 const cricket::ContentInfo* old_local_content = nullptr;
3159 if (old_local_description &&
3160 i < old_local_description->description()->contents().size()) {
3161 old_local_content =
3162 &old_local_description->description()->contents()[i];
3163 }
3164 const cricket::ContentInfo* old_remote_content = nullptr;
3165 if (old_remote_description &&
3166 i < old_remote_description->description()->contents().size()) {
3167 old_remote_content =
3168 &old_remote_description->description()->contents()[i];
3169 }
Steve Antondcc3c022017-12-22 16:02:54 -08003170 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003171 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3172 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003173 if (!transceiver_or_error.ok()) {
3174 return transceiver_or_error.MoveError();
3175 }
3176 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003177 RTCError error =
3178 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3179 if (!error.ok()) {
3180 return error;
3181 }
3182 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003183 if (GetDataMid() && new_content.name != *GetDataMid()) {
3184 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003185 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3186 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003187 continue;
3188 }
3189 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3190 if (!error.ok()) {
3191 return error;
3192 }
Steve Antondcc3c022017-12-22 16:02:54 -08003193 } else {
3194 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3195 "Unknown section type.");
3196 }
3197 }
3198
3199 return RTCError::OK();
3200}
3201
3202RTCError PeerConnection::UpdateTransceiverChannel(
3203 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3204 transceiver,
3205 const cricket::ContentInfo& content,
3206 const cricket::ContentGroup* bundle_group) {
3207 RTC_DCHECK(IsUnifiedPlan());
3208 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003209 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003210 if (content.rejected) {
3211 if (channel) {
3212 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003213 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003214 }
3215 } else {
3216 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003217 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003218 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003219 } else {
Steve Anton69470252018-02-09 11:43:08 -08003220 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003221 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003222 }
3223 if (!channel) {
3224 LOG_AND_RETURN_ERROR(
3225 RTCErrorType::INTERNAL_ERROR,
3226 "Failed to create channel for mid=" + content.name);
3227 }
3228 transceiver->internal()->SetChannel(channel);
3229 }
3230 }
3231 return RTCError::OK();
3232}
3233
Steve Antonfa2260d2017-12-28 16:38:23 -08003234RTCError PeerConnection::UpdateDataChannel(
3235 cricket::ContentSource source,
3236 const cricket::ContentInfo& content,
3237 const cricket::ContentGroup* bundle_group) {
3238 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003239 // If data channels are disabled, ignore this media section. CreateAnswer
3240 // will take care of rejecting it.
3241 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003242 }
3243 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003244 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003245 DestroyDataChannel();
3246 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003247 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003248 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003249 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003250 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3251 "Failed to create data channel.");
3252 }
3253 }
3254 if (source == cricket::CS_REMOTE) {
3255 const MediaContentDescription* data_desc = content.media_description();
3256 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3257 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3258 }
3259 }
3260 }
3261 return RTCError::OK();
3262}
3263
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003264// This method will extract any send encodings that were sent by the remote
3265// connection. This is currently only relevant for Simulcast scenario (where
3266// the number of layers may be communicated by the server).
3267static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3268 const MediaContentDescription& desc) {
3269 if (!desc.HasSimulcast()) {
3270 return {};
3271 }
3272 std::vector<RtpEncodingParameters> result;
3273 const SimulcastDescription& simulcast = desc.simulcast_description();
3274
3275 // This is a remote description, the parameters we are after should appear
3276 // as receive streams.
3277 for (const auto& alternatives : simulcast.receive_layers()) {
3278 RTC_DCHECK(!alternatives.empty());
3279 // There is currently no way to specify or choose from alternatives.
3280 // We will always use the first alternative, which is the most preferred.
3281 const SimulcastLayer& layer = alternatives[0];
3282 RtpEncodingParameters parameters;
3283 parameters.rid = layer.rid;
3284 parameters.active = !layer.is_paused;
3285 result.push_back(parameters);
3286 }
3287
3288 return result;
3289}
3290
3291static RTCError UpdateSimulcastLayerStatusInSender(
3292 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003293 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003294 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003295 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003296 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003297
3298 // The simulcast envelope cannot be changed, only the status of the streams.
3299 // So we will iterate over the send encodings rather than the layers.
3300 for (RtpEncodingParameters& encoding : parameters.encodings) {
3301 auto iter = std::find_if(layers.begin(), layers.end(),
3302 [&encoding](const SimulcastLayer& layer) {
3303 return layer.rid == encoding.rid;
3304 });
3305 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003306 if (iter == layers.end()) {
3307 disabled_layers.push_back(encoding.rid);
3308 continue;
3309 }
3310
3311 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003312 }
3313
Amit Hilbuch619b2942019-02-26 15:55:19 -08003314 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003315 if (result.ok()) {
3316 result = sender->DisableEncodingLayers(disabled_layers);
3317 }
3318
3319 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003320}
3321
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003322static bool SimulcastIsRejected(
3323 const ContentInfo* local_content,
3324 const MediaContentDescription& answer_media_desc) {
3325 bool simulcast_offered = local_content &&
3326 local_content->media_description() &&
3327 local_content->media_description()->HasSimulcast();
3328 bool simulcast_answered = answer_media_desc.HasSimulcast();
3329 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3330 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3331 return simulcast_offered && (!simulcast_answered || !rids_supported);
3332}
3333
Amit Hilbuch2297d332019-02-19 12:49:22 -08003334static RTCError DisableSimulcastInSender(
3335 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003336 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003337 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003338 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003339 return RTCError::OK();
3340 }
3341
Amit Hilbuch2297d332019-02-19 12:49:22 -08003342 std::vector<std::string> disabled_layers;
3343 std::transform(
3344 parameters.encodings.begin() + 1, parameters.encodings.end(),
3345 std::back_inserter(disabled_layers),
3346 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3347 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003348}
3349
Steve Antondcc3c022017-12-22 16:02:54 -08003350RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3351PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003352 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003353 size_t mline_index,
3354 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003355 const ContentInfo* old_local_content,
3356 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003357 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003358 // If this is an offer then the m= section might be recycled. If the m=
3359 // section is being recycled (defined as: rejected in the current local or
3360 // remote description and not rejected in new description), dissociate the
3361 // currently associated RtpTransceiver by setting its mid property to null,
3362 // and discard the mapping between the transceiver and its m= section index.
3363 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3364 old_remote_content)) {
3365 // We want to dissociate the transceiver that has the rejected mid.
3366 const std::string& old_mid =
3367 (old_local_content && old_local_content->rejected)
3368 ? old_local_content->name
3369 : old_remote_content->name;
3370 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003371 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003372 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3373 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003374 old_transceiver->internal()->set_mid(absl::nullopt);
3375 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003376 }
3377 }
3378 const MediaContentDescription* media_desc = content.media_description();
3379 auto transceiver = GetAssociatedTransceiver(content.name);
3380 if (source == cricket::CS_LOCAL) {
3381 // Find the RtpTransceiver that corresponds to this m= section, using the
3382 // mapping between transceivers and m= section indices established when
3383 // creating the offer.
3384 if (!transceiver) {
3385 transceiver = GetTransceiverByMLineIndex(mline_index);
3386 }
3387 if (!transceiver) {
3388 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3389 "Unknown transceiver");
3390 }
3391 } else {
3392 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3393 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3394 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003395 // When simulcast is requested, a transceiver cannot be associated because
3396 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003397 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003398 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3399 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003400 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3401 }
3402 // If no RtpTransceiver was found in the previous step, create one with a
3403 // recvonly direction.
3404 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003405 RTC_LOG(LS_INFO) << "Adding "
3406 << cricket::MediaTypeToString(media_desc->type())
3407 << " transceiver for MID=" << content.name
3408 << " at i=" << mline_index
3409 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003410 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003411 std::vector<RtpEncodingParameters> send_encodings =
3412 GetSendEncodingsFromRemoteDescription(*media_desc);
3413 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3414 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003415 std::string receiver_id;
3416 if (!media_desc->streams().empty()) {
3417 receiver_id = media_desc->streams()[0].id;
3418 } else {
3419 receiver_id = rtc::CreateRandomUuid();
3420 }
3421 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003422 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003423 transceiver->internal()->set_direction(
3424 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003425 if (type == SdpType::kOffer) {
3426 transceiver_stable_states_by_transceivers_[transceiver] =
3427 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3428 absl::nullopt, absl::nullopt, true);
3429 }
Steve Antondcc3c022017-12-22 16:02:54 -08003430 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003431 // Check if the offer indicated simulcast but the answer rejected it.
3432 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003433 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003434 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003435 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003436 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003437 if (!error.ok()) {
3438 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3439 return std::move(error);
3440 }
3441 }
Steve Antondcc3c022017-12-22 16:02:54 -08003442 }
3443 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003444 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003445 LOG_AND_RETURN_ERROR(
3446 RTCErrorType::INVALID_PARAMETER,
3447 "Transceiver type does not match media description type.");
3448 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003449 if (media_desc->HasSimulcast()) {
3450 std::vector<SimulcastLayer> layers =
3451 source == cricket::CS_LOCAL
3452 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3453 : media_desc->simulcast_description()
3454 .receive_layers()
3455 .GetAllLayers();
3456 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003457 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003458 if (!error.ok()) {
3459 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3460 return std::move(error);
3461 }
3462 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003463 if (type == SdpType::kOffer) {
3464 // Make sure we don't overwrite existing stable states and that the
3465 // state is really going to change when adding new record to the map.
3466 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3467 if (it == transceiver_stable_states_by_transceivers_.end() &&
3468 (transceiver->internal()->mid() != content.name ||
3469 transceiver->internal()->mline_index() != mline_index)) {
3470 transceiver_stable_states_by_transceivers_[transceiver] =
3471 TransceiverStableState(transceiver->internal()->direction(),
3472 transceiver->internal()->mid(),
3473 transceiver->internal()->mline_index(), false);
3474 }
3475 }
3476
Steve Antondcc3c022017-12-22 16:02:54 -08003477 // Associate the found or created RtpTransceiver with the m= section by
3478 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3479 // section, and establish a mapping between the transceiver and the index of
3480 // the m= section.
3481 transceiver->internal()->set_mid(content.name);
3482 transceiver->internal()->set_mline_index(mline_index);
3483 return std::move(transceiver);
3484}
3485
3486rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3487PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3488 RTC_DCHECK(IsUnifiedPlan());
3489 for (auto transceiver : transceivers_) {
3490 if (transceiver->mid() == mid) {
3491 return transceiver;
3492 }
3493 }
3494 return nullptr;
3495}
3496
3497rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3498PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3499 RTC_DCHECK(IsUnifiedPlan());
3500 for (auto transceiver : transceivers_) {
3501 if (transceiver->internal()->mline_index() == mline_index) {
3502 return transceiver;
3503 }
3504 }
3505 return nullptr;
3506}
3507
3508rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3509PeerConnection::FindAvailableTransceiverToReceive(
3510 cricket::MediaType media_type) const {
3511 RTC_DCHECK(IsUnifiedPlan());
3512 // From JSEP section 5.10 (Applying a Remote Description):
3513 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3514 // the same type that were added to the PeerConnection by addTrack and are not
3515 // associated with any m= section and are not stopped, find the first such
3516 // RtpTransceiver.
3517 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003518 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003519 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3520 !transceiver->stopped()) {
3521 return transceiver;
3522 }
3523 }
3524 return nullptr;
3525}
3526
Steve Antoned10bd92017-12-05 10:52:59 -08003527const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3528 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3529 transceiver,
3530 const SessionDescriptionInterface* sdesc) const {
3531 RTC_DCHECK(transceiver);
3532 RTC_DCHECK(sdesc);
3533 if (IsUnifiedPlan()) {
3534 if (!transceiver->internal()->mid()) {
3535 // This transceiver is not associated with a media section yet.
3536 return nullptr;
3537 }
3538 return sdesc->description()->GetContentByName(
3539 *transceiver->internal()->mid());
3540 } else {
3541 // Plan B only allows at most one audio and one video section, so use the
3542 // first media section of that type.
3543 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003544 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003545 }
3546}
3547
deadbeef46c73892016-11-16 19:42:04 -08003548PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003549 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003550 return configuration_;
3551}
3552
Niels Möller2579f0c2019-08-19 09:58:17 +02003553RTCError PeerConnection::SetConfiguration(
3554 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003555 RTC_DCHECK_RUN_ON(signaling_thread());
3556 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003557 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003558 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3560 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003561 }
3562
Qingsi Wanga2d60672018-04-11 16:57:45 -07003563 // According to JSEP, after setLocalDescription, changing the candidate pool
3564 // size is not allowed, and changing the set of ICE servers will not result
3565 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003566 if (local_description() && configuration.ice_candidate_pool_size !=
3567 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003568 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3569 "Can't change candidate pool size after calling "
3570 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003571 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003572
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003573 if (local_description() &&
3574 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3576 "Can't change media_transport after calling "
3577 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003578 }
3579
3580 if (remote_description() &&
3581 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003582 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3583 "Can't change media_transport after calling "
3584 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003585 }
3586
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003587 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003588 configuration.use_media_transport_for_data_channels !=
3589 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3591 "Can't change media_transport_for_data_channels "
3592 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003593 }
3594
3595 if (remote_description() &&
3596 configuration.use_media_transport_for_data_channels !=
3597 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003598 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3599 "Can't change media_transport_for_data_channels "
3600 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003601 }
3602
3603 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003604 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3606 "Can't change crypto_options after calling "
3607 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003608 }
3609
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003610 if (local_description() && configuration.use_datagram_transport !=
3611 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003612 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3613 "Can't change use_datagram_transport "
3614 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003615 }
3616
3617 if (remote_description() && configuration.use_datagram_transport !=
3618 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003619 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3620 "Can't change use_datagram_transport "
3621 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003622 }
3623
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003624 if (local_description() &&
3625 configuration.use_datagram_transport_for_data_channels !=
3626 configuration_.use_datagram_transport_for_data_channels) {
3627 LOG_AND_RETURN_ERROR(
3628 RTCErrorType::INVALID_MODIFICATION,
3629 "Can't change use_datagram_transport_for_data_channels "
3630 "after calling SetLocalDescription.");
3631 }
3632
3633 if (remote_description() &&
3634 configuration.use_datagram_transport_for_data_channels !=
3635 configuration_.use_datagram_transport_for_data_channels) {
3636 LOG_AND_RETURN_ERROR(
3637 RTCErrorType::INVALID_MODIFICATION,
3638 "Can't change use_datagram_transport_for_data_channels "
3639 "after calling SetRemoteDescription.");
3640 }
3641
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003642 if (local_description() &&
3643 configuration.use_datagram_transport_for_data_channels_receive_only !=
3644 configuration_
3645 .use_datagram_transport_for_data_channels_receive_only) {
3646 LOG_AND_RETURN_ERROR(
3647 RTCErrorType::INVALID_MODIFICATION,
3648 "Can't change use_datagram_transport_for_data_channels_receive_only "
3649 "after calling SetLocalDescription.");
3650 }
3651
3652 if (remote_description() &&
3653 configuration.use_datagram_transport_for_data_channels_receive_only !=
3654 configuration_
3655 .use_datagram_transport_for_data_channels_receive_only) {
3656 LOG_AND_RETURN_ERROR(
3657 RTCErrorType::INVALID_MODIFICATION,
3658 "Can't change use_datagram_transport_for_data_channels_receive_only "
3659 "after calling SetRemoteDescription.");
3660 }
3661
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003662 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003663 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003664 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003665 *configuration.use_datagram_transport) ||
3666 (configuration.use_datagram_transport_for_data_channels &&
3667 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003668 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3669 << "Media transport requires MaxBundle policy.";
3670 }
3671
deadbeef293e9262017-01-11 12:28:30 -08003672 // The simplest (and most future-compatible) way to tell if the config was
3673 // modified in an invalid way is to copy each property we do support
3674 // modifying, then use operator==. There are far more properties we don't
3675 // support modifying than those we do, and more could be added.
3676 RTCConfiguration modified_config = configuration_;
3677 modified_config.servers = configuration.servers;
3678 modified_config.type = configuration.type;
3679 modified_config.ice_candidate_pool_size =
3680 configuration.ice_candidate_pool_size;
3681 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003682 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07003683 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3684 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003685 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003686 modified_config.ice_check_interval_strong_connectivity =
3687 configuration.ice_check_interval_strong_connectivity;
3688 modified_config.ice_check_interval_weak_connectivity =
3689 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003690 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3691 modified_config.ice_unwritable_min_checks =
3692 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003693 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003694 modified_config.stun_candidate_keepalive_interval =
3695 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003696 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003697 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003698 modified_config.active_reset_srtp_params =
3699 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003700 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003701 modified_config.use_media_transport_for_data_channels =
3702 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003703 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003704 modified_config.use_datagram_transport_for_data_channels =
3705 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003706 modified_config.use_datagram_transport_for_data_channels_receive_only =
3707 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02003708 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 12:23:02 +02003709 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -08003710 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003711 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3712 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003713 }
3714
Steve Anton038834f2017-07-14 15:59:59 -07003715 // Validate the modified configuration.
3716 RTCError validate_error = ValidateConfiguration(modified_config);
3717 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003718 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003719 }
3720
deadbeef293e9262017-01-11 12:28:30 -08003721 // Note that this isn't possible through chromium, since it's an unsigned
3722 // short in WebIDL.
3723 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003724 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003725 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003726 }
3727
3728 // Parse ICE servers before hopping to network thread.
3729 cricket::ServerAddresses stun_servers;
3730 std::vector<cricket::RelayServerConfig> turn_servers;
3731 RTCErrorType parse_error =
3732 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3733 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003734 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003735 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003736 // Add the turn logging id to all turn servers
3737 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3738 turn_server.turn_logging_id = configuration.turn_logging_id;
3739 }
3740
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003741 // Note if STUN or TURN servers were supplied.
3742 if (!stun_servers.empty()) {
3743 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3744 }
3745 if (!turn_servers.empty()) {
3746 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3747 }
deadbeef293e9262017-01-11 12:28:30 -08003748
3749 // In theory this shouldn't fail.
3750 if (!network_thread()->Invoke<bool>(
3751 RTC_FROM_HERE,
3752 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3753 stun_servers, turn_servers, modified_config.type,
3754 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003755 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003756 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003757 modified_config.stun_candidate_keepalive_interval,
3758 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003759 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3760 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003761 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003762
deadbeefd1a38b52016-12-10 13:15:33 -08003763 // As described in JSEP, calling setConfiguration with new ICE servers or
3764 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3765 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003766 if (modified_config.servers != configuration_.servers ||
3767 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003768 modified_config.GetTurnPortPrunePolicy() !=
3769 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08003770 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003771 }
skvladd1f5fda2017-02-03 16:54:05 -08003772
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003773 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003774
3775 use_datagram_transport_ = datagram_transport_config_.enabled &&
3776 modified_config.use_datagram_transport.value_or(
3777 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003778 use_datagram_transport_for_data_channels_ =
3779 datagram_transport_data_channel_config_.enabled &&
3780 modified_config.use_datagram_transport_for_data_channels.value_or(
3781 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003782 use_datagram_transport_for_data_channels_receive_only_ =
3783 modified_config.use_datagram_transport_for_data_channels_receive_only
3784 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003785 transport_controller_->SetMediaTransportSettings(
3786 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003787 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003788 use_datagram_transport_, use_datagram_transport_for_data_channels_,
3789 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08003790
Zhi Huangb57e1692018-06-12 11:41:11 -07003791 if (configuration_.active_reset_srtp_params !=
3792 modified_config.active_reset_srtp_params) {
3793 transport_controller_->SetActiveResetSrtpParams(
3794 modified_config.active_reset_srtp_params);
3795 }
3796
philipel16cec3b2019-10-25 12:23:02 +02003797 if (modified_config.allow_codec_switching.has_value()) {
3798 video_media_channel()->SetVideoCodecSwitchingEnabled(
3799 *modified_config.allow_codec_switching);
3800 }
3801
deadbeef293e9262017-01-11 12:28:30 -08003802 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003803 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003804 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003805}
3806
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003807bool PeerConnection::AddIceCandidate(
3808 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003809 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003810 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003811 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003812 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003813 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003814 return false;
3815 }
Steve Antond25da372017-11-06 14:50:29 -08003816
3817 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003818 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003819 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003820 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003821 return false;
3822 }
3823
3824 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003825 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003826 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003827 return false;
3828 }
3829
3830 bool valid = false;
3831 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3832 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003833 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003834 return false;
3835 }
3836
3837 // Add this candidate to the remote session description.
3838 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003839 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003840 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003841 return false;
3842 }
3843
3844 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003845 bool result = UseCandidate(ice_candidate);
3846 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003847 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003848 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3849 } else {
3850 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3851 }
3852 return result;
Steve Antond25da372017-11-06 14:50:29 -08003853 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003854 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003855 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003856 return true;
3857 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003858}
3859
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003860bool PeerConnection::RemoveIceCandidates(
3861 const std::vector<cricket::Candidate>& candidates) {
3862 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003863 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003864 if (IsClosed()) {
3865 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3866 return false;
3867 }
3868
Steve Antond25da372017-11-06 14:50:29 -08003869 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003870 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3871 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003872 return false;
3873 }
3874
3875 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003876 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003877 return false;
3878 }
3879
3880 size_t number_removed =
3881 mutable_remote_description()->RemoveCandidates(candidates);
3882 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003883 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003884 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003885 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003886 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003887 }
3888
3889 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003890 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3891 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003892 RTC_LOG(LS_ERROR)
3893 << "RemoveIceCandidates: Error when removing remote candidates: "
3894 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003895 }
3896 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003897}
3898
Niels Möller0c4f7be2018-05-07 14:01:37 +02003899RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003900 if (!worker_thread()->IsCurrent()) {
3901 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003902 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003903 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003904 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003905
Niels Möller0c4f7be2018-05-07 14:01:37 +02003906 const bool has_min = bitrate.min_bitrate_bps.has_value();
3907 const bool has_start = bitrate.start_bitrate_bps.has_value();
3908 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003909 if (has_min && *bitrate.min_bitrate_bps < 0) {
3910 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3911 "min_bitrate_bps <= 0");
3912 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003913 if (has_start) {
3914 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003915 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003916 "start_bitrate_bps < min_bitrate_bps");
3917 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003918 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3919 "curent_bitrate_bps < 0");
3920 }
3921 }
3922 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003923 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003924 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003925 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003926 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3927 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3928 "max_bitrate_bps < min_bitrate_bps");
3929 } else if (*bitrate.max_bitrate_bps < 0) {
3930 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3931 "max_bitrate_bps < 0");
3932 }
3933 }
3934
zstein4b979802017-06-02 14:37:37 -07003935 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003936 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003937
3938 return RTCError::OK();
3939}
3940
henrika5f6bf242017-11-01 11:06:56 +01003941void PeerConnection::SetAudioPlayout(bool playout) {
3942 if (!worker_thread()->IsCurrent()) {
3943 worker_thread()->Invoke<void>(
3944 RTC_FROM_HERE,
3945 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3946 return;
3947 }
3948 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003949 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003950 audio_state->SetPlayout(playout);
3951}
3952
3953void PeerConnection::SetAudioRecording(bool recording) {
3954 if (!worker_thread()->IsCurrent()) {
3955 worker_thread()->Invoke<void>(
3956 RTC_FROM_HERE,
3957 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3958 return;
3959 }
3960 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003961 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003962 audio_state->SetRecording(recording);
3963}
3964
Steve Anton8c0f7a72017-10-03 10:03:10 -07003965std::unique_ptr<rtc::SSLCertificate>
3966PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003967 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3968 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003969 return nullptr;
3970 }
Steve Antonf25303e2018-10-16 15:23:31 -07003971 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003972}
3973
Zhi Huang70b820f2018-01-27 14:16:15 -08003974std::unique_ptr<rtc::SSLCertChain>
3975PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003976 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003977 auto audio_transceiver = GetFirstAudioTransceiver();
3978 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003979 return nullptr;
3980 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003981 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003982 audio_transceiver->internal()->channel()->transport_name());
3983}
3984
3985rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3986PeerConnection::GetFirstAudioTransceiver() const {
3987 for (auto transceiver : transceivers_) {
3988 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3989 return transceiver;
3990 }
3991 }
3992 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003993}
3994
Bjorn Tereliusde939432017-11-20 17:38:14 +01003995bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3996 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003997 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02003998 RTC_FROM_HERE,
3999 [this, output = std::move(output), output_period_ms]() mutable {
4000 return StartRtcEventLog_w(std::move(output), output_period_ms);
4001 });
ivoc14d5dbe2016-07-04 07:06:55 -07004002}
4003
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004004bool PeerConnection::StartRtcEventLog(
4005 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004006 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4007 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4008 output_period_ms = 5000;
4009 }
4010 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004011}
4012
ivoc14d5dbe2016-07-04 07:06:55 -07004013void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004014 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004015 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4016}
4017
Harald Alvestrandad88c882018-11-28 16:47:46 +01004018rtc::scoped_refptr<DtlsTransportInterface>
4019PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004020 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004021 return transport_controller_->LookupDtlsTransportByMid(mid);
4022}
4023
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004024rtc::scoped_refptr<DtlsTransport>
4025PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004026 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004027 return transport_controller_->LookupDtlsTransportByMid(mid);
4028}
4029
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004030rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4031 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004032 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004033 if (!sctp_mid_) {
4034 return nullptr;
4035 }
4036 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004037}
4038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004039const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004040 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004041 return pending_local_description_ ? pending_local_description_.get()
4042 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004043}
4044
4045const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004046 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004047 return pending_remote_description_ ? pending_remote_description_.get()
4048 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004049}
4050
deadbeeffe4a8a42016-12-20 17:56:17 -08004051const SessionDescriptionInterface* PeerConnection::current_local_description()
4052 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004053 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004054 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004055}
4056
4057const SessionDescriptionInterface* PeerConnection::current_remote_description()
4058 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004059 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004060 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004061}
4062
4063const SessionDescriptionInterface* PeerConnection::pending_local_description()
4064 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004065 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004066 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004067}
4068
4069const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4070 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004071 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004072 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004073}
4074
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004075void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004076 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004077 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004078 // Update stats here so that we have the most recent stats for tracks and
4079 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004080 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004081
Steve Anton75737c02017-11-06 10:37:17 -08004082 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004083 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004084
Mirko Bonadei739baf02019-01-27 17:29:42 +01004085 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004086 transceiver->Stop();
4087 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004088
4089 // Ensure that all asynchronous stats requests are completed before destroying
4090 // the transport controller below.
4091 if (stats_collector_) {
4092 stats_collector_->WaitForPendingRequest();
4093 }
4094
4095 // Don't destroy BaseChannels until after stats has been cleaned up so that
4096 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004097 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004098
Qingsi Wang93a84392018-01-30 17:13:09 -08004099 // The event log is used in the transport controller, which must be outlived
4100 // by the former. CreateOffer by the peer connection is implemented
4101 // asynchronously and if the peer connection is closed without resetting the
4102 // WebRTC session description factory, the session description factory would
4103 // call the transport controller.
4104 webrtc_session_desc_factory_.reset();
4105 transport_controller_.reset();
4106
deadbeef42a42632017-03-10 15:18:00 -08004107 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004108 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4109 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004110
Steve Anton978b8762017-09-29 12:15:02 -07004111 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004112 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004113 call_.reset();
4114 // The event log must outlive call (and any other object that uses it).
4115 event_log_.reset();
4116 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004117 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004118 // The .h file says that observer can be discarded after close() returns.
4119 // Make sure this is true.
4120 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004121}
4122
Steve Antonad182762018-09-05 20:22:40 +00004123void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004124 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004125 switch (msg->message_id) {
4126 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4127 SetSessionDescriptionMsg* param =
4128 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4129 param->observer->OnSuccess();
4130 delete param;
4131 break;
4132 }
4133 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4134 SetSessionDescriptionMsg* param =
4135 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4136 param->observer->OnFailure(std::move(param->error));
4137 delete param;
4138 break;
4139 }
4140 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4141 CreateSessionDescriptionMsg* param =
4142 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4143 param->observer->OnFailure(std::move(param->error));
4144 delete param;
4145 break;
4146 }
4147 case MSG_GETSTATS: {
4148 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4149 StatsReports reports;
4150 stats_->GetStats(param->track, &reports);
4151 param->observer->OnComplete(reports);
4152 delete param;
4153 break;
4154 }
4155 case MSG_FREE_DATACHANNELS: {
4156 sctp_data_channels_to_free_.clear();
4157 break;
4158 }
4159 case MSG_REPORT_USAGE_PATTERN: {
4160 ReportUsagePattern();
4161 break;
4162 }
4163 default:
4164 RTC_NOTREACHED() << "Not implemented";
4165 break;
4166 }
4167}
4168
Steve Antonafb0bb72018-02-20 11:35:37 -08004169cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4170 RTC_DCHECK(!IsUnifiedPlan());
4171 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4172 GetAudioTransceiver()->internal()->channel());
4173 if (voice_channel) {
4174 return voice_channel->media_channel();
4175 } else {
4176 return nullptr;
4177 }
4178}
4179
4180cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4181 RTC_DCHECK(!IsUnifiedPlan());
4182 auto* video_channel = static_cast<cricket::VideoChannel*>(
4183 GetVideoTransceiver()->internal()->channel());
4184 if (video_channel) {
4185 return video_channel->media_channel();
4186 } else {
4187 return nullptr;
4188 }
4189}
4190
Steve Anton4171afb2017-11-20 10:20:22 -08004191void PeerConnection::CreateAudioReceiver(
4192 MediaStreamInterface* stream,
4193 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004194 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4195 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004196 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4197 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004198 auto* audio_receiver = new AudioRtpReceiver(
4199 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004200 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004201 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4202 audio_receiver->SetupUnsignaledMediaChannel();
4203 } else {
4204 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4205 }
Steve Antond3679212018-01-17 17:41:02 -08004206 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4207 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004208 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004209 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004210 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004211}
4212
Steve Anton4171afb2017-11-20 10:20:22 -08004213void PeerConnection::CreateVideoReceiver(
4214 MediaStreamInterface* stream,
4215 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004216 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4217 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004218 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4219 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004220 auto* video_receiver = new VideoRtpReceiver(
4221 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004222 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004223 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4224 video_receiver->SetupUnsignaledMediaChannel();
4225 } else {
4226 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4227 }
Steve Antond3679212018-01-17 17:41:02 -08004228 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4229 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004230 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004231 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004232 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004233}
4234
deadbeef70ab1a12015-09-28 16:53:55 -07004235// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4236// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004237rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004238 const RtpSenderInfo& remote_sender_info) {
4239 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4240 if (!receiver) {
4241 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4242 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004243 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004244 }
Steve Anton4171afb2017-11-20 10:20:22 -08004245 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4246 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4247 } else {
4248 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4249 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004250 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004251}
4252
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004253void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4254 MediaStreamInterface* stream) {
4255 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004256 RTC_DCHECK(track);
4257 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004258 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004259 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004260 // We already have a sender for this track, so just change the stream_id
4261 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004262 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004263 return;
4264 }
4265
4266 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004267 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004268 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004269 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004270 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004271 // If the sender has already been configured in SDP, we call SetSsrc,
4272 // which will connect the sender to the underlying transport. This can
4273 // occur if a local session description that contains the ID of the sender
4274 // is set before AddStream is called. It can also occur if the local
4275 // session description is not changed and RemoveStream is called, and
4276 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004277 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004278 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004279 if (sender_info) {
4280 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004281 }
4282}
4283
4284// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4285// indefinitely, when we have unified plan SDP.
4286void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4287 MediaStreamInterface* stream) {
4288 RTC_DCHECK(!IsClosed());
4289 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004290 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004291 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4292 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004293 return;
4294 }
Steve Anton4171afb2017-11-20 10:20:22 -08004295 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004296}
4297
4298void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4299 MediaStreamInterface* stream) {
4300 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004301 RTC_DCHECK(track);
4302 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004303 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004304 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004305 // We already have a sender for this track, so just change the stream_id
4306 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004307 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004308 return;
4309 }
4310
4311 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004312 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004313 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004314 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004315 GetVideoTransceiver()->internal()->AddSender(new_sender);
4316 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004317 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004318 if (sender_info) {
4319 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004320 }
4321}
4322
4323void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4324 MediaStreamInterface* stream) {
4325 RTC_DCHECK(!IsClosed());
4326 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004327 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004328 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4329 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004330 return;
4331 }
Steve Anton4171afb2017-11-20 10:20:22 -08004332 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004333}
4334
Steve Antonba818672017-11-06 10:21:57 -08004335void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004336 if (ice_connection_state_ == new_state) {
4337 return;
4338 }
4339
deadbeefcbecd352015-09-23 11:50:27 -07004340 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004341 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004342 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004343 return;
4344 }
Steve Antonba818672017-11-06 10:21:57 -08004345
Mirko Bonadei675513b2017-11-09 11:09:25 +01004346 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4347 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004348 RTC_DCHECK(ice_connection_state_ !=
4349 PeerConnectionInterface::kIceConnectionClosed);
4350
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004351 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004352 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004353}
4354
Alex Loiko9289eda2018-11-23 16:18:59 +00004355void PeerConnection::SetStandardizedIceConnectionState(
4356 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004357 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004358 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004359 }
4360
4361 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004362 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004363 }
4364
4365 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4366 << standardized_ice_connection_state_ << " => " << new_state;
4367
Alex Loiko9289eda2018-11-23 16:18:59 +00004368 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004369 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004370}
4371
Jonas Olsson635474e2018-10-18 15:58:17 +02004372void PeerConnection::SetConnectionState(
4373 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004374 if (connection_state_ == new_state)
4375 return;
4376 if (IsClosed())
4377 return;
4378 connection_state_ = new_state;
4379 Observer()->OnConnectionChange(new_state);
4380}
4381
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004382void PeerConnection::OnIceGatheringChange(
4383 PeerConnectionInterface::IceGatheringState new_state) {
4384 if (IsClosed()) {
4385 return;
4386 }
4387 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004388 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004389}
4390
jbauch81bf7b02017-03-25 08:31:12 -07004391void PeerConnection::OnIceCandidate(
4392 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004393 if (IsClosed()) {
4394 return;
4395 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004396 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004397 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004398}
4399
Eldar Relloda13ea22019-06-01 12:23:43 +03004400void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4401 const std::string& url,
4402 int error_code,
4403 const std::string& error_text) {
4404 if (IsClosed()) {
4405 return;
4406 }
4407 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4408}
4409
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004410void PeerConnection::OnIceCandidatesRemoved(
4411 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004412 if (IsClosed()) {
4413 return;
4414 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004415 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004416}
4417
Alex Drake00c7ecf2019-08-06 10:54:47 -07004418void PeerConnection::OnSelectedCandidatePairChanged(
4419 const cricket::CandidatePairChangeEvent& event) {
4420 if (IsClosed()) {
4421 return;
4422 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004423
Qingsi Wangcc46b102019-09-12 11:19:01 -07004424 if (event.selected_candidate_pair.local_candidate().type() ==
4425 LOCAL_PORT_TYPE &&
4426 event.selected_candidate_pair.remote_candidate().type() ==
4427 LOCAL_PORT_TYPE) {
4428 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4429 }
4430
Alex Drake00c7ecf2019-08-06 10:54:47 -07004431 Observer()->OnIceSelectedCandidatePairChanged(event);
4432}
4433
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004434void PeerConnection::ChangeSignalingState(
4435 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004436 if (signaling_state_ == signaling_state) {
4437 return;
4438 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004439 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4440 << GetSignalingStateString(signaling_state_)
4441 << " New state: "
4442 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004443 signaling_state_ = signaling_state;
4444 if (signaling_state == kClosed) {
4445 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004446 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004447 standardized_ice_connection_state_ =
4448 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004449 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4450 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004451 if (ice_gathering_state_ != kIceGatheringComplete) {
4452 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004453 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004454 }
4455 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004456 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004457}
4458
deadbeefeb459812015-12-15 19:24:43 -08004459void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4460 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004461 if (IsClosed()) {
4462 return;
4463 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004464 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004465 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004466}
4467
deadbeefeb459812015-12-15 19:24:43 -08004468void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4469 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004470 if (IsClosed()) {
4471 return;
4472 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004473 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004474 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004475}
4476
4477void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4478 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004479 if (IsClosed()) {
4480 return;
4481 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004482 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004483 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004484}
4485
4486void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4487 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004488 if (IsClosed()) {
4489 return;
4490 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004491 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004492 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004493}
4494
Henrik Boström31638672017-11-23 17:48:32 +01004495void PeerConnection::PostSetSessionDescriptionSuccess(
4496 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004497 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4498 signaling_thread()->Post(RTC_FROM_HERE, this,
4499 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004500}
4501
deadbeefab9b2d12015-10-14 11:33:11 -07004502void PeerConnection::PostSetSessionDescriptionFailure(
4503 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004504 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004505 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004506 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4507 msg->error = std::move(error);
4508 signaling_thread()->Post(RTC_FROM_HERE, this,
4509 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004510}
4511
4512void PeerConnection::PostCreateSessionDescriptionFailure(
4513 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004514 RTCError error) {
4515 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004516 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4517 msg->error = std::move(error);
4518 signaling_thread()->Post(RTC_FROM_HERE, this,
4519 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004520}
4521
zhihuang1c378ed2017-08-17 14:10:50 -07004522void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004523 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004524 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004525 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004526
Steve Antondcc3c022017-12-22 16:02:54 -08004527 if (IsUnifiedPlan()) {
4528 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4529 } else {
4530 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4531 }
4532
Steve Antonfa2260d2017-12-28 16:38:23 -08004533 // Intentionally unset the data channel type for RTP data channel with the
4534 // second condition. Otherwise the RTP data channels would be successfully
4535 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4536 // when building with chromium. We want to leave RTP data channels broken, so
4537 // people won't try to use them.
4538 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4539 session_options->data_channel_type = data_channel_type();
4540 }
4541
Steve Antondcc3c022017-12-22 16:02:54 -08004542 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004543 bool ice_restart = offer_answer_options.ice_restart ||
4544 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004545 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004546 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004547 options.transport_options.enable_ice_renomination =
4548 configuration_.enable_ice_renomination;
4549 }
4550
4551 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004552 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004553 session_options->pooled_ice_credentials =
4554 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4555 RTC_FROM_HERE,
4556 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4557 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004558 session_options->offer_extmap_allow_mixed =
4559 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004560
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004561 if (configuration_.use_media_transport ||
4562 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004563 session_options->media_transport_settings =
4564 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4565 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004566
4567 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004568 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004569 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004570 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004571 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004572 if (!params) {
4573 continue;
4574 }
4575 options.transport_options.opaque_parameters = params;
4576 if ((use_datagram_transport_ &&
4577 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4578 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4579 (use_datagram_transport_for_data_channels_ &&
4580 options.type == cricket::MEDIA_TYPE_DATA)) {
4581 options.alt_protocol = params->protocol;
4582 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004583 }
4584 }
4585
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004586 // Allow fallback for using obsolete SCTP syntax.
4587 // Note that the default in |session_options| is true, while
4588 // the default in |options| is false.
4589 session_options->use_obsolete_sctp_sdp =
4590 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004591}
4592
4593void PeerConnection::GetOptionsForPlanBOffer(
4594 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4595 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004596 // Figure out transceiver directional preferences.
4597 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4598 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4599
4600 // By default, generate sendrecv/recvonly m= sections.
4601 bool recv_audio = true;
4602 bool recv_video = true;
4603
4604 // By default, only offer a new m= section if we have media to send with it.
4605 bool offer_new_audio_description = send_audio;
4606 bool offer_new_video_description = send_video;
4607 bool offer_new_data_description = HasDataChannels();
4608
4609 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004610 if (offer_answer_options.offer_to_receive_audio !=
4611 RTCOfferAnswerOptions::kUndefined) {
4612 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004613 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004614 offer_new_audio_description ||
4615 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004616 }
Steve Antondcc3c022017-12-22 16:02:54 -08004617 if (offer_answer_options.offer_to_receive_video !=
4618 RTCOfferAnswerOptions::kUndefined) {
4619 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004620 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004621 offer_new_video_description ||
4622 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004623 }
4624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004625 absl::optional<size_t> audio_index;
4626 absl::optional<size_t> video_index;
4627 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004628 // If a current description exists, generate m= sections in the same order,
4629 // using the first audio/video/data section that appears and rejecting
4630 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004631 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004632 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004633 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004634 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4635 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4636 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004637 }
4638
zhihuang1c378ed2017-08-17 14:10:50 -07004639 // Add audio/video/data m= sections to the end if needed.
4640 if (!audio_index && offer_new_audio_description) {
4641 session_options->media_description_options.push_back(
4642 cricket::MediaDescriptionOptions(
4643 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004644 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4645 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004646 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004647 }
zhihuang1c378ed2017-08-17 14:10:50 -07004648 if (!video_index && offer_new_video_description) {
4649 session_options->media_description_options.push_back(
4650 cricket::MediaDescriptionOptions(
4651 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004652 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4653 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004654 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004655 }
zhihuang1c378ed2017-08-17 14:10:50 -07004656 if (!data_index && offer_new_data_description) {
4657 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004658 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004659 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004660 }
4661
4662 cricket::MediaDescriptionOptions* audio_media_description_options =
4663 !audio_index ? nullptr
4664 : &session_options->media_description_options[*audio_index];
4665 cricket::MediaDescriptionOptions* video_media_description_options =
4666 !video_index ? nullptr
4667 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004668
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004669 AddPlanBRtpSenderOptions(GetSendersInternal(),
4670 audio_media_description_options,
4671 video_media_description_options,
4672 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004673}
4674
Steve Antondcc3c022017-12-22 16:02:54 -08004675static cricket::MediaDescriptionOptions
4676GetMediaDescriptionOptionsForTransceiver(
4677 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4678 transceiver,
4679 const std::string& mid) {
4680 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004681 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004682 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004683 media_description_options.codec_preferences =
4684 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004685 // This behavior is specified in JSEP. The gist is that:
4686 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4687 // sendrecv.
4688 // 2. If the MSID is included, then it must be included in any subsequent
4689 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004690 if (transceiver->stopped() ||
4691 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4692 !transceiver->internal()->has_ever_been_used_to_send())) {
4693 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004694 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004695
4696 cricket::SenderOptions sender_options;
4697 sender_options.track_id = transceiver->sender()->id();
4698 sender_options.stream_ids = transceiver->sender()->stream_ids();
4699
4700 // The following sets up RIDs and Simulcast.
4701 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004702 RtpParameters send_parameters =
4703 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004704 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4705 send_parameters.encodings.end(),
4706 [](const RtpEncodingParameters& encoding) {
4707 return !encoding.rid.empty();
4708 });
4709
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004710 std::vector<RidDescription> send_rids;
4711 SimulcastLayerList send_layers;
4712 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4713 if (encoding.rid.empty()) {
4714 continue;
4715 }
4716 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4717 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4718 }
4719
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004720 if (has_rids) {
4721 sender_options.rids = send_rids;
4722 }
4723
4724 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004725 // When RIDs are configured, we must set num_sim_layers to 0 to.
4726 // Otherwise, num_sim_layers must be 1 because either there is no
4727 // simulcast, or simulcast is acheived by munging the SDP.
4728 sender_options.num_sim_layers = has_rids ? 0 : 1;
4729 media_description_options.sender_options.push_back(sender_options);
4730
Steve Antondcc3c022017-12-22 16:02:54 -08004731 return media_description_options;
4732}
4733
Steve Anton5c72e712018-12-10 14:25:30 -08004734// Returns the ContentInfo at mline index |i|, or null if none exists.
4735static const ContentInfo* GetContentByIndex(
4736 const SessionDescriptionInterface* sdesc,
4737 size_t i) {
4738 if (!sdesc) {
4739 return nullptr;
4740 }
4741 const ContentInfos& contents = sdesc->description()->contents();
4742 return (i < contents.size() ? &contents[i] : nullptr);
4743}
4744
Steve Antondcc3c022017-12-22 16:02:54 -08004745void PeerConnection::GetOptionsForUnifiedPlanOffer(
4746 const RTCOfferAnswerOptions& offer_answer_options,
4747 cricket::MediaSessionOptions* session_options) {
4748 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4749 // Offers) and 5.2.2 (Subsequent Offers).
4750 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004751 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004752 const ContentInfos& local_contents =
4753 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004754 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004755 const ContentInfos& remote_contents =
4756 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004757 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004758 // The mline indices that can be recycled. New transceivers should reuse these
4759 // slots first.
4760 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004761 // First, go through each media section that exists in either the local or
4762 // remote description and generate a media section in this offer for the
4763 // associated transceiver. If a media section can be recycled, generate a
4764 // default, rejected media section here that can be later overwritten.
4765 for (size_t i = 0;
4766 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4767 // Either |local_content| or |remote_content| is non-null.
4768 const ContentInfo* local_content =
4769 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004770 const ContentInfo* current_local_content =
4771 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004772 const ContentInfo* remote_content =
4773 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004774 const ContentInfo* current_remote_content =
4775 GetContentByIndex(current_remote_description(), i);
4776 bool had_been_rejected =
4777 (current_local_content && current_local_content->rejected) ||
4778 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004779 const std::string& mid =
4780 (local_content ? local_content->name : remote_content->name);
4781 cricket::MediaType media_type =
4782 (local_content ? local_content->media_description()->type()
4783 : remote_content->media_description()->type());
4784 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4785 media_type == cricket::MEDIA_TYPE_VIDEO) {
4786 auto transceiver = GetAssociatedTransceiver(mid);
4787 RTC_CHECK(transceiver);
4788 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004789 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004790 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004791 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004792 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4793 RtpTransceiverDirection::kInactive,
4794 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004795 recycleable_mline_indices.push(i);
4796 } else {
4797 session_options->media_description_options.push_back(
4798 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4799 // CreateOffer shouldn't really cause any state changes in
4800 // PeerConnection, but we need a way to match new transceivers to new
4801 // media sections in SetLocalDescription and JSEP specifies this is done
4802 // by recording the index of the media section generated for the
4803 // transceiver in the offer.
4804 transceiver->internal()->set_mline_index(i);
4805 }
4806 } else {
4807 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004808 RTC_CHECK(GetDataMid());
4809 if (had_been_rejected || mid != *GetDataMid()) {
4810 session_options->media_description_options.push_back(
4811 GetMediaDescriptionOptionsForRejectedData(mid));
4812 } else {
4813 session_options->media_description_options.push_back(
4814 GetMediaDescriptionOptionsForActiveData(mid));
4815 }
Steve Antondcc3c022017-12-22 16:02:54 -08004816 }
4817 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004818
Steve Antondcc3c022017-12-22 16:02:54 -08004819 // Next, look for transceivers that are newly added (that is, are not stopped
4820 // and not associated). Reuse media sections marked as recyclable first,
4821 // otherwise append to the end of the offer. New media sections should be
4822 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004823 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004824 if (transceiver->mid() || transceiver->stopped()) {
4825 continue;
4826 }
4827 size_t mline_index;
4828 if (!recycleable_mline_indices.empty()) {
4829 mline_index = recycleable_mline_indices.front();
4830 recycleable_mline_indices.pop();
4831 session_options->media_description_options[mline_index] =
4832 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004833 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004834 } else {
4835 mline_index = session_options->media_description_options.size();
4836 session_options->media_description_options.push_back(
4837 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004838 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004839 }
4840 // See comment above for why CreateOffer changes the transceiver's state.
4841 transceiver->internal()->set_mline_index(mline_index);
4842 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004843 // Lastly, add a m-section if we have local data channels and an m section
4844 // does not already exist.
4845 if (!GetDataMid() && HasDataChannels()) {
4846 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004847 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004848 }
Steve Antondcc3c022017-12-22 16:02:54 -08004849}
4850
4851void PeerConnection::GetOptionsForAnswer(
4852 const RTCOfferAnswerOptions& offer_answer_options,
4853 cricket::MediaSessionOptions* session_options) {
4854 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4855
4856 if (IsUnifiedPlan()) {
4857 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4858 } else {
4859 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4860 }
4861
Steve Antonfa2260d2017-12-28 16:38:23 -08004862 // Intentionally unset the data channel type for RTP data channel. Otherwise
4863 // the RTP data channels would be successfully negotiated by default and the
4864 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4865 // We want to leave RTP data channels broken, so people won't try to use them.
4866 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4867 session_options->data_channel_type = data_channel_type();
4868 }
4869
Steve Antondcc3c022017-12-22 16:02:54 -08004870 // Apply ICE renomination flag.
4871 for (auto& options : session_options->media_description_options) {
4872 options.transport_options.enable_ice_renomination =
4873 configuration_.enable_ice_renomination;
4874 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004875
4876 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004877 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004878 session_options->pooled_ice_credentials =
4879 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4880 RTC_FROM_HERE,
4881 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4882 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004883
4884 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004885 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004886 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004887 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004888 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004889 if (!params) {
4890 continue;
4891 }
4892 options.transport_options.opaque_parameters = params;
4893 if ((use_datagram_transport_ &&
4894 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4895 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4896 (use_datagram_transport_for_data_channels_ &&
4897 options.type == cricket::MEDIA_TYPE_DATA)) {
4898 options.alt_protocol = params->protocol;
4899 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004900 }
4901 }
deadbeefab9b2d12015-10-14 11:33:11 -07004902}
4903
Steve Antondcc3c022017-12-22 16:02:54 -08004904void PeerConnection::GetOptionsForPlanBAnswer(
4905 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004906 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004907 // Figure out transceiver directional preferences.
4908 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4909 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4910
4911 // By default, generate sendrecv/recvonly m= sections. The direction is also
4912 // restricted by the direction in the offer.
4913 bool recv_audio = true;
4914 bool recv_video = true;
4915
4916 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004917 if (offer_answer_options.offer_to_receive_audio !=
4918 RTCOfferAnswerOptions::kUndefined) {
4919 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004920 }
Steve Antondcc3c022017-12-22 16:02:54 -08004921 if (offer_answer_options.offer_to_receive_video !=
4922 RTCOfferAnswerOptions::kUndefined) {
4923 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004924 }
4925
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004926 absl::optional<size_t> audio_index;
4927 absl::optional<size_t> video_index;
4928 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004929
4930 // Generate m= sections that match those in the offer.
4931 // Note that mediasession.cc will handle intersection our preferred
4932 // direction with the offered direction.
4933 GenerateMediaDescriptionOptions(
4934 remote_description(),
4935 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4936 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4937 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004938
4939 cricket::MediaDescriptionOptions* audio_media_description_options =
4940 !audio_index ? nullptr
4941 : &session_options->media_description_options[*audio_index];
4942 cricket::MediaDescriptionOptions* video_media_description_options =
4943 !video_index ? nullptr
4944 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004945
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004946 AddPlanBRtpSenderOptions(GetSendersInternal(),
4947 audio_media_description_options,
4948 video_media_description_options,
4949 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004950}
zhihuangaf388472016-11-02 16:49:48 -07004951
Steve Antondcc3c022017-12-22 16:02:54 -08004952void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4953 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4954 cricket::MediaSessionOptions* session_options) {
4955 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4956 // Answers) and 5.3.2 (Subsequent Answers).
4957 RTC_DCHECK(remote_description());
4958 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4959 for (const ContentInfo& content :
4960 remote_description()->description()->contents()) {
4961 cricket::MediaType media_type = content.media_description()->type();
4962 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4963 media_type == cricket::MEDIA_TYPE_VIDEO) {
4964 auto transceiver = GetAssociatedTransceiver(content.name);
4965 RTC_CHECK(transceiver);
4966 session_options->media_description_options.push_back(
4967 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4968 } else {
4969 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004970 // Reject all data sections if data channels are disabled.
4971 // Reject a data section if it has already been rejected.
4972 // Reject all data sections except for the first one.
4973 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4974 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004975 session_options->media_description_options.push_back(
4976 GetMediaDescriptionOptionsForRejectedData(content.name));
4977 } else {
4978 session_options->media_description_options.push_back(
4979 GetMediaDescriptionOptionsForActiveData(content.name));
4980 }
Steve Antondcc3c022017-12-22 16:02:54 -08004981 }
4982 }
htaa2a49d92016-03-04 02:51:39 -08004983}
4984
zhihuang1c378ed2017-08-17 14:10:50 -07004985void PeerConnection::GenerateMediaDescriptionOptions(
4986 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004987 RtpTransceiverDirection audio_direction,
4988 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004989 absl::optional<size_t>* audio_index,
4990 absl::optional<size_t>* video_index,
4991 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004992 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004993 for (const cricket::ContentInfo& content :
4994 session_desc->description()->contents()) {
4995 if (IsAudioContent(&content)) {
4996 // If we already have an audio m= section, reject this extra one.
4997 if (*audio_index) {
4998 session_options->media_description_options.push_back(
4999 cricket::MediaDescriptionOptions(
5000 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005001 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005002 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005003 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005004 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005005 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5006 content.name, audio_direction,
5007 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005008 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005009 }
5010 } else if (IsVideoContent(&content)) {
5011 // If we already have an video m= section, reject this extra one.
5012 if (*video_index) {
5013 session_options->media_description_options.push_back(
5014 cricket::MediaDescriptionOptions(
5015 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005016 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005017 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005018 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005019 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005020 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5021 content.name, video_direction,
5022 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005023 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005024 }
5025 } else {
5026 RTC_DCHECK(IsDataContent(&content));
5027 // If we already have an data m= section, reject this extra one.
5028 if (*data_index) {
5029 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005030 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005031 } else {
5032 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005033 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005034 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005035 }
5036 }
htaa2a49d92016-03-04 02:51:39 -08005037 }
deadbeefab9b2d12015-10-14 11:33:11 -07005038}
5039
Steve Antonfa2260d2017-12-28 16:38:23 -08005040cricket::MediaDescriptionOptions
5041PeerConnection::GetMediaDescriptionOptionsForActiveData(
5042 const std::string& mid) const {
5043 // Direction for data sections is meaningless, but legacy endpoints might
5044 // expect sendrecv.
5045 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5046 RtpTransceiverDirection::kSendRecv,
5047 /*stopped=*/false);
5048 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5049 return options;
5050}
5051
5052cricket::MediaDescriptionOptions
5053PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5054 const std::string& mid) const {
5055 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5056 RtpTransceiverDirection::kInactive,
5057 /*stopped=*/true);
5058 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5059 return options;
5060}
5061
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005062absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005063 switch (data_channel_type_) {
5064 case cricket::DCT_RTP:
5065 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005066 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005067 }
5068 return rtp_data_channel_->content_name();
5069 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005070 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005071 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5072 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5073 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005074 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005075 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005076 }
5077}
5078
Steve Anton4171afb2017-11-20 10:20:22 -08005079void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5080 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5081 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005082 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005083}
5084
Steve Anton4171afb2017-11-20 10:20:22 -08005085void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005086 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005087 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005088 cricket::MediaType media_type,
5089 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005090 RTC_DCHECK(!IsUnifiedPlan());
5091
Steve Anton4171afb2017-11-20 10:20:22 -08005092 std::vector<RtpSenderInfo>* current_senders =
5093 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005094
Steve Anton4171afb2017-11-20 10:20:22 -08005095 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005096 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005097 for (auto sender_it = current_senders->begin();
5098 sender_it != current_senders->end();
5099 /* incremented manually */) {
5100 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005101 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005102 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005103 std::string params_stream_id;
5104 if (params) {
5105 params_stream_id =
5106 (!params->first_stream_id().empty() ? params->first_stream_id()
5107 : kDefaultStreamId);
5108 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005109 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005110 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005111 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005112 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005113 sender_exists) {
5114 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005115 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005116 OnRemoteSenderRemoved(info, media_type);
5117 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005118 }
5119 }
5120
Steve Anton4171afb2017-11-20 10:20:22 -08005121 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005122 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005123 if (!params.has_ssrcs()) {
5124 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5125 // sender, this means it is coming from a Unified Plan endpoint,so we just
5126 // create a default.
5127 default_sender_needed = true;
5128 break;
5129 }
5130
Seth Hampson845e8782018-03-02 11:34:10 -08005131 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005132 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005133 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5134 // not supported in Plan B, we just take the first here and create the
5135 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005136 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005137 (!params.first_stream_id().empty() ? params.first_stream_id()
5138 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005139 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005140 uint32_t ssrc = params.first_ssrc();
5141
5142 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005143 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005144 if (!stream) {
5145 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005146 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005147 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005148 remote_streams_->AddStream(stream);
5149 new_streams->AddStream(stream);
5150 }
5151
Steve Anton4171afb2017-11-20 10:20:22 -08005152 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005153 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005154 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005155 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005156 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005157 }
5158 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005159
Steve Anton4171afb2017-11-20 10:20:22 -08005160 // Add default sender if necessary.
5161 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005162 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005163 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005164 if (!default_stream) {
5165 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005166 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005167 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005168 remote_streams_->AddStream(default_stream);
5169 new_streams->AddStream(default_stream);
5170 }
Steve Anton4171afb2017-11-20 10:20:22 -08005171 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5172 ? kDefaultAudioSenderId
5173 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005174 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005175 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005176 if (!default_sender_info) {
5177 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005178 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005179 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005180 }
5181 }
deadbeefab9b2d12015-10-14 11:33:11 -07005182}
5183
Steve Anton4171afb2017-11-20 10:20:22 -08005184void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5185 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005186 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5187 << " receiver for track_id=" << sender_info.sender_id
5188 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005189
Steve Anton3d954a62018-04-02 11:27:23 -07005190 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005191 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005192 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005193 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005194 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005195 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005196 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005197 }
5198}
5199
Steve Anton4171afb2017-11-20 10:20:22 -08005200void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5201 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005202 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5203 << " receiver for track_id=" << sender_info.sender_id
5204 << " and stream_id=" << sender_info.stream_id;
5205
Seth Hampson845e8782018-03-02 11:34:10 -08005206 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005207
Henrik Boström933d8b02017-10-10 10:05:16 -07005208 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005209 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005210 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5211 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005212 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005213 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005214 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005215 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005216 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005217 }
5218 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005219 // Stopping or destroying a VideoRtpReceiver will end the
5220 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005221 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005222 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005223 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005224 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005225 // There's no guarantee the track is still available, e.g. the track may
5226 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005227 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005228 }
5229 } else {
nisseede5da42017-01-12 05:15:36 -08005230 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005231 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005232 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005233 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005234 }
deadbeefab9b2d12015-10-14 11:33:11 -07005235}
5236
5237void PeerConnection::UpdateEndedRemoteMediaStreams() {
5238 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5239 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5240 MediaStreamInterface* stream = remote_streams_->at(i);
5241 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5242 streams_to_remove.push_back(stream);
5243 }
5244 }
5245
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005246 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005247 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005248 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005249 }
5250}
5251
Steve Anton4171afb2017-11-20 10:20:22 -08005252void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005253 const std::vector<cricket::StreamParams>& streams,
5254 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005255 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005256
Seth Hampson845e8782018-03-02 11:34:10 -08005257 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005258 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005259 for (auto sender_it = current_senders->begin();
5260 sender_it != current_senders->end();
5261 /* incremented manually */) {
5262 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005263 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005264 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5265 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005266 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005267 OnLocalSenderRemoved(info, media_type);
5268 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005269 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005270 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005271 }
5272 }
5273
Steve Anton4171afb2017-11-20 10:20:22 -08005274 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005275 for (const cricket::StreamParams& params : streams) {
5276 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005277 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005278 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005279 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005280 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005281 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005282 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005283 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005284 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005285 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005286 }
5287 }
5288}
5289
Steve Anton4171afb2017-11-20 10:20:22 -08005290void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5291 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005292 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005293 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005294 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005295 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5296 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005297 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005298 return;
5299 }
5300
deadbeeffac06552015-11-25 11:26:01 -08005301 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005302 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005303 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005304 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005305 }
deadbeeffac06552015-11-25 11:26:01 -08005306
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005307 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005308 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005309}
5310
Steve Anton4171afb2017-11-20 10:20:22 -08005311void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5312 cricket::MediaType media_type) {
5313 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005314 if (!sender) {
5315 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005316 // SessionDescriptions has been renegotiated.
5317 return;
5318 }
deadbeeffac06552015-11-25 11:26:01 -08005319
5320 // A sender has been removed from the SessionDescription but it's still
5321 // associated with the PeerConnection. This only occurs if the SDP doesn't
5322 // match with the calls to CreateSender, AddStream and RemoveStream.
5323 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005324 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005325 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005326 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005327 }
deadbeeffac06552015-11-25 11:26:01 -08005328
Steve Anton4171afb2017-11-20 10:20:22 -08005329 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005330}
5331
5332void PeerConnection::UpdateLocalRtpDataChannels(
5333 const cricket::StreamParamsVec& streams) {
5334 std::vector<std::string> existing_channels;
5335
5336 // Find new and active data channels.
5337 for (const cricket::StreamParams& params : streams) {
5338 // |it->sync_label| is actually the data channel label. The reason is that
5339 // we use the same naming of data channels as we do for
5340 // MediaStreams and Tracks.
5341 // For MediaStreams, the sync_label is the MediaStream label and the
5342 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005343 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005344 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005345 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005346 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005347 continue;
5348 }
5349 // Set the SSRC the data channel should use for sending.
5350 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5351 existing_channels.push_back(data_channel_it->first);
5352 }
5353
5354 UpdateClosingRtpDataChannels(existing_channels, true);
5355}
5356
5357void PeerConnection::UpdateRemoteRtpDataChannels(
5358 const cricket::StreamParamsVec& streams) {
5359 std::vector<std::string> existing_channels;
5360
5361 // Find new and active data channels.
5362 for (const cricket::StreamParams& params : streams) {
5363 // The data channel label is either the mslabel or the SSRC if the mslabel
5364 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005365 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005366 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005367 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005368 auto data_channel_it = rtp_data_channels_.find(label);
5369 if (data_channel_it == rtp_data_channels_.end()) {
5370 // This is a new data channel.
5371 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5372 } else {
5373 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5374 }
5375 existing_channels.push_back(label);
5376 }
5377
5378 UpdateClosingRtpDataChannels(existing_channels, false);
5379}
5380
5381void PeerConnection::UpdateClosingRtpDataChannels(
5382 const std::vector<std::string>& active_channels,
5383 bool is_local_update) {
5384 auto it = rtp_data_channels_.begin();
5385 while (it != rtp_data_channels_.end()) {
5386 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005387 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005388 ++it;
5389 continue;
5390 }
5391
5392 if (is_local_update) {
5393 data_channel->SetSendSsrc(0);
5394 } else {
5395 data_channel->RemotePeerRequestClose();
5396 }
5397
5398 if (data_channel->state() == DataChannel::kClosed) {
5399 rtp_data_channels_.erase(it);
5400 it = rtp_data_channels_.begin();
5401 } else {
5402 ++it;
5403 }
5404 }
5405}
5406
5407void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5408 uint32_t remote_ssrc) {
5409 rtc::scoped_refptr<DataChannel> channel(
5410 InternalCreateDataChannel(label, nullptr));
5411 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005412 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005413 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005414 return;
5415 }
5416 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005417 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5418 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005419 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005420}
5421
5422rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5423 const std::string& label,
5424 const InternalDataChannelInit* config) {
5425 if (IsClosed()) {
5426 return nullptr;
5427 }
Steve Anton75737c02017-11-06 10:37:17 -08005428 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005429 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005430 << "InternalCreateDataChannel: Data is not supported in this call.";
5431 return nullptr;
5432 }
5433 InternalDataChannelInit new_config =
5434 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005435 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005436 if (new_config.id < 0) {
5437 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005438 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005439 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005440 RTC_LOG(LS_ERROR)
5441 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005442 return nullptr;
5443 }
5444 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005445 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005446 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005447 return nullptr;
5448 }
5449 }
5450
Steve Anton75737c02017-11-06 10:37:17 -08005451 rtc::scoped_refptr<DataChannel> channel(
5452 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005453 if (!channel) {
5454 sid_allocator_.ReleaseSid(new_config.id);
5455 return nullptr;
5456 }
5457
5458 if (channel->data_channel_type() == cricket::DCT_RTP) {
5459 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005460 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5461 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005462 return nullptr;
5463 }
5464 rtp_data_channels_[channel->label()] = channel;
5465 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005466 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005467 sctp_data_channels_.push_back(channel);
5468 channel->SignalClosed.connect(this,
5469 &PeerConnection::OnSctpDataChannelClosed);
5470 }
5471
Steve Anton2d8609c2018-01-23 16:38:46 -08005472 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005473 return channel;
5474}
5475
5476bool PeerConnection::HasDataChannels() const {
5477 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5478}
5479
5480void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005481 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005482 for (const auto& channel : sctp_data_channels_) {
5483 if (channel->id() < 0) {
5484 int sid;
5485 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005486 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5487 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005488 continue;
5489 }
5490 channel->SetSctpSid(sid);
5491 }
5492 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005493 // Since closing modifies the list of channels, we have to do the actual
5494 // closing outside the loop.
5495 for (const auto& channel : channels_to_close) {
5496 channel->CloseAbruptly();
5497 }
deadbeefab9b2d12015-10-14 11:33:11 -07005498}
5499
5500void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005501 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005502 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5503 ++it) {
5504 if (it->get() == channel) {
5505 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005506 // After the closing procedure is done, it's safe to use this ID for
5507 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005508 sid_allocator_.ReleaseSid(channel->id());
5509 }
deadbeefbd292462015-12-14 18:15:29 -08005510 // Since this method is triggered by a signal from the DataChannel,
5511 // we can't free it directly here; we need to free it asynchronously.
5512 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005513 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005514 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5515 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005516 return;
5517 }
5518 }
5519}
5520
deadbeefab9b2d12015-10-14 11:33:11 -07005521void PeerConnection::OnDataChannelDestroyed() {
5522 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5523 // DataChannel may callback to us and try to modify the list.
5524 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5525 temp_rtp_dcs.swap(rtp_data_channels_);
5526 for (const auto& kv : temp_rtp_dcs) {
5527 kv.second->OnTransportChannelDestroyed();
5528 }
5529
5530 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5531 temp_sctp_dcs.swap(sctp_data_channels_);
5532 for (const auto& channel : temp_sctp_dcs) {
5533 channel->OnTransportChannelDestroyed();
5534 }
5535}
5536
5537void PeerConnection::OnDataChannelOpenMessage(
5538 const std::string& label,
5539 const InternalDataChannelInit& config) {
5540 rtc::scoped_refptr<DataChannel> channel(
5541 InternalCreateDataChannel(label, &config));
5542 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005543 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005544 return;
5545 }
5546
deadbeefa601f5c2016-06-06 14:27:39 -07005547 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5548 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005549 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005550 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005551}
5552
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005553bool PeerConnection::HandleOpenMessage_s(
5554 const cricket::ReceiveDataParams& params,
5555 const rtc::CopyOnWriteBuffer& buffer) {
5556 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5557 // Received OPEN message; parse and signal that a new data channel should
5558 // be created.
5559 std::string label;
5560 InternalDataChannelInit config;
5561 config.id = params.ssrc;
5562 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5563 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5564 << params.ssrc;
5565 return true;
5566 }
5567 config.open_handshake_role = InternalDataChannelInit::kAcker;
5568 OnDataChannelOpenMessage(label, config);
5569 return true;
5570 }
5571 return false;
5572}
5573
Steve Anton4171afb2017-11-20 10:20:22 -08005574rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5575PeerConnection::GetAudioTransceiver() const {
5576 // This method only works with Plan B SDP, where there is a single
5577 // audio/video transceiver.
5578 RTC_DCHECK(!IsUnifiedPlan());
5579 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005580 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005581 return transceiver;
5582 }
5583 }
5584 RTC_NOTREACHED();
5585 return nullptr;
5586}
5587
5588rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5589PeerConnection::GetVideoTransceiver() const {
5590 // This method only works with Plan B SDP, where there is a single
5591 // audio/video transceiver.
5592 RTC_DCHECK(!IsUnifiedPlan());
5593 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005594 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005595 return transceiver;
5596 }
5597 }
5598 RTC_NOTREACHED();
5599 return nullptr;
5600}
5601
5602// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5603// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005604bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005605 switch (type) {
5606 case cricket::MEDIA_TYPE_AUDIO:
5607 return !GetAudioTransceiver()->internal()->senders().empty();
5608 case cricket::MEDIA_TYPE_VIDEO:
5609 return !GetVideoTransceiver()->internal()->senders().empty();
5610 case cricket::MEDIA_TYPE_DATA:
5611 return false;
5612 }
5613 RTC_NOTREACHED();
5614 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005615}
5616
Steve Anton4171afb2017-11-20 10:20:22 -08005617rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5618PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005619 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005620 for (auto sender : transceiver->internal()->senders()) {
5621 if (sender->track() == track) {
5622 return sender;
5623 }
5624 }
5625 }
5626 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005627}
5628
Steve Anton4171afb2017-11-20 10:20:22 -08005629rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5630PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005631 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005632 for (auto sender : transceiver->internal()->senders()) {
5633 if (sender->id() == sender_id) {
5634 return sender;
5635 }
5636 }
5637 }
5638 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005639}
5640
Steve Anton4171afb2017-11-20 10:20:22 -08005641rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5642PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005643 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005644 for (auto receiver : transceiver->internal()->receivers()) {
5645 if (receiver->id() == receiver_id) {
5646 return receiver;
5647 }
5648 }
5649 }
5650 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005651}
5652
Steve Anton4171afb2017-11-20 10:20:22 -08005653std::vector<PeerConnection::RtpSenderInfo>*
5654PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5655 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5656 media_type == cricket::MEDIA_TYPE_VIDEO);
5657 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5658 ? &remote_audio_sender_infos_
5659 : &remote_video_sender_infos_;
5660}
5661
5662std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005663 cricket::MediaType media_type) {
5664 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5665 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005666 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5667 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005668}
5669
Steve Anton4171afb2017-11-20 10:20:22 -08005670const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5671 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005672 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005673 const std::string sender_id) const {
5674 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005675 if (sender_info.stream_id == stream_id &&
5676 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005677 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005678 }
5679 }
5680 return nullptr;
5681}
5682
5683DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5684 for (const auto& channel : sctp_data_channels_) {
5685 if (channel->id() == sid) {
5686 return channel;
5687 }
5688 }
5689 return nullptr;
5690}
5691
Karl Wibergfb3be392019-03-22 14:13:22 +01005692PeerConnection::InitializePortAllocatorResult
5693PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005694 const cricket::ServerAddresses& stun_servers,
5695 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005696 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005697 RTC_DCHECK_RUN_ON(network_thread());
5698
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005699 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005700 // To handle both internal and externally created port allocator, we will
5701 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005702 int port_allocator_flags = port_allocator_->flags();
5703 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5704 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5705 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005706 // If the disable-IPv6 flag was specified, we'll not override it
5707 // by experiment.
5708 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005709 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005710 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5711 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005712 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005713 }
5714
zhihuangb09b3f92017-03-07 14:40:51 -08005715 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005716 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005717 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005718 }
5719
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005720 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005721 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005722 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005723 }
5724
honghaiz60347052016-05-31 18:29:12 -07005725 if (configuration.candidate_network_policy ==
5726 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005727 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005728 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005729 }
5730
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005731 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005732 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005733 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5734 }
5735
Karl Wibergfb3be392019-03-22 14:13:22 +01005736 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005737 // No step delay is used while allocating ports.
5738 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005739 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005740 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005741 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005742
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005743 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005744 for (auto& turn_server : turn_servers_copy) {
5745 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005746 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005747 // Call this last since it may create pooled allocator sessions using the
5748 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005749 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005750 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005751 configuration.ice_candidate_pool_size,
5752 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005753 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005754
5755 InitializePortAllocatorResult res;
5756 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5757 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005758}
5759
deadbeef91dd5672016-05-18 16:55:30 -07005760bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005761 const cricket::ServerAddresses& stun_servers,
5762 const std::vector<cricket::RelayServerConfig>& turn_servers,
5763 IceTransportsType type,
5764 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005765 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005766 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005767 absl::optional<int> stun_candidate_keepalive_interval,
5768 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005769 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005770 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005771 // According to JSEP, after setLocalDescription, changing the candidate pool
5772 // size is not allowed, and changing the set of ICE servers will not result
5773 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005774 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005775 port_allocator_->FreezeCandidatePool();
5776 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005777 // Add the custom tls turn servers if they exist.
5778 auto turn_servers_copy = turn_servers;
5779 for (auto& turn_server : turn_servers_copy) {
5780 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5781 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005782 // Call this last since it may create pooled allocator sessions using the
5783 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005784 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005785 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005786 turn_port_prune_policy, turn_customizer,
5787 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005788}
5789
Steve Antonba818672017-11-06 10:21:57 -08005790cricket::ChannelManager* PeerConnection::channel_manager() const {
5791 return factory_->channel_manager();
5792}
5793
Elad Alon99c3fe52017-10-13 16:29:40 +02005794bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005795 std::unique_ptr<RtcEventLogOutput> output,
5796 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005797 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005798 if (!event_log_) {
5799 return false;
5800 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005801 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005802}
5803
5804void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005805 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005806 if (event_log_) {
5807 event_log_->StopLogging();
5808 }
ivoc14d5dbe2016-07-04 07:06:55 -07005809}
nisseeaabdf62017-05-05 02:23:02 -07005810
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005811cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005812 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005813 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005814 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005815 if (channel && channel->content_name() == content_name) {
5816 return channel;
5817 }
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819 if (rtp_data_channel() &&
5820 rtp_data_channel()->content_name() == content_name) {
5821 return rtp_data_channel();
5822 }
5823 return nullptr;
5824}
5825
5826bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005828 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005829 RTC_LOG(LS_INFO)
5830 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005831 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005832 return false;
5833 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005834 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005835 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005836 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005837 return false;
5838 }
5839
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005840 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005841 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005842 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005843 if (!dtls_role && is_caller_.has_value()) {
5844 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5845 }
Zhi Huange830e682018-03-30 10:48:35 -07005846 *role = *dtls_role;
5847 return true;
5848 }
5849 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005850}
5851
5852bool PeerConnection::GetSslRole(const std::string& content_name,
5853 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005854 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005855 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005856 RTC_LOG(LS_INFO)
5857 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005858 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005859 return false;
5860 }
5861
Zhi Huange830e682018-03-30 10:48:35 -07005862 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5863 if (dtls_role) {
5864 *role = *dtls_role;
5865 return true;
5866 }
5867 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005868}
5869
Steve Antonf8470812017-12-04 10:46:21 -08005870void PeerConnection::SetSessionError(SessionError error,
5871 const std::string& error_desc) {
5872 RTC_DCHECK_RUN_ON(signaling_thread());
5873 if (error != session_error_) {
5874 session_error_ = error;
5875 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005876 }
5877}
5878
Zhi Huange830e682018-03-30 10:48:35 -07005879RTCError PeerConnection::UpdateSessionState(
5880 SdpType type,
5881 cricket::ContentSource source,
5882 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005883 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005884
5885 // If there's already a pending error then no state transition should happen.
5886 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005887 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005888
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005889 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005890 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005891 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005892 }
5893
5894 // Update the signaling state according to the specified state machine (see
5895 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005896 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005897 ChangeSignalingState(source == cricket::CS_LOCAL
5898 ? PeerConnectionInterface::kHaveLocalOffer
5899 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005900 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005901 ChangeSignalingState(source == cricket::CS_LOCAL
5902 ? PeerConnectionInterface::kHaveLocalPrAnswer
5903 : PeerConnectionInterface::kHaveRemotePrAnswer);
5904 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005905 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005906 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03005907 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005908 }
5909
5910 // Update internal objects according to the session description's media
5911 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005912 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005913 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005914 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005915 }
5916
Steve Anton8a006912017-12-04 15:25:56 -08005917 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005918}
5919
Steve Anton8a006912017-12-04 15:25:56 -08005920RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005921 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005922 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005923 const SessionDescriptionInterface* sdesc =
5924 (source == cricket::CS_LOCAL ? local_description()
5925 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005926 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005927
5928 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005929 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005930 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005931 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005932 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005933 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005934 continue;
5935 }
5936 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005937 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005938 if (!content_desc) {
5939 continue;
5940 }
5941 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005942 bool success = (source == cricket::CS_LOCAL)
5943 ? channel->SetLocalContent(content_desc, type, &error)
5944 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005945 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005946 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005947 }
5948 }
5949
5950 // If using the RtpDataChannel, push down the new SDP section for it too.
5951 if (rtp_data_channel_) {
5952 const ContentInfo* data_content =
5953 cricket::GetFirstDataContent(sdesc->description());
5954 if (data_content && !data_content->rejected) {
5955 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005956 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005957 if (data_desc) {
5958 std::string error;
5959 bool success =
5960 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005961 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005962 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005963 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005964 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005965 }
Steve Anton75737c02017-11-06 10:37:17 -08005966 }
5967 }
5968 }
Steve Antoned10bd92017-12-05 10:52:59 -08005969
Steve Anton75737c02017-11-06 10:37:17 -08005970 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5971 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005972 if (sctp_mid_ && local_description() && remote_description()) {
5973 rtc::scoped_refptr<SctpTransport> sctp_transport =
5974 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005975 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5976 local_description()->description());
5977 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5978 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005979 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005980 int max_message_size;
5981 // A remote max message size of zero means "any size supported".
5982 // We configure the connection with our own max message size.
5983 if (remote_sctp_description->max_message_size() == 0) {
5984 max_message_size = local_sctp_description->max_message_size();
5985 } else {
5986 max_message_size =
5987 std::min(local_sctp_description->max_message_size(),
5988 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005989 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005990 sctp_transport->Start(local_sctp_description->port(),
5991 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005992 }
Steve Anton75737c02017-11-06 10:37:17 -08005993 }
Steve Antoned10bd92017-12-05 10:52:59 -08005994
Steve Anton8a006912017-12-04 15:25:56 -08005995 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005996}
5997
Steve Anton8a006912017-12-04 15:25:56 -08005998RTCError PeerConnection::PushdownTransportDescription(
5999 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006000 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006001 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006002
Zhi Huange830e682018-03-30 10:48:35 -07006003 if (source == cricket::CS_LOCAL) {
6004 const SessionDescriptionInterface* sdesc = local_description();
6005 RTC_DCHECK(sdesc);
6006 return transport_controller_->SetLocalDescription(type,
6007 sdesc->description());
6008 } else {
6009 const SessionDescriptionInterface* sdesc = remote_description();
6010 RTC_DCHECK(sdesc);
6011 return transport_controller_->SetRemoteDescription(type,
6012 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
Steve Anton75737c02017-11-06 10:37:17 -08006014}
6015
6016bool PeerConnection::GetTransportDescription(
6017 const SessionDescription* description,
6018 const std::string& content_name,
6019 cricket::TransportDescription* tdesc) {
6020 if (!description || !tdesc) {
6021 return false;
6022 }
6023 const TransportInfo* transport_info =
6024 description->GetTransportInfoByName(content_name);
6025 if (!transport_info) {
6026 return false;
6027 }
6028 *tdesc = transport_info->description;
6029 return true;
6030}
6031
Steve Anton75737c02017-11-06 10:37:17 -08006032cricket::IceConfig PeerConnection::ParseIceConfig(
6033 const PeerConnectionInterface::RTCConfiguration& config) const {
6034 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006035 switch (config.continual_gathering_policy) {
6036 case PeerConnectionInterface::GATHER_ONCE:
6037 gathering_policy = cricket::GATHER_ONCE;
6038 break;
6039 case PeerConnectionInterface::GATHER_CONTINUALLY:
6040 gathering_policy = cricket::GATHER_CONTINUALLY;
6041 break;
6042 default:
6043 RTC_NOTREACHED();
6044 gathering_policy = cricket::GATHER_ONCE;
6045 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006046
Steve Anton75737c02017-11-06 10:37:17 -08006047 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006048 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6049 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006050 ice_config.prioritize_most_likely_candidate_pairs =
6051 config.prioritize_most_likely_ice_candidate_pairs;
6052 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006053 RTCConfigurationToIceConfigOptionalInt(
6054 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006055 ice_config.continual_gathering_policy = gathering_policy;
6056 ice_config.presume_writable_when_fully_relayed =
6057 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006058 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6059 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006060 ice_config.ice_check_interval_strong_connectivity =
6061 config.ice_check_interval_strong_connectivity;
6062 ice_config.ice_check_interval_weak_connectivity =
6063 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006064 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006065 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6066 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006067 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006068 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006069 ice_config.regather_all_networks_interval_range =
6070 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006071 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006072 return ice_config;
6073}
6074
Steve Anton75737c02017-11-06 10:37:17 -08006075bool PeerConnection::SendData(const cricket::SendDataParams& params,
6076 const rtc::CopyOnWriteBuffer& payload,
6077 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006078 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006079 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006080 SendDataParams send_params;
6081 send_params.type = ToWebrtcDataMessageType(params.type);
6082 send_params.ordered = params.ordered;
6083 if (params.max_rtx_count >= 0) {
6084 send_params.max_rtx_count = params.max_rtx_count;
6085 } else if (params.max_rtx_ms >= 0) {
6086 send_params.max_rtx_ms = params.max_rtx_ms;
6087 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006088
6089 RTCError error = network_thread()->Invoke<RTCError>(
6090 RTC_FROM_HERE, [this, params, send_params, payload] {
6091 return data_channel_transport_->SendData(params.sid, send_params,
6092 payload);
6093 });
6094
6095 if (error.ok()) {
6096 *result = cricket::SendDataResult::SDR_SUCCESS;
6097 return true;
6098 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6099 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6100 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6101 *result = cricket::SendDataResult::SDR_BLOCK;
6102 return false;
6103 }
6104 *result = cricket::SendDataResult::SDR_ERROR;
6105 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006106 } else if (rtp_data_channel_) {
6107 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006108 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006109 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6110 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006111}
6112
6113bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006114 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006115 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006116 // Don't log an error here, because DataChannels are expected to call
6117 // ConnectDataChannel in this state. It's the only way to initially tell
6118 // whether or not the underlying transport is ready.
6119 return false;
6120 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006121 if (data_channel_transport_) {
6122 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6123 &DataChannel::OnChannelReady);
6124 SignalDataChannelTransportReceivedData_s.connect(
6125 webrtc_data_channel, &DataChannel::OnDataReceived);
6126 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006127 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006128 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006129 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006130 }
6131 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006132 rtp_data_channel_->SignalReadyToSendData.connect(
6133 webrtc_data_channel, &DataChannel::OnChannelReady);
6134 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6135 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006136 }
Steve Anton75737c02017-11-06 10:37:17 -08006137 return true;
6138}
6139
6140void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006141 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006142 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006143 RTC_LOG(LS_ERROR)
6144 << "DisconnectDataChannel called when rtp_data_channel_ and "
6145 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006146 return;
6147 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006148 if (data_channel_transport_) {
6149 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6150 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6151 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6152 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6153 }
6154 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006155 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6156 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006157 }
Steve Anton75737c02017-11-06 10:37:17 -08006158}
6159
6160void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006161 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006162 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6163 if (data_channel_transport_) {
6164 data_channel_transport_->OpenChannel(sid);
6165 }
6166 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006167 }
Steve Anton75737c02017-11-06 10:37:17 -08006168}
6169
6170void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006171 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006172 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6173 if (data_channel_transport_) {
6174 data_channel_transport_->CloseChannel(sid);
6175 }
6176 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006177 }
Steve Anton75737c02017-11-06 10:37:17 -08006178}
6179
6180bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006181 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006182 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006183 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006184}
6185
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006186void PeerConnection::OnDataReceived(int channel_id,
6187 DataMessageType type,
6188 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006189 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006190 cricket::ReceiveDataParams params;
6191 params.sid = channel_id;
6192 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006193 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006194 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6195 RTC_DCHECK_RUN_ON(signaling_thread());
6196 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006197 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006198 }
6199 });
6200}
6201
6202void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006203 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006204 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006205 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6206 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006207 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006208 });
6209}
6210
6211void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006212 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006213 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006214 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6215 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006216 SignalDataChannelTransportChannelClosed_s(channel_id);
6217 });
6218}
6219
6220void PeerConnection::OnReadyToSend() {
6221 RTC_DCHECK_RUN_ON(network_thread());
6222 data_channel_transport_invoker_->AsyncInvoke<void>(
6223 RTC_FROM_HERE, signaling_thread(), [this] {
6224 RTC_DCHECK_RUN_ON(signaling_thread());
6225 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006226 SignalDataChannelTransportWritable_s(
6227 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006228 });
6229}
6230
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006231absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006232 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006233 if (sctp_mid_ && transport_controller_) {
6234 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6235 if (dtls_transport) {
6236 return dtls_transport->transport_name();
6237 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006238 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006239 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006240 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006241}
6242
Qingsi Wang72a43a12018-02-20 16:03:18 -08006243cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6244 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006245 network_thread()->Invoke<void>(
6246 RTC_FROM_HERE,
6247 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6248 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006249 return candidate_states_list;
6250}
6251
Steve Anton5dfde182018-02-06 10:34:40 -08006252std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6253 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006254 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006255 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006256 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006257 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006258 if (channel) {
6259 transport_names_by_mid[channel->content_name()] =
6260 channel->transport_name();
6261 }
Steve Anton75737c02017-11-06 10:37:17 -08006262 }
Steve Anton5dfde182018-02-06 10:34:40 -08006263 if (rtp_data_channel_) {
6264 transport_names_by_mid[rtp_data_channel_->content_name()] =
6265 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006266 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006267 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006268 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006269 RTC_DCHECK(transport_name);
6270 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006271 }
Steve Anton5dfde182018-02-06 10:34:40 -08006272 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006273}
6274
Steve Anton5dfde182018-02-06 10:34:40 -08006275std::map<std::string, cricket::TransportStats>
6276PeerConnection::GetTransportStatsByNames(
6277 const std::set<std::string>& transport_names) {
6278 if (!network_thread()->IsCurrent()) {
6279 return network_thread()
6280 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6281 RTC_FROM_HERE,
6282 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006283 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006284 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006285 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6286 for (const std::string& transport_name : transport_names) {
6287 cricket::TransportStats transport_stats;
6288 bool success =
6289 transport_controller_->GetStats(transport_name, &transport_stats);
6290 if (success) {
6291 transport_stats_by_name[transport_name] = std::move(transport_stats);
6292 } else {
6293 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6294 << transport_name;
6295 }
6296 }
6297 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006298}
6299
6300bool PeerConnection::GetLocalCertificate(
6301 const std::string& transport_name,
6302 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006303 if (!certificate) {
6304 return false;
6305 }
6306 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6307 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006308}
6309
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006310std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006311 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006312 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006313}
6314
6315cricket::DataChannelType PeerConnection::data_channel_type() const {
6316 return data_channel_type_;
6317}
6318
6319bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006320 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006321 return pending_ice_restarts_.find(content_name) !=
6322 pending_ice_restarts_.end();
6323}
6324
Steve Anton75737c02017-11-06 10:37:17 -08006325bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6326 return transport_controller_->NeedsIceRestart(content_name);
6327}
6328
6329void PeerConnection::OnCertificateReady(
6330 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6331 transport_controller_->SetLocalCertificate(certificate);
6332}
6333
6334void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006335 SetSessionError(SessionError::kTransport,
6336 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006337}
6338
Alex Loiko9289eda2018-11-23 16:18:59 +00006339void PeerConnection::OnTransportControllerConnectionState(
6340 cricket::IceConnectionState state) {
6341 switch (state) {
6342 case cricket::kIceConnectionConnecting:
6343 // If the current state is Connected or Completed, then there were
6344 // writable channels but now there are not, so the next state must
6345 // be Disconnected.
6346 // kIceConnectionConnecting is currently used as the default,
6347 // un-connected state by the TransportController, so its only use is
6348 // detecting disconnections.
6349 if (ice_connection_state_ ==
6350 PeerConnectionInterface::kIceConnectionConnected ||
6351 ice_connection_state_ ==
6352 PeerConnectionInterface::kIceConnectionCompleted) {
6353 SetIceConnectionState(
6354 PeerConnectionInterface::kIceConnectionDisconnected);
6355 }
6356 break;
6357 case cricket::kIceConnectionFailed:
6358 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6359 break;
6360 case cricket::kIceConnectionConnected:
6361 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6362 "all transports are writable.";
6363 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6364 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6365 break;
6366 case cricket::kIceConnectionCompleted:
6367 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6368 "all transports are complete.";
6369 if (ice_connection_state_ !=
6370 PeerConnectionInterface::kIceConnectionConnected) {
6371 // If jumping directly from "checking" to "connected",
6372 // signal "connected" first.
6373 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6374 }
6375 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6376 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6377 ReportTransportStats();
6378 break;
6379 default:
6380 RTC_NOTREACHED();
6381 }
6382}
6383
Steve Anton75737c02017-11-06 10:37:17 -08006384void PeerConnection::OnTransportControllerCandidatesGathered(
6385 const std::string& transport_name,
6386 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006387 int sdp_mline_index;
6388 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006389 RTC_LOG(LS_ERROR)
6390 << "OnTransportControllerCandidatesGathered: content name "
6391 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006392 return;
6393 }
6394
6395 for (cricket::Candidates::const_iterator citer = candidates.begin();
6396 citer != candidates.end(); ++citer) {
6397 // Use transport_name as the candidate media id.
6398 std::unique_ptr<JsepIceCandidate> candidate(
6399 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6400 if (local_description()) {
6401 mutable_local_description()->AddCandidate(candidate.get());
6402 }
6403 OnIceCandidate(std::move(candidate));
6404 }
6405}
6406
Eldar Relloda13ea22019-06-01 12:23:43 +03006407void PeerConnection::OnTransportControllerCandidateError(
6408 const cricket::IceCandidateErrorEvent& event) {
6409 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6410 event.error_text);
6411}
6412
Steve Anton75737c02017-11-06 10:37:17 -08006413void PeerConnection::OnTransportControllerCandidatesRemoved(
6414 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006415 // Sanity check.
6416 for (const cricket::Candidate& candidate : candidates) {
6417 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006418 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006419 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006420 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006421 return;
6422 }
6423 }
6424
6425 if (local_description()) {
6426 mutable_local_description()->RemoveCandidates(candidates);
6427 }
6428 OnIceCandidatesRemoved(candidates);
6429}
6430
Alex Drake00c7ecf2019-08-06 10:54:47 -07006431void PeerConnection::OnTransportControllerCandidateChanged(
6432 const cricket::CandidatePairChangeEvent& event) {
6433 OnSelectedCandidatePairChanged(event);
6434}
6435
Steve Anton75737c02017-11-06 10:37:17 -08006436void PeerConnection::OnTransportControllerDtlsHandshakeError(
6437 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006438 RTC_HISTOGRAM_ENUMERATION(
6439 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6440 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006441}
6442
Steve Antoned10bd92017-12-05 10:52:59 -08006443void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006444 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006445 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006446 if (channel && !channel->enabled()) {
6447 channel->Enable(true);
6448 }
Steve Anton75737c02017-11-06 10:37:17 -08006449 }
6450
Steve Anton4171afb2017-11-20 10:20:22 -08006451 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006452 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006453 }
Steve Anton75737c02017-11-06 10:37:17 -08006454}
6455
6456// Returns the media index for a local ice candidate given the content name.
6457bool PeerConnection::GetLocalCandidateMediaIndex(
6458 const std::string& content_name,
6459 int* sdp_mline_index) {
6460 if (!local_description() || !sdp_mline_index) {
6461 return false;
6462 }
6463
6464 bool content_found = false;
6465 const ContentInfos& contents = local_description()->description()->contents();
6466 for (size_t index = 0; index < contents.size(); ++index) {
6467 if (contents[index].name == content_name) {
6468 *sdp_mline_index = static_cast<int>(index);
6469 content_found = true;
6470 break;
6471 }
6472 }
6473 return content_found;
6474}
6475
6476bool PeerConnection::UseCandidatesInSessionDescription(
6477 const SessionDescriptionInterface* remote_desc) {
6478 if (!remote_desc) {
6479 return true;
6480 }
6481 bool ret = true;
6482
6483 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6484 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6485 for (size_t n = 0; n < candidates->count(); ++n) {
6486 const IceCandidateInterface* candidate = candidates->at(n);
6487 bool valid = false;
6488 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6489 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006490 RTC_LOG(LS_INFO)
6491 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006492 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006493 }
6494 continue;
6495 }
6496 ret = UseCandidate(candidate);
6497 if (!ret) {
6498 break;
6499 }
6500 }
6501 }
6502 return ret;
6503}
6504
6505bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006506 RTCErrorOr<const cricket::ContentInfo*> result =
6507 FindContentInfo(remote_description(), candidate);
6508 if (!result.ok()) {
6509 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6510 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006511 return false;
6512 }
Steve Anton75737c02017-11-06 10:37:17 -08006513 std::vector<cricket::Candidate> candidates;
6514 candidates.push_back(candidate->candidate());
6515 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006516 RTCError error = transport_controller_->AddRemoteCandidates(
6517 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006518 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006519 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006520 // Candidates successfully submitted for checking.
6521 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6522 ice_connection_state_ ==
6523 PeerConnectionInterface::kIceConnectionDisconnected) {
6524 // If state is New, then the session has just gotten its first remote ICE
6525 // candidates, so go to Checking.
6526 // If state is Disconnected, the session is re-using old candidates or
6527 // receiving additional ones, so go to Checking.
6528 // If state is Connected, stay Connected.
6529 // TODO(bemasc): If state is Connected, and the new candidates are for a
6530 // newly added transport, then the state actually _should_ move to
6531 // checking. Add a way to distinguish that case.
6532 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6533 }
6534 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006535 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006536 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006537 }
6538 return true;
6539}
6540
Guido Urdaneta41633172019-05-23 20:12:29 +02006541RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6542 const SessionDescriptionInterface* description,
6543 const IceCandidateInterface* candidate) {
6544 if (candidate->sdp_mline_index() >= 0) {
6545 size_t mediacontent_index =
6546 static_cast<size_t>(candidate->sdp_mline_index());
6547 size_t content_size = description->description()->contents().size();
6548 if (mediacontent_index < content_size) {
6549 return &description->description()->contents()[mediacontent_index];
6550 } else {
6551 return RTCError(RTCErrorType::INVALID_RANGE,
6552 "Media line index (" +
6553 rtc::ToString(candidate->sdp_mline_index()) +
6554 ") out of range (number of mlines: " +
6555 rtc::ToString(content_size) + ").");
6556 }
6557 } else if (!candidate->sdp_mid().empty()) {
6558 auto& contents = description->description()->contents();
6559 auto it = absl::c_find_if(
6560 contents, [candidate](const cricket::ContentInfo& content_info) {
6561 return content_info.mid() == candidate->sdp_mid();
6562 });
6563 if (it == contents.end()) {
6564 return RTCError(
6565 RTCErrorType::INVALID_PARAMETER,
6566 "Mid " + candidate->sdp_mid() +
6567 " specified but no media section with that mid found.");
6568 } else {
6569 return &*it;
6570 }
6571 }
6572
6573 return RTCError(RTCErrorType::INVALID_PARAMETER,
6574 "Neither sdp_mline_index nor sdp_mid specified.");
6575}
6576
Steve Anton75737c02017-11-06 10:37:17 -08006577void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006578 // Destroy video channel first since it may have a pointer to the
6579 // voice channel.
6580 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006581 if (!video_info || video_info->rejected) {
6582 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006583 }
6584
Steve Anton6fec8802017-12-04 10:37:29 -08006585 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6586 if (!audio_info || audio_info->rejected) {
6587 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006588 }
6589
6590 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6591 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006592 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006593 }
6594}
6595
Steve Antondcc3c022017-12-22 16:02:54 -08006596RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6597 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006598 const cricket::ContentGroup* bundle_group = nullptr;
6599 if (configuration_.bundle_policy ==
6600 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006601 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006602 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6604 "max-bundle configured but session description "
6605 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006606 }
6607 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006608 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006609}
6610
6611RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006612 // Creating the media channels. Transports should already have been created
6613 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006614 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006615 if (voice && !voice->rejected &&
6616 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006617 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006618 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006619 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6620 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006621 }
6622 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6623 }
6624
Steve Antondcc3c022017-12-22 16:02:54 -08006625 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006626 if (video && !video->rejected &&
6627 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006628 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006629 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006630 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6631 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006632 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006633 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006634 }
6635
Steve Antondcc3c022017-12-22 16:02:54 -08006636 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006637 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006638 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006639 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006640 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6641 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006642 }
6643 }
6644
Steve Anton8a006912017-12-04 15:25:56 -08006645 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006646}
6647
Steve Anton4171afb2017-11-20 10:20:22 -08006648// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006649cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006650 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006651 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006652 MediaTransportConfig media_transport_config =
6653 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006654
Steve Anton75737c02017-11-06 10:37:17 -08006655 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006656 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006657 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6658 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006659 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006660 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006661 }
Steve Anton75737c02017-11-06 10:37:17 -08006662 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6663 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006664 voice_channel->SignalSentPacket.connect(this,
6665 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006666 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006667
Steve Antoneda6ccd2017-12-04 10:21:55 -08006668 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006669}
6670
Steve Anton4171afb2017-11-20 10:20:22 -08006671// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006672cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006673 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006674 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006675 MediaTransportConfig media_transport_config =
6676 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006677
Steve Anton75737c02017-11-06 10:37:17 -08006678 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006679 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006680 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6681 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006682 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006683 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006684 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006685 }
Steve Anton75737c02017-11-06 10:37:17 -08006686 video_channel->SignalDtlsSrtpSetupFailure.connect(
6687 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006688 video_channel->SignalSentPacket.connect(this,
6689 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006690 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006691
Steve Antoneda6ccd2017-12-04 10:21:55 -08006692 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006693}
6694
Zhi Huange830e682018-03-30 10:48:35 -07006695bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006696 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006697 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006698 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006699 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6700 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006701 if (!network_thread()->Invoke<bool>(
6702 RTC_FROM_HERE,
6703 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6704 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006705 return false;
6706 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006707
6708 // All non-RTP data channels must initialize |sctp_data_channels_|.
6709 for (const auto& channel : sctp_data_channels_) {
6710 channel->OnTransportChannelCreated();
6711 }
6712 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006713 case cricket::DCT_RTP:
6714 default:
6715 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6716 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6717 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006718 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006719 if (!rtp_data_channel_) {
6720 return false;
6721 }
6722 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6723 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6724 rtp_data_channel_->SignalSentPacket.connect(
6725 this, &PeerConnection::OnSentPacket_w);
6726 rtp_data_channel_->SetRtpTransport(rtp_transport);
6727 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006728 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006729 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006730}
6731
6732Call::Stats PeerConnection::GetCallStats() {
6733 if (!worker_thread()->IsCurrent()) {
6734 return worker_thread()->Invoke<Call::Stats>(
6735 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6736 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006737 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006738 if (call_) {
6739 return call_->GetStats();
6740 } else {
6741 return Call::Stats();
6742 }
6743}
6744
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006745bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006746 DataChannelTransportInterface* transport =
6747 transport_controller_->GetDataChannelTransport(mid);
6748 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006749 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006750 << "Data channel transport is not available for data channels, mid="
6751 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006752 return false;
6753 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006754 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006755
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006756 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02006757 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006758 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006759
6760 // Note: setting the data sink and checking initial state must be done last,
6761 // after setting up the data channel. Setting the data sink may trigger
6762 // callbacks to PeerConnection which require the transport to be completely
6763 // set up (eg. OnReadyToSend()).
6764 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006765 return true;
6766}
6767
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006768void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006769 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006770 return;
6771 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006772 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6773 << *sctp_mid_;
6774
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006775 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6776 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006777 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00006778 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006779 if (data_channel_transport_) {
6780 data_channel_transport_->SetDataSink(nullptr);
6781 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006782 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006783}
6784
Steve Anton75737c02017-11-06 10:37:17 -08006785// Returns false if bundle is enabled and rtcp_mux is disabled.
6786bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6787 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6788 if (!bundle_enabled)
6789 return true;
6790
6791 const cricket::ContentGroup* bundle_group =
6792 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6793 RTC_DCHECK(bundle_group != NULL);
6794
6795 const cricket::ContentInfos& contents = desc->contents();
6796 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6797 citer != contents.end(); ++citer) {
6798 const cricket::ContentInfo* content = (&*citer);
6799 RTC_DCHECK(content != NULL);
6800 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006801 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006802 if (!HasRtcpMuxEnabled(content))
6803 return false;
6804 }
6805 }
6806 // RTCP-MUX is enabled in all the contents.
6807 return true;
6808}
6809
6810bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006811 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006812}
6813
Steve Anton06817cd2018-12-18 15:55:30 -08006814static RTCError ValidateMids(const cricket::SessionDescription& description) {
6815 std::set<std::string> mids;
6816 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006817 if (content.name.empty()) {
6818 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6819 "A media section is missing a MID attribute.");
6820 }
Steve Anton06817cd2018-12-18 15:55:30 -08006821 if (!mids.insert(content.name).second) {
6822 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6823 "Duplicate a=mid value '" + content.name + "'.");
6824 }
6825 }
6826 return RTCError::OK();
6827}
6828
Steve Anton8a006912017-12-04 15:25:56 -08006829RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006830 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006831 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006832 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006833 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006834 }
6835
6836 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006837 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006838 }
6839
Steve Anton3828c062017-12-06 10:34:51 -08006840 SdpType type = sdesc->GetType();
6841 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6842 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006843 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006844 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006845 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006846 }
6847
Steve Anton06817cd2018-12-18 15:55:30 -08006848 RTCError error = ValidateMids(*sdesc->description());
6849 if (!error.ok()) {
6850 return error;
6851 }
6852
Steve Anton75737c02017-11-06 10:37:17 -08006853 // Verify crypto settings.
6854 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006855 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6856 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006857 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006858 if (!crypto_error.ok()) {
6859 return crypto_error;
6860 }
Steve Anton75737c02017-11-06 10:37:17 -08006861 }
6862
6863 // Verify ice-ufrag and ice-pwd.
6864 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6866 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006867 }
6868
6869 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006870 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6871 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006872 }
6873
6874 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6875 // m-lines that do not rtcp-mux enabled.
6876
6877 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006878 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006879 // With an answer we want to compare the new answer session description with
6880 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006881 const cricket::SessionDescription* offer_desc =
6882 (source == cricket::CS_LOCAL) ? remote_description()->description()
6883 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006884 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6885 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6886 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006887 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6888 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006889 }
6890 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006891 // The re-offers should respect the order of m= sections in current
6892 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006893 // With a re-offer, either the current local or current remote descriptions
6894 // could be the most up to date, so we would like to check against both of
6895 // them if they exist. It could be the case that one of them has a 0 port
6896 // for a media section, but the other does not. This is important to check
6897 // against in the case that we are recycling an m= section.
6898 const cricket::SessionDescription* current_desc = nullptr;
6899 const cricket::SessionDescription* secondary_current_desc = nullptr;
6900 if (local_description()) {
6901 current_desc = local_description()->description();
6902 if (remote_description()) {
6903 secondary_current_desc = remote_description()->description();
6904 }
6905 } else if (remote_description()) {
6906 current_desc = remote_description()->description();
6907 }
Steve Anton75737c02017-11-06 10:37:17 -08006908 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006909 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6910 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006911 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6912 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006913 }
6914 }
6915
Steve Antonba42e992018-04-09 14:10:01 -07006916 if (IsUnifiedPlan()) {
6917 // Ensure that each audio and video media section has at most one
6918 // "StreamParams". This will return an error if receiving a session
6919 // description from a "Plan B" endpoint which adds multiple tracks of the
6920 // same type. With Unified Plan, there can only be at most one track per
6921 // media section.
6922 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006923 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006924 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6925 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6926 desc.streams().size() > 1u) {
6927 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6928 "Media section has more than one track specified "
6929 "with a=ssrc lines which is not supported with "
6930 "Unified Plan.");
6931 }
6932 }
6933 }
6934
Steve Anton8a006912017-12-04 15:25:56 -08006935 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006936}
6937
Steve Anton3828c062017-12-06 10:34:51 -08006938bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006939 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006940 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006941 return (state == PeerConnectionInterface::kStable) ||
6942 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006943 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006944 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006945 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6946 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6947 }
6948}
6949
Steve Anton3828c062017-12-06 10:34:51 -08006950bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006951 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006952 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006953 return (state == PeerConnectionInterface::kStable) ||
6954 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006955 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006956 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006957 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6958 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6959 }
6960}
6961
Steve Antonf8470812017-12-04 10:46:21 -08006962const char* PeerConnection::SessionErrorToString(SessionError error) const {
6963 switch (error) {
6964 case SessionError::kNone:
6965 return "ERROR_NONE";
6966 case SessionError::kContent:
6967 return "ERROR_CONTENT";
6968 case SessionError::kTransport:
6969 return "ERROR_TRANSPORT";
6970 }
6971 RTC_NOTREACHED();
6972 return "";
6973}
6974
Steve Anton75737c02017-11-06 10:37:17 -08006975std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006976 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006977 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6978 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006979 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006980}
6981
Steve Anton8e20f172018-03-06 10:55:04 -08006982void PeerConnection::ReportSdpFormatReceived(
6983 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006984 int num_audio_mlines = 0;
6985 int num_video_mlines = 0;
6986 int num_audio_tracks = 0;
6987 int num_video_tracks = 0;
6988 for (const ContentInfo& content : remote_offer.description()->contents()) {
6989 cricket::MediaType media_type = content.media_description()->type();
6990 int num_tracks = std::max(
6991 1, static_cast<int>(content.media_description()->streams().size()));
6992 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6993 num_audio_mlines += 1;
6994 num_audio_tracks += num_tracks;
6995 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6996 num_video_mlines += 1;
6997 num_video_tracks += num_tracks;
6998 }
6999 }
7000 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7001 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7002 format = kSdpFormatReceivedComplexUnifiedPlan;
7003 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7004 format = kSdpFormatReceivedComplexPlanB;
7005 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7006 format = kSdpFormatReceivedSimple;
7007 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007008 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7009 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007010}
7011
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007012void PeerConnection::ReportIceCandidateCollected(
7013 const cricket::Candidate& candidate) {
7014 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7015 if (candidate.address().IsPrivateIP()) {
7016 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7017 }
7018 if (candidate.address().IsUnresolvedIP()) {
7019 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7020 }
7021 if (candidate.address().family() == AF_INET6) {
7022 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7023 }
7024}
7025
7026void PeerConnection::ReportRemoteIceCandidateAdded(
7027 const cricket::Candidate& candidate) {
7028 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7029 if (candidate.address().IsPrivateIP()) {
7030 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7031 }
7032 if (candidate.address().IsUnresolvedIP()) {
7033 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7034 }
7035 if (candidate.address().family() == AF_INET6) {
7036 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7037 }
7038}
7039
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007040void PeerConnection::NoteUsageEvent(UsageEvent event) {
7041 RTC_DCHECK_RUN_ON(signaling_thread());
7042 usage_event_accumulator_ |= static_cast<int>(event);
7043}
7044
7045void PeerConnection::ReportUsagePattern() const {
7046 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007047 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7048 usage_event_accumulator_,
7049 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007050 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007051 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007052 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7053 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007054 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007055 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7056 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7057 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7058 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007059 // If called after close(), we can't report, because observer may have
7060 // been deallocated, and therefore pointer is null. Write to log instead.
7061 if (observer_) {
7062 Observer()->OnInterestingUsage(usage_event_accumulator_);
7063 } else {
7064 RTC_LOG(LS_INFO) << "Interesting usage signature "
7065 << usage_event_accumulator_
7066 << " observed after observer shutdown";
7067 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007068 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007069}
7070
Steve Anton0ffaaa22018-02-23 10:31:30 -08007071void PeerConnection::ReportNegotiatedSdpSemantics(
7072 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007073 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007074 switch (answer.description()->msid_signaling()) {
7075 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007076 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007077 break;
7078 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007079 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007080 break;
7081 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007082 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007083 break;
7084 case cricket::kMsidSignalingMediaSection |
7085 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007086 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007087 break;
7088 default:
7089 RTC_NOTREACHED();
7090 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007091 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7092 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007093}
7094
Steve Anton75737c02017-11-06 10:37:17 -08007095// We need to check the local/remote description for the Transport instead of
7096// the session, because a new Transport added during renegotiation may have
7097// them unset while the session has them set from the previous negotiation.
7098// Not doing so may trigger the auto generation of transport description and
7099// mess up DTLS identity information, ICE credential, etc.
7100bool PeerConnection::ReadyToUseRemoteCandidate(
7101 const IceCandidateInterface* candidate,
7102 const SessionDescriptionInterface* remote_desc,
7103 bool* valid) {
7104 *valid = true;
7105
7106 const SessionDescriptionInterface* current_remote_desc =
7107 remote_desc ? remote_desc : remote_description();
7108
7109 if (!current_remote_desc) {
7110 return false;
7111 }
7112
Guido Urdaneta41633172019-05-23 20:12:29 +02007113 RTCErrorOr<const cricket::ContentInfo*> result =
7114 FindContentInfo(current_remote_desc, candidate);
7115 if (!result.ok()) {
7116 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7117 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007118
7119 *valid = false;
7120 return false;
7121 }
7122
Guido Urdaneta41633172019-05-23 20:12:29 +02007123 std::string transport_name = GetTransportName(result.value()->name);
7124 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007125}
7126
7127bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007128 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007129 (dtls_enabled_ ||
7130 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007131}
7132
7133void PeerConnection::OnTransportControllerGatheringState(
7134 cricket::IceGatheringState state) {
7135 RTC_DCHECK(signaling_thread()->IsCurrent());
7136 if (state == cricket::kIceGatheringGathering) {
7137 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7138 } else if (state == cricket::kIceGatheringComplete) {
7139 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7140 }
7141}
7142
7143void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007144 std::map<std::string, std::set<cricket::MediaType>>
7145 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007146 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007147 if (transceiver->internal()->channel()) {
7148 const std::string& transport_name =
7149 transceiver->internal()->channel()->transport_name();
7150 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007151 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007152 }
Steve Anton75737c02017-11-06 10:37:17 -08007153 }
7154 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007155 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7156 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007157 }
Zhi Huange830e682018-03-30 10:48:35 -07007158
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007159 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007160 if (transport_name) {
7161 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007162 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007163 }
Zhi Huange830e682018-03-30 10:48:35 -07007164
Steve Antonc7b964c2018-02-01 14:39:45 -08007165 for (const auto& entry : media_types_by_transport_name) {
7166 const std::string& transport_name = entry.first;
7167 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007168 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007169 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007170 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007171 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007172 }
7173 }
7174}
7175// Walk through the ConnectionInfos to gather best connection usage
7176// for IPv4 and IPv6.
7177void PeerConnection::ReportBestConnectionState(
7178 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007179 for (const cricket::TransportChannelStats& channel_stats :
7180 stats.channel_stats) {
7181 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007182 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007183 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007184 continue;
7185 }
7186
Steve Antonc7b964c2018-02-01 14:39:45 -08007187 const cricket::Candidate& local = connection_info.local_candidate;
7188 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007189
7190 // Increment the counter for IceCandidatePairType.
7191 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7192 (local.type() == RELAY_PORT_TYPE &&
7193 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007194 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7195 GetIceCandidatePairCounter(local, remote),
7196 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007197 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007198 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7199 GetIceCandidatePairCounter(local, remote),
7200 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007201 } else {
7202 RTC_CHECK(0);
7203 }
Steve Anton75737c02017-11-06 10:37:17 -08007204
7205 // Increment the counter for IP type.
7206 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007207 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7208 kBestConnections_IPv4,
7209 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007210 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007211 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7212 kBestConnections_IPv6,
7213 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007214 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007215 RTC_CHECK(!local.address().hostname().empty() &&
7216 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007217 }
7218
7219 return;
7220 }
7221 }
7222}
7223
7224void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007225 const cricket::TransportStats& stats,
7226 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007227 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7228 return;
7229 }
7230
7231 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7232 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7233 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7234 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7235 return;
7236 }
7237
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007238 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7239 for (cricket::MediaType media_type : media_types) {
7240 switch (media_type) {
7241 case cricket::MEDIA_TYPE_AUDIO:
7242 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7243 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7244 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7245 break;
7246 case cricket::MEDIA_TYPE_VIDEO:
7247 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7248 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7249 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7250 break;
7251 case cricket::MEDIA_TYPE_DATA:
7252 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7253 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7254 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7255 break;
7256 default:
7257 RTC_NOTREACHED();
7258 continue;
7259 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007260 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007261 }
7262
7263 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7264 for (cricket::MediaType media_type : media_types) {
7265 switch (media_type) {
7266 case cricket::MEDIA_TYPE_AUDIO:
7267 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7268 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7269 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7270 break;
7271 case cricket::MEDIA_TYPE_VIDEO:
7272 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7273 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7274 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7275 break;
7276 case cricket::MEDIA_TYPE_DATA:
7277 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7278 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7279 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7280 break;
7281 default:
7282 RTC_NOTREACHED();
7283 continue;
7284 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007285 }
Steve Anton75737c02017-11-06 10:37:17 -08007286 }
7287}
7288
7289void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007290 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007291 RTC_DCHECK(call_);
7292 call_->OnSentPacket(sent_packet);
7293}
7294
7295const std::string PeerConnection::GetTransportName(
7296 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007297 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007298 if (channel) {
7299 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007300 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007301 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007302 RTC_DCHECK(sctp_mid_);
7303 if (content_name == *sctp_mid_) {
7304 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007305 }
7306 }
7307 // Return an empty string if failed to retrieve the transport name.
7308 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007309}
7310
Steve Anton6fec8802017-12-04 10:37:29 -08007311void PeerConnection::DestroyTransceiverChannel(
7312 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7313 transceiver) {
7314 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007315
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007316 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007317 if (channel) {
7318 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007319 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007320 }
7321}
7322
7323void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007324 if (rtp_data_channel_) {
7325 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007326 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007327 rtp_data_channel_ = nullptr;
7328 }
7329
7330 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7331 // grab a reference to this PeerConnection. If this is called from the
7332 // PeerConnection destructor, the RefCountedObject vtable will have already
7333 // been destroyed (since it is a subclass of PeerConnection) and using
7334 // rtc::Bind will cause "Pure virtual function called" error to appear.
7335
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007336 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007337 OnDataChannelDestroyed();
7338 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7339 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007340 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007341 });
7342 }
Steve Anton6fec8802017-12-04 10:37:29 -08007343}
7344
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007345void PeerConnection::DestroyChannelInterface(
7346 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007347 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007348 switch (channel->media_type()) {
7349 case cricket::MEDIA_TYPE_AUDIO:
7350 channel_manager()->DestroyVoiceChannel(
7351 static_cast<cricket::VoiceChannel*>(channel));
7352 break;
7353 case cricket::MEDIA_TYPE_VIDEO:
7354 channel_manager()->DestroyVideoChannel(
7355 static_cast<cricket::VideoChannel*>(channel));
7356 break;
7357 case cricket::MEDIA_TYPE_DATA:
7358 channel_manager()->DestroyRtpDataChannel(
7359 static_cast<cricket::RtpDataChannel*>(channel));
7360 break;
7361 default:
7362 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7363 break;
7364 }
Zhi Huange830e682018-03-30 10:48:35 -07007365}
Steve Anton6fec8802017-12-04 10:37:29 -08007366
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007367bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007368 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007369 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007370 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007371 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007372 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007373 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007374 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007375 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007376 auto base_channel = GetChannel(mid);
7377 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007378 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007379 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007380
Karl Wiberg5966c502019-02-21 23:55:09 +01007381 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007382 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007383 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007384
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007385 if (data_channel_transport_ && mid == sctp_mid_ &&
7386 data_channel_transport_ != data_channel_transport) {
7387 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7388 // it's bundled).
7389 data_channel_transport_->SetDataSink(nullptr);
7390 data_channel_transport_ = data_channel_transport;
7391 if (data_channel_transport) {
7392 data_channel_transport->SetDataSink(this);
7393
7394 // There's a new data channel transport. This needs to be signaled to the
7395 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7396 // necessary when bundling is applied.
7397 data_channel_transport_invoker_->AsyncInvoke<void>(
7398 RTC_FROM_HERE, signaling_thread(), [this] {
7399 RTC_DCHECK_RUN_ON(signaling_thread());
7400 for (auto channel : sctp_data_channels_) {
7401 channel->OnTransportChannelCreated();
7402 }
7403 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007404 }
7405 }
7406
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007407 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007408}
7409
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007410void PeerConnection::OnSetStreams() {
7411 RTC_DCHECK_RUN_ON(signaling_thread());
7412 if (IsUnifiedPlan())
7413 UpdateNegotiationNeeded();
7414}
7415
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007416PeerConnectionObserver* PeerConnection::Observer() const {
7417 // In earlier production code, the pointer was not cleared on close,
7418 // which might have led to undefined behavior if the observer was not
7419 // deallocated, or strange crashes if it was.
7420 // We use CHECK in order to catch such behavior if it exists.
7421 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7422 RTC_CHECK(observer_);
7423 return observer_;
7424}
7425
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007426CryptoOptions PeerConnection::GetCryptoOptions() {
7427 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7428 // after it has been removed.
7429 return configuration_.crypto_options.has_value()
7430 ? *configuration_.crypto_options
7431 : factory_->options().crypto_options;
7432}
7433
Harald Alvestrand89061872018-01-02 14:08:34 +01007434void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007435 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007436 if (stats_collector_) {
7437 stats_collector_->ClearCachedStatsReport();
7438 }
7439}
7440
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007441void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007442 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7443 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007444}
7445
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007446void PeerConnection::UpdateNegotiationNeeded() {
7447 RTC_DCHECK_RUN_ON(signaling_thread());
7448 if (!IsUnifiedPlan()) {
7449 Observer()->OnRenegotiationNeeded();
7450 return;
7451 }
7452
7453 // If connection's [[IsClosed]] slot is true, abort these steps.
7454 if (IsClosed())
7455 return;
7456
7457 // If connection's signaling state is not "stable", abort these steps.
7458 if (signaling_state() != kStable)
7459 return;
7460
7461 // NOTE
7462 // The negotiation-needed flag will be updated once the state transitions to
7463 // "stable", as part of the steps for setting an RTCSessionDescription.
7464
7465 // If the result of checking if negotiation is needed is false, clear the
7466 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7467 // to false, and abort these steps.
7468 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7469 if (!is_negotiation_needed) {
7470 is_negotiation_needed_ = false;
7471 return;
7472 }
7473
7474 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7475 // steps.
7476 if (is_negotiation_needed_)
7477 return;
7478
7479 // Set connection's [[NegotiationNeeded]] slot to true.
7480 is_negotiation_needed_ = true;
7481
7482 // Queue a task that runs the following steps:
7483 // If connection's [[IsClosed]] slot is true, abort these steps.
7484 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7485 // Fire an event named negotiationneeded at connection.
7486 Observer()->OnRenegotiationNeeded();
7487}
7488
7489bool PeerConnection::CheckIfNegotiationIsNeeded() {
7490 RTC_DCHECK_RUN_ON(signaling_thread());
7491 // 1. If any implementation-specific negotiation is required, as described at
7492 // the start of this section, return true.
7493
Henrik Boström79b69802019-07-18 11:16:56 +02007494 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7495 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7496 return true;
7497 }
7498
7499 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007500 const SessionDescriptionInterface* description = current_local_description();
7501 if (!description)
7502 return true;
7503
Henrik Boström79b69802019-07-18 11:16:56 +02007504 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007505 // description has been negotiated yet for data, return true.
7506 if (!sctp_data_channels_.empty()) {
7507 if (!cricket::GetFirstDataContent(description->description()->contents()))
7508 return true;
7509 }
7510
Henrik Boström79b69802019-07-18 11:16:56 +02007511 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007512 // following checks:
7513 for (const auto& transceiver : transceivers_) {
7514 const ContentInfo* current_local_msection =
7515 FindTransceiverMSection(transceiver.get(), description);
7516
7517 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7518 transceiver.get(), current_remote_description());
7519
Henrik Boström79b69802019-07-18 11:16:56 +02007520 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007521 // but the associated m= section is not yet rejected in
7522 // connection.[[CurrentLocalDescription]] or
7523 // connection.[[CurrentRemoteDescription]], return true.
7524 if (transceiver->stopped()) {
7525 if (current_local_msection && !current_local_msection->rejected &&
7526 ((current_remote_msection && !current_remote_msection->rejected) ||
7527 !current_remote_msection)) {
7528 return true;
7529 }
7530 continue;
7531 }
7532
Henrik Boström79b69802019-07-18 11:16:56 +02007533 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007534 // section in description, return true.
7535 if (!current_local_msection)
7536 return true;
7537
7538 const MediaContentDescription* current_local_media_description =
7539 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007540 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007541 // in description then perform the following checks:
7542
Henrik Boström79b69802019-07-18 11:16:56 +02007543 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007544 // associated m= section in description either doesn't contain a single
7545 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7546 // m= section, or the MSID values themselves, differ from what is in
7547 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7548 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7549 if (current_local_media_description->streams().size() == 0)
7550 return true;
7551
7552 std::vector<std::string> msection_msids;
7553 for (const auto& stream : current_local_media_description->streams()) {
7554 for (const std::string& msid : stream.stream_ids())
7555 msection_msids.push_back(msid);
7556 }
7557
7558 std::vector<std::string> transceiver_msids =
7559 transceiver->sender()->stream_ids();
7560 if (msection_msids.size() != transceiver_msids.size())
7561 return true;
7562
7563 absl::c_sort(transceiver_msids);
7564 absl::c_sort(msection_msids);
7565 if (transceiver_msids != msection_msids)
7566 return true;
7567 }
7568
Henrik Boström79b69802019-07-18 11:16:56 +02007569 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007570 // associated m= section in neither connection.[[CurrentLocalDescription]]
7571 // nor connection.[[CurrentRemoteDescription]] matches
7572 // transceiver.[[Direction]], return true.
7573 if (description->GetType() == SdpType::kOffer) {
7574 if (!current_remote_description())
7575 return true;
7576
7577 if (!current_remote_msection)
7578 return true;
7579
7580 RtpTransceiverDirection current_local_direction =
7581 current_local_media_description->direction();
7582 RtpTransceiverDirection current_remote_direction =
7583 current_remote_msection->media_description()->direction();
7584 if (transceiver->direction() != current_local_direction &&
7585 transceiver->direction() !=
7586 RtpTransceiverDirectionReversed(current_remote_direction)) {
7587 return true;
7588 }
7589 }
7590
Henrik Boström79b69802019-07-18 11:16:56 +02007591 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007592 // associated m= section in the description does not match
7593 // transceiver.[[Direction]] intersected with the offered direction (as
7594 // described in [JSEP] (section 5.3.1.)), return true.
7595 if (description->GetType() == SdpType::kAnswer) {
7596 if (!remote_description())
7597 return true;
7598
7599 const ContentInfo* offered_remote_msection =
7600 FindTransceiverMSection(transceiver.get(), remote_description());
7601
7602 RtpTransceiverDirection offered_direction =
7603 offered_remote_msection
7604 ? offered_remote_msection->media_description()->direction()
7605 : RtpTransceiverDirection::kInactive;
7606
7607 if (current_local_media_description->direction() !=
7608 (RtpTransceiverDirectionIntersection(
7609 transceiver->direction(),
7610 RtpTransceiverDirectionReversed(offered_direction)))) {
7611 return true;
7612 }
7613 }
7614 }
7615
7616 // If all the preceding checks were performed and true was not returned,
7617 // nothing remains to be negotiated; return false.
7618 return false;
7619}
7620
Eldar Relloead0ec92019-10-21 23:01:31 +03007621RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007622 auto state = signaling_state();
7623 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7624 state != PeerConnectionInterface::kHaveRemoteOffer) {
7625 return RTCError(RTCErrorType::INVALID_STATE,
7626 "Called in wrong signalingState: " +
7627 GetSignalingStateString(signaling_state()));
7628 }
7629 RTC_DCHECK_RUN_ON(signaling_thread());
7630 RTC_DCHECK(IsUnifiedPlan());
7631
7632 for (auto&& transceivers_stable_state_pair :
7633 transceiver_stable_states_by_transceivers_) {
7634 auto transceiver = transceivers_stable_state_pair.first;
7635 auto state = transceivers_stable_state_pair.second;
7636 RTC_DCHECK(transceiver->internal()->mid().has_value());
7637 std::string mid = transceiver->internal()->mid().value();
7638 transport_controller_->RollbackTransportForMid(mid);
7639 DestroyTransceiverChannel(transceiver);
7640
Eldar Relloead0ec92019-10-21 23:01:31 +03007641 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7642 transceiver->receiver()) {
7643 Observer()->OnRemoveTrack(transceiver->receiver());
7644 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007645 if (state.newly_created()) {
7646 // Remove added transceivers with no added track.
7647 if (transceiver->internal()->sender()->track()) {
7648 transceiver->internal()->set_created_by_addtrack(true);
7649 } else {
7650 int remaining_transceiver_count = 0;
7651 for (auto&& t : transceivers_) {
7652 if (t != transceiver) {
7653 transceivers_[remaining_transceiver_count++] = t;
7654 }
7655 }
7656 transceivers_.resize(remaining_transceiver_count);
7657 }
7658 }
7659 transceiver->internal()->sender_internal()->set_transport(nullptr);
7660 transceiver->internal()->receiver_internal()->set_transport(nullptr);
7661 transceiver->internal()->set_direction(state.direction());
7662 transceiver->internal()->set_mid(state.mid());
7663 transceiver->internal()->set_mline_index(state.mline_index());
7664 }
7665 transceiver_stable_states_by_transceivers_.clear();
7666 pending_local_description_.reset();
7667 pending_remote_description_.reset();
7668 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03007669
7670 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
7671 // gets called in SetRemoteDescription.
7672 if (sdp_type == SdpType::kRollback) {
7673 UpdateNegotiationNeeded();
7674 if (is_negotiation_needed_) {
7675 Observer()->OnRenegotiationNeeded();
7676 }
7677 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007678 return RTCError::OK();
7679}
7680
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007681} // namespace webrtc