blob: c0e1831916803ba6f5cf99fbdf4758109913c61f [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;
761 bool presume_writable_when_fully_relayed;
762 bool enable_ice_renomination;
763 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700764 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200765 absl::optional<int> ice_check_interval_strong_connectivity;
766 absl::optional<int> ice_check_interval_weak_connectivity;
767 absl::optional<int> ice_check_min_interval;
768 absl::optional<int> ice_unwritable_timeout;
769 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800770 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200771 absl::optional<int> stun_candidate_keepalive_interval;
772 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200773 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800774 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200775 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700776 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700777 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700778 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700779 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700780 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700781 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700782 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100783 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200784 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300785 bool enable_implicit_rollback;
deadbeef293e9262017-01-11 12:28:30 -0800786 };
787 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
788 "Did you add something to RTCConfiguration and forget to "
789 "update operator==?");
790 return type == o.type && servers == o.servers &&
791 bundle_policy == o.bundle_policy &&
792 rtcp_mux_policy == o.rtcp_mux_policy &&
793 tcp_candidate_policy == o.tcp_candidate_policy &&
794 candidate_network_policy == o.candidate_network_policy &&
795 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
796 audio_jitter_buffer_fast_accelerate ==
797 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100798 audio_jitter_buffer_min_delay_ms ==
799 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100800 audio_jitter_buffer_enable_rtx_handling ==
801 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800802 ice_connection_receiving_timeout ==
803 o.ice_connection_receiving_timeout &&
804 ice_backup_candidate_pair_ping_interval ==
805 o.ice_backup_candidate_pair_ping_interval &&
806 continual_gathering_policy == o.continual_gathering_policy &&
807 certificates == o.certificates &&
808 prioritize_most_likely_ice_candidate_pairs ==
809 o.prioritize_most_likely_ice_candidate_pairs &&
810 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800811 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700812 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100813 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800814 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800815 screencast_min_bitrate == o.screencast_min_bitrate &&
816 combined_audio_video_bwe == o.combined_audio_video_bwe &&
817 enable_dtls_srtp == o.enable_dtls_srtp &&
818 ice_candidate_pool_size == o.ice_candidate_pool_size &&
819 prune_turn_ports == o.prune_turn_ports &&
820 presume_writable_when_fully_relayed ==
821 o.presume_writable_when_fully_relayed &&
822 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800823 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700824 surface_ice_candidates_on_ice_transport_type_changed ==
825 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800826 ice_check_interval_strong_connectivity ==
827 o.ice_check_interval_strong_connectivity &&
828 ice_check_interval_weak_connectivity ==
829 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700830 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700831 ice_unwritable_timeout == o.ice_unwritable_timeout &&
832 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800833 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800834 stun_candidate_keepalive_interval ==
835 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200836 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800837 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800838 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700839 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700840 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700841 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700842 use_media_transport_for_data_channels ==
843 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700844 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700845 use_datagram_transport_for_data_channels ==
846 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700847 use_datagram_transport_for_data_channels_receive_only ==
848 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100849 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200850 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300851 turn_logging_id == o.turn_logging_id &&
852 enable_implicit_rollback == o.enable_implicit_rollback;
deadbeef293e9262017-01-11 12:28:30 -0800853}
854
855bool PeerConnectionInterface::RTCConfiguration::operator!=(
856 const PeerConnectionInterface::RTCConfiguration& o) const {
857 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800858}
859
zhihuang8f65cdf2016-05-06 18:40:30 -0700860// Generate a RTCP CNAME when a PeerConnection is created.
861std::string GenerateRtcpCname() {
862 std::string cname;
863 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100864 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800865 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700866 }
867 return cname;
868}
869
zhihuang1c378ed2017-08-17 14:10:50 -0700870bool ValidateOfferAnswerOptions(
871 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
872 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
873 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700874}
875
zhihuang1c378ed2017-08-17 14:10:50 -0700876// From |rtc_options|, fill parts of |session_options| shared by all generated
877// m= sections (in other words, nothing that involves a map/array).
878void ExtractSharedMediaSessionOptions(
879 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
880 cricket::MediaSessionOptions* session_options) {
881 session_options->vad_enabled = rtc_options.voice_activity_detection;
882 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200883 session_options->raw_packetization_for_video =
884 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700885}
zhihuanga77e6bb2017-08-14 18:17:48 -0700886
zhihuang38ede132017-06-15 12:52:32 -0700887PeerConnection::PeerConnection(PeerConnectionFactory* factory,
888 std::unique_ptr<RtcEventLog> event_log,
889 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000890 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700891 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100892 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700893 datagram_transport_config_(
894 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700895 datagram_transport_data_channel_config_(
896 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700897 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700898 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700899 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100900 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200901 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -0700902 data_channel_transport_(nullptr),
Henrik Boström79b69802019-07-18 11:16:56 +0200903 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904
905PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100906 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800907 RTC_DCHECK_RUN_ON(signaling_thread());
908
Steve Anton8af21862017-12-15 11:20:13 -0800909 // Need to stop transceivers before destroying the stats collector because
910 // AudioRtpSender has a reference to the StatsCollector it will update when
911 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100912 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800913 transceiver->Stop();
914 }
Steve Anton4171afb2017-11-20 10:20:22 -0800915
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700916 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800917 if (stats_collector_) {
918 stats_collector_->WaitForPendingRequest();
919 stats_collector_ = nullptr;
920 }
Steve Anton75737c02017-11-06 10:37:17 -0800921
Steve Anton8af21862017-12-15 11:20:13 -0800922 // Don't destroy BaseChannels until after stats has been cleaned up so that
923 // the last stats request can still read from the channels.
924 DestroyAllChannels();
925
Mirko Bonadei675513b2017-11-09 11:09:25 +0100926 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800927
928 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800929 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700930 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800931 transport_controller_.reset();
932
deadbeef91dd5672016-05-18 16:55:30 -0700933 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100934 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
935 RTC_DCHECK_RUN_ON(network_thread());
936 port_allocator_.reset();
937 });
eladalon248fd4f2017-09-06 05:18:15 -0700938 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700939 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100940 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700941 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800942 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700943 event_log_.reset();
944 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945}
946
Steve Anton8af21862017-12-15 11:20:13 -0800947void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800948 // Destroy video channels first since they may have a pointer to a voice
949 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100950 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800951 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800952 DestroyTransceiverChannel(transceiver);
953 }
954 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100955 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800956 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800957 DestroyTransceiverChannel(transceiver);
958 }
959 }
960 DestroyDataChannel();
961}
962
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000964 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100966 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100967 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100968 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700969
970 RTCError config_error = ValidateConfiguration(configuration);
971 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100972 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700973 return false;
974 }
975
Benjamin Wrightcab58882018-05-02 15:12:47 -0700976 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100977 RTC_LOG(LS_ERROR)
978 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100979 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800980 return false;
981 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200982
Benjamin Wrightcab58882018-05-02 15:12:47 -0700983 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800984 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100985 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100986 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800987 return false;
988 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700989
Benjamin Wrightcab58882018-05-02 15:12:47 -0700990 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700991 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700992 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700993 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800994
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200995 cricket::ServerAddresses stun_servers;
996 std::vector<cricket::RelayServerConfig> turn_servers;
997
998 RTCErrorType parse_error =
999 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1000 if (parse_error != RTCErrorType::NONE) {
1001 return false;
1002 }
1003
Jonas Oreland3c028422019-08-22 16:16:35 +02001004 // Add the turn logging id to all turn servers
1005 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1006 turn_server.turn_logging_id = configuration.turn_logging_id;
1007 }
1008
deadbeef91dd5672016-05-18 16:55:30 -07001009 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001010 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001011 const auto pa_result =
1012 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001013 RTC_FROM_HERE,
1014 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001015 stun_servers, turn_servers, configuration));
1016
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001017 // If initialization was successful, note if STUN or TURN servers
1018 // were supplied.
1019 if (!stun_servers.empty()) {
1020 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1021 }
1022 if (!turn_servers.empty()) {
1023 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1024 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001026 // Send information about IPv4/IPv6 status.
1027 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001028 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001029 address_family = kPeerConnection_IPv6;
1030 } else {
1031 address_family = kPeerConnection_IPv4;
1032 }
1033 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1034 kPeerConnectionAddressFamilyCounter_Max);
1035
Zhi Huange830e682018-03-30 10:48:35 -07001036 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1037
Steve Anton75737c02017-11-06 10:37:17 -08001038 // RFC 3264: The numeric value of the session id and version in the
1039 // o line MUST be representable with a "64 bit signed integer".
1040 // Due to this constraint session id |session_id_| is max limited to
1041 // LLONG_MAX.
1042 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001043 JsepTransportController::Config config;
1044 config.redetermine_role_on_ice_restart =
1045 configuration.redetermine_role_on_ice_restart;
1046 config.ssl_max_version = factory_->options().ssl_max_version;
1047 config.disable_encryption = options.disable_encryption;
1048 config.bundle_policy = configuration.bundle_policy;
1049 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001050 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1051 // stub.
1052 config.crypto_options = configuration.crypto_options.has_value()
1053 ? *configuration.crypto_options
1054 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001055 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001056 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1057 // since the JsepTransportController instance is owned by this PeerConnection
1058 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1059 // pointer.
1060 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1061 int64_t packet_time_us) {
1062 RTC_DCHECK_RUN_ON(network_thread());
1063 rtcp_invoker_.AsyncInvoke<void>(
1064 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1065 RTC_DCHECK_RUN_ON(worker_thread());
1066 // |call_| is reset on the worker thread in the PeerConnection
1067 // destructor, so we check that it's still valid before propagating
1068 // the packet.
1069 if (call_) {
1070 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1071 packet_time_us);
1072 }
1073 });
1074 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001075 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001076#if defined(ENABLE_EXTERNAL_AUTH)
1077 config.enable_external_auth = true;
1078#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001079 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001080
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001081 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001082 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001083 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001084 use_datagram_transport_for_data_channels_ =
1085 datagram_transport_data_channel_config_.enabled &&
1086 configuration.use_datagram_transport_for_data_channels.value_or(
1087 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001088 use_datagram_transport_for_data_channels_receive_only_ =
1089 configuration.use_datagram_transport_for_data_channels_receive_only
1090 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001091 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1092 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001093 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001094 if (!factory_->media_transport_factory()) {
1095 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001096 << "PeerConnecton is initialized with use_media_transport = true or "
1097 << "use_media_transport_for_data_channels = true "
1098 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001099 return false;
1100 }
1101
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001102 if (configuration.use_media_transport ||
1103 configuration.use_media_transport_for_data_channels) {
1104 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1105 // RTP media transport is introduced. But until then, we require SDES to
1106 // be enabled.
1107 if (configuration.enable_dtls_srtp.has_value() &&
1108 configuration.enable_dtls_srtp.value()) {
1109 RTC_LOG(LS_WARNING)
1110 << "When media transport is used, SDES must be enabled. Set "
1111 "configuration.enable_dtls_srtp to false. use_media_transport="
1112 << configuration.use_media_transport
1113 << ", use_media_transport_for_data_channels="
1114 << configuration.use_media_transport_for_data_channels;
1115 return false;
1116 }
1117 }
1118
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001119 config.use_media_transport_for_media = configuration.use_media_transport;
1120 config.use_media_transport_for_data_channels =
1121 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001122 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001123 config.use_datagram_transport_for_data_channels =
1124 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001125 config.use_datagram_transport_for_data_channels_receive_only =
1126 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001127 config.media_transport_factory = factory_->media_transport_factory();
1128 }
1129
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001130 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1131 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1132 if (!configuration.certificates.empty()) {
1133 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1134 // just picking the first one. The decision should be made based on the DTLS
1135 // handshake. The DTLS negotiations need to know about all certificates.
1136 certificate = configuration.certificates[0];
1137 }
1138
1139 if (options.disable_encryption) {
1140 dtls_enabled_ = false;
1141 } else {
1142 // Enable DTLS by default if we have an identity store or a certificate.
1143 dtls_enabled_ = (dependencies.cert_generator || certificate);
1144 // |configuration| can override the default |dtls_enabled_| value.
1145 if (configuration.enable_dtls_srtp) {
1146 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1147 }
1148 }
1149
1150 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1151
1152 if (use_datagram_transport_for_data_channels_) {
1153 if (configuration.enable_rtp_data_channel) {
1154 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1155 "use_datagram_transport_for_data_channels are "
1156 "incompatible and cannot both be set to true";
1157 return false;
1158 }
1159 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1160 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1161 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1162 } else {
1163 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1164 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1165 config.sctp_factory = sctp_factory_.get();
1166 }
1167 } else if (configuration.use_media_transport_for_data_channels) {
1168 if (configuration.enable_rtp_data_channel) {
1169 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1170 "use_media_transport_for_data_channels are "
1171 "incompatible and cannot both be set to true";
1172 return false;
1173 }
1174 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1175 } else if (configuration.enable_rtp_data_channel) {
1176 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1177 // set. It takes precendence over the disable_sctp_data_channels
1178 // PeerConnectionFactoryInterface::Options.
1179 data_channel_type_ = cricket::DCT_RTP;
1180 } else {
1181 // DTLS has to be enabled to use SCTP.
1182 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1183 data_channel_type_ = cricket::DCT_SCTP;
1184 config.sctp_factory = sctp_factory_.get();
1185 }
1186 }
1187
Zhi Huange830e682018-03-30 10:48:35 -07001188 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001189 signaling_thread(), network_thread(), port_allocator_.get(),
1190 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001191 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001192 this, &PeerConnection::OnTransportControllerConnectionState);
1193 transport_controller_->SignalStandardizedIceConnectionState.connect(
1194 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001195 transport_controller_->SignalConnectionState.connect(
1196 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001197 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001198 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001199 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001200 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001201 transport_controller_->SignalIceCandidateError.connect(
1202 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001203 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001204 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1205 transport_controller_->SignalDtlsHandshakeError.connect(
1206 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001207 transport_controller_->SignalIceCandidatePairChanged.connect(
1208 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001209
deadbeefab9b2d12015-10-14 11:33:11 -07001210 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001211 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212
Steve Antonba818672017-11-06 10:21:57 -08001213 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001214 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001215
Steve Antond25da372017-11-06 14:50:29 -08001216 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001217
Steve Anton75737c02017-11-06 10:37:17 -08001218 video_options_.screencast_min_bitrate_kbps =
1219 configuration.screencast_min_bitrate;
1220 audio_options_.combined_audio_video_bwe =
1221 configuration.combined_audio_video_bwe;
1222
1223 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001224 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001225
1226 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001227 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001228
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001229 audio_options_.audio_jitter_buffer_min_delay_ms =
1230 configuration.audio_jitter_buffer_min_delay_ms;
1231
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001232 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1233 configuration.audio_jitter_buffer_enable_rtx_handling;
1234
Steve Anton75737c02017-11-06 10:37:17 -08001235 // Whether the certificate generator/certificate is null or not determines
1236 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1237 // the right instructions by clearing the variables if needed.
1238 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001239 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001240 certificate = nullptr;
1241 } else if (certificate) {
1242 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001243 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001244 }
1245
1246 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1247 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001248 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001249 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1250 this, &PeerConnection::OnCertificateReady);
1251
1252 if (options.disable_encryption) {
1253 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1254 }
1255
1256 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001257 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001258 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259
Steve Anton4171afb2017-11-20 10:20:22 -08001260 // Add default audio/video transceivers for Plan B SDP.
1261 if (!IsUnifiedPlan()) {
1262 transceivers_.push_back(
1263 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1264 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1265 transceivers_.push_back(
1266 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1267 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1268 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001269 int delay_ms =
1270 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001271 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1272 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001273
1274 if (dependencies.video_bitrate_allocator_factory) {
1275 video_bitrate_allocator_factory_ =
1276 std::move(dependencies.video_bitrate_allocator_factory);
1277 } else {
1278 video_bitrate_allocator_factory_ =
1279 CreateBuiltinVideoBitrateAllocatorFactory();
1280 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 return true;
1282}
1283
Steve Anton038834f2017-07-14 15:59:59 -07001284RTCError PeerConnection::ValidateConfiguration(
1285 const RTCConfiguration& config) const {
1286 if (config.ice_regather_interval_range &&
1287 config.continual_gathering_policy == GATHER_ONCE) {
1288 return RTCError(RTCErrorType::INVALID_PARAMETER,
1289 "ice_regather_interval_range specified but continual "
1290 "gathering policy is GATHER_ONCE");
1291 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001292 auto result =
1293 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1294 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001295}
1296
Yves Gerey665174f2018-06-19 15:03:05 +02001297rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001298 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001299 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1300 "Plan SdpSemantics. Please use GetSenders "
1301 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001302 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303}
1304
Yves Gerey665174f2018-06-19 15:03:05 +02001305rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001306 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001307 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1308 "Plan SdpSemantics. Please use GetReceivers "
1309 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001310 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311}
1312
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001313bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001314 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001315 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1316 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001317 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 if (IsClosed()) {
1319 return false;
1320 }
deadbeefab9b2d12015-10-14 11:33:11 -07001321 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 return false;
1323 }
deadbeefab9b2d12015-10-14 11:33:11 -07001324
1325 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001326 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1327 observer->SignalAudioTrackAdded.connect(this,
1328 &PeerConnection::OnAudioTrackAdded);
1329 observer->SignalAudioTrackRemoved.connect(
1330 this, &PeerConnection::OnAudioTrackRemoved);
1331 observer->SignalVideoTrackAdded.connect(this,
1332 &PeerConnection::OnVideoTrackAdded);
1333 observer->SignalVideoTrackRemoved.connect(
1334 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001335 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001336
deadbeefab9b2d12015-10-14 11:33:11 -07001337 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001338 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001339 }
1340 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001341 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001342 }
1343
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001344 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001345 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 return true;
1347}
1348
1349void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001350 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001351 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1352 "Plan SdpSemantics. Please use RemoveTrack "
1353 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001354 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001355 if (!IsClosed()) {
1356 for (const auto& track : local_stream->GetAudioTracks()) {
1357 RemoveAudioTrack(track.get(), local_stream);
1358 }
1359 for (const auto& track : local_stream->GetVideoTracks()) {
1360 RemoveVideoTrack(track.get(), local_stream);
1361 }
deadbeefab9b2d12015-10-14 11:33:11 -07001362 }
deadbeefab9b2d12015-10-14 11:33:11 -07001363 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001364 stream_observers_.erase(
1365 std::remove_if(
1366 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001367 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001368 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001369 }),
1370 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001371
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 if (IsClosed()) {
1373 return;
1374 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001375 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376}
1377
Steve Anton2d6c76a2018-01-05 17:10:52 -08001378RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001379 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001380 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001381 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001382 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001383 if (!track) {
1384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1385 }
1386 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1387 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1388 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1389 "Track has invalid kind: " + track->kind());
1390 }
Steve Antonf9381f02017-12-14 10:23:57 -08001391 if (IsClosed()) {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1393 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001394 }
Steve Anton4171afb2017-11-20 10:20:22 -08001395 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001396 LOG_AND_RETURN_ERROR(
1397 RTCErrorType::INVALID_PARAMETER,
1398 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001399 }
Steve Antonf9381f02017-12-14 10:23:57 -08001400 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001401 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1402 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001403 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001404 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001405 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001406 }
1407 return sender_or_error;
1408}
deadbeefe1f9d832016-01-14 15:35:42 -08001409
Steve Antonf9381f02017-12-14 10:23:57 -08001410RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1411PeerConnection::AddTrackPlanB(
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001413 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001414 if (stream_ids.size() > 1u) {
1415 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1416 "AddTrack with more than one stream is not "
1417 "supported with Plan B semantics.");
1418 }
1419 std::vector<std::string> adjusted_stream_ids = stream_ids;
1420 if (adjusted_stream_ids.empty()) {
1421 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1422 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001423 cricket::MediaType media_type =
1424 (track->kind() == MediaStreamTrackInterface::kAudioKind
1425 ? cricket::MEDIA_TYPE_AUDIO
1426 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001427 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001428 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001429 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001430 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001431 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001432 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001433 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001434 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001435 if (sender_info) {
1436 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001437 }
Steve Antonf9381f02017-12-14 10:23:57 -08001438 } else {
1439 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001440 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001441 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001442 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001443 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001444 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001445 if (sender_info) {
1446 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001447 }
deadbeefe1f9d832016-01-14 15:35:42 -08001448 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001449 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001450}
deadbeefe1f9d832016-01-14 15:35:42 -08001451
Steve Antonf9381f02017-12-14 10:23:57 -08001452RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1453PeerConnection::AddTrackUnifiedPlan(
1454 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001455 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001456 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1457 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001458 RTC_LOG(LS_INFO) << "Reusing an existing "
1459 << cricket::MediaTypeToString(transceiver->media_type())
1460 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001461 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001462 transceiver->internal()->set_direction(
1463 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001464 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001465 transceiver->internal()->set_direction(
1466 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001467 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001468 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001469 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001470 } else {
1471 cricket::MediaType media_type =
1472 (track->kind() == MediaStreamTrackInterface::kAudioKind
1473 ? cricket::MEDIA_TYPE_AUDIO
1474 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001475 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1476 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001477 std::string sender_id = track->id();
1478 // Avoid creating a sender with an existing ID by generating a random ID.
1479 // This can happen if this is the second time AddTrack has created a sender
1480 // for this track.
1481 if (FindSenderById(sender_id)) {
1482 sender_id = rtc::CreateRandomUuid();
1483 }
Florent Castelli892acf02018-10-01 22:47:20 +02001484 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001485 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1486 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001487 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001488 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001489 }
Steve Antonf9381f02017-12-14 10:23:57 -08001490 return transceiver->sender();
1491}
1492
1493rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1494PeerConnection::FindFirstTransceiverForAddedTrack(
1495 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1496 RTC_DCHECK(track);
1497 for (auto transceiver : transceivers_) {
1498 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001499 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001500 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001501 !transceiver->internal()->has_ever_been_used_to_send() &&
1502 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001503 return transceiver;
1504 }
1505 }
1506 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001507}
1508
1509bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1510 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001511 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001512}
1513
Steve Anton24db5732018-07-23 10:27:33 -07001514RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001515 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001516 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001517 if (!sender) {
1518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1519 }
deadbeefe1f9d832016-01-14 15:35:42 -08001520 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001521 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1522 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001523 }
Steve Antonf9381f02017-12-14 10:23:57 -08001524 if (IsUnifiedPlan()) {
1525 auto transceiver = FindTransceiverBySender(sender);
1526 if (!transceiver || !sender->track()) {
1527 return RTCError::OK();
1528 }
1529 sender->SetTrack(nullptr);
1530 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001531 transceiver->internal()->set_direction(
1532 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001533 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001534 transceiver->internal()->set_direction(
1535 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001536 }
Steve Anton4171afb2017-11-20 10:20:22 -08001537 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001538 bool removed;
1539 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1540 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1541 } else {
1542 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1543 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1544 }
1545 if (!removed) {
1546 LOG_AND_RETURN_ERROR(
1547 RTCErrorType::INVALID_PARAMETER,
1548 "Couldn't find sender " + sender->id() + " to remove.");
1549 }
Steve Anton4171afb2017-11-20 10:20:22 -08001550 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001551 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001552 return RTCError::OK();
1553}
1554
1555rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1556PeerConnection::FindTransceiverBySender(
1557 rtc::scoped_refptr<RtpSenderInterface> sender) {
1558 for (auto transceiver : transceivers_) {
1559 if (transceiver->sender() == sender) {
1560 return transceiver;
1561 }
1562 }
1563 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001564}
1565
Steve Anton9158ef62017-11-27 13:01:52 -08001566RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1567PeerConnection::AddTransceiver(
1568 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1569 return AddTransceiver(track, RtpTransceiverInit());
1570}
1571
1572RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1573PeerConnection::AddTransceiver(
1574 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1575 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001576 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001577 RTC_CHECK(IsUnifiedPlan())
1578 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001579 if (!track) {
1580 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1581 }
1582 cricket::MediaType media_type;
1583 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1584 media_type = cricket::MEDIA_TYPE_AUDIO;
1585 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1586 media_type = cricket::MEDIA_TYPE_VIDEO;
1587 } else {
1588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1589 "Track kind is not audio or video");
1590 }
1591 return AddTransceiver(media_type, track, init);
1592}
1593
1594RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1595PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1596 return AddTransceiver(media_type, RtpTransceiverInit());
1597}
1598
1599RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1600PeerConnection::AddTransceiver(cricket::MediaType media_type,
1601 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001602 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001603 RTC_CHECK(IsUnifiedPlan())
1604 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001605 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1606 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1607 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1608 "media type is not audio or video");
1609 }
1610 return AddTransceiver(media_type, nullptr, init);
1611}
1612
1613RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1614PeerConnection::AddTransceiver(
1615 cricket::MediaType media_type,
1616 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001617 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001618 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001619 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1620 media_type == cricket::MEDIA_TYPE_VIDEO));
1621 if (track) {
1622 RTC_DCHECK_EQ(media_type,
1623 (track->kind() == MediaStreamTrackInterface::kAudioKind
1624 ? cricket::MEDIA_TYPE_AUDIO
1625 : cricket::MEDIA_TYPE_VIDEO));
1626 }
1627
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001628 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1629 init.send_encodings.size(), 0, 7, 8);
1630
Amit Hilbuchaa584152019-02-06 17:09:52 -08001631 size_t num_rids = absl::c_count_if(init.send_encodings,
1632 [](const RtpEncodingParameters& encoding) {
1633 return !encoding.rid.empty();
1634 });
1635 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001636 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001637 RTCErrorType::INVALID_PARAMETER,
1638 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001639 }
1640
Amit Hilbuchf4770402019-04-08 14:11:57 -07001641 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1642 [](const RtpEncodingParameters& encoding) {
1643 return !IsLegalRsidName(encoding.rid);
1644 })) {
1645 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1646 "Invalid RID value provided.");
1647 }
1648
Amit Hilbuchaa584152019-02-06 17:09:52 -08001649 if (absl::c_any_of(init.send_encodings,
1650 [](const RtpEncodingParameters& encoding) {
1651 return encoding.ssrc.has_value();
1652 })) {
1653 LOG_AND_RETURN_ERROR(
1654 RTCErrorType::UNSUPPORTED_PARAMETER,
1655 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001656 }
1657
1658 RtpParameters parameters;
1659 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001660
1661 // Encodings are dropped from the tail if too many are provided.
1662 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1663 parameters.encodings.erase(
1664 parameters.encodings.begin() + kMaxSimulcastStreams,
1665 parameters.encodings.end());
1666 }
1667
1668 // Single RID should be removed.
1669 if (parameters.encodings.size() == 1 &&
1670 !parameters.encodings[0].rid.empty()) {
1671 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1672 parameters.encodings[0].rid.clear();
1673 }
1674
1675 // If RIDs were not provided, they are generated for simulcast scenario.
1676 if (parameters.encodings.size() > 1 && num_rids == 0) {
1677 rtc::UniqueStringGenerator rid_generator;
1678 for (RtpEncodingParameters& encoding : parameters.encodings) {
1679 encoding.rid = rid_generator();
1680 }
1681 }
1682
Florent Castelli892acf02018-10-01 22:47:20 +02001683 if (UnimplementedRtpParameterHasValue(parameters)) {
1684 LOG_AND_RETURN_ERROR(
1685 RTCErrorType::UNSUPPORTED_PARAMETER,
1686 "Attempted to set an unimplemented parameter of RtpParameters.");
1687 }
Steve Anton9158ef62017-11-27 13:01:52 -08001688
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001689 auto result = cricket::CheckRtpParametersValues(parameters);
1690 if (!result.ok()) {
1691 LOG_AND_RETURN_ERROR(result.type(), result.message());
1692 }
1693
Steve Anton3d954a62018-04-02 11:27:23 -07001694 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1695 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001696 // Set the sender ID equal to the track ID if the track is specified unless
1697 // that sender ID is already in use.
1698 std::string sender_id =
1699 (track && !FindSenderById(track->id()) ? track->id()
1700 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001701 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001702 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001703 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1704 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1705 transceiver->internal()->set_direction(init.direction);
1706
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001707 if (update_negotiation_needed) {
1708 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001709 }
Steve Antonf9381f02017-12-14 10:23:57 -08001710
1711 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1712}
1713
Steve Anton02ee47c2018-01-10 16:26:06 -08001714rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1715PeerConnection::CreateSender(
1716 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001717 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001718 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001719 const std::vector<std::string>& stream_ids,
1720 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001721 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001722 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001723 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1724 RTC_DCHECK(!track ||
1725 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1726 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1727 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001728 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001729 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001730 } else {
1731 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1732 RTC_DCHECK(!track ||
1733 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1734 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001735 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001736 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001737 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001738 bool set_track_succeeded = sender->SetTrack(track);
1739 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001740 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001741 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001742 return sender;
1743}
1744
1745rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1746PeerConnection::CreateReceiver(cricket::MediaType media_type,
1747 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001748 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1749 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001750 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001751 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001752 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1753 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001754 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001755 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001756 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001757 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001758 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1759 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001760 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001761 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001762 return receiver;
1763}
1764
1765rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1766PeerConnection::CreateAndAddTransceiver(
1767 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1768 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1769 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001770 // Ensure that the new sender does not have an ID that is already in use by
1771 // another sender.
1772 // Allow receiver IDs to conflict since those come from remote SDP (which
1773 // could be invalid, but should not cause a crash).
1774 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001775 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001776 signaling_thread(),
1777 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001778 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001779 transceiver->internal()->SignalNegotiationNeeded.connect(
1780 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001781 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001782}
1783
Steve Anton52d86772018-02-20 15:48:12 -08001784void PeerConnection::OnNegotiationNeeded() {
1785 RTC_DCHECK_RUN_ON(signaling_thread());
1786 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001787 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001788}
1789
deadbeeffac06552015-11-25 11:26:01 -08001790rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001791 const std::string& kind,
1792 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001793 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001794 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1795 "Plan SdpSemantics. Please use AddTransceiver "
1796 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001797 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001798 if (IsClosed()) {
1799 return nullptr;
1800 }
Steve Anton4171afb2017-11-20 10:20:22 -08001801
Seth Hampson5b4f0752018-04-02 16:31:36 -07001802 // Internally we need to have one stream with Plan B semantics, so we
1803 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001804 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001805 if (stream_id.empty()) {
1806 stream_ids.push_back(rtc::CreateRandomUuid());
1807 RTC_LOG(LS_INFO)
1808 << "No stream_id specified for sender. Generated stream ID: "
1809 << stream_ids[0];
1810 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001811 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001812 }
1813
Steve Anton4171afb2017-11-20 10:20:22 -08001814 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001815 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001816 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001817 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001818 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001819 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001820 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001821 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001822 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001823 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001824 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001825 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001826 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001827 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001828 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001829 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001830 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001832 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001833 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001834 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001835
deadbeefe1f9d832016-01-14 15:35:42 -08001836 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001837}
1838
deadbeef70ab1a12015-09-28 16:53:55 -07001839std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1840 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001841 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001842 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001843 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001844 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001845 }
1846 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001847}
1848
Steve Anton4171afb2017-11-20 10:20:22 -08001849std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1850PeerConnection::GetSendersInternal() const {
1851 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1852 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001853 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001854 auto senders = transceiver->internal()->senders();
1855 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1856 }
1857 return all_senders;
1858}
1859
deadbeef70ab1a12015-09-28 16:53:55 -07001860std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1861PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001862 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001863 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001864 for (const auto& receiver : GetReceiversInternal()) {
1865 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001866 }
1867 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001868}
1869
Steve Anton4171afb2017-11-20 10:20:22 -08001870std::vector<
1871 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1872PeerConnection::GetReceiversInternal() const {
1873 std::vector<
1874 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1875 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001876 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001877 auto receivers = transceiver->internal()->receivers();
1878 all_receivers.insert(all_receivers.end(), receivers.begin(),
1879 receivers.end());
1880 }
1881 return all_receivers;
1882}
1883
Steve Anton9158ef62017-11-27 13:01:52 -08001884std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1885PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001886 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001887 RTC_CHECK(IsUnifiedPlan())
1888 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001889 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001890 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001891 all_transceivers.push_back(transceiver);
1892 }
1893 return all_transceivers;
1894}
1895
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001897 MediaStreamTrackInterface* track,
1898 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001899 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001900 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001901 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001902 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903 return false;
1904 }
1905
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001906 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001907 // The StatsCollector is used to tell if a track is valid because it may
1908 // remember tracks that the PeerConnection previously removed.
1909 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001910 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1911 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001912 return false;
1913 }
Steve Antonad182762018-09-05 20:22:40 +00001914 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1915 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 return true;
1917}
1918
hbos74e1a4f2016-09-15 23:33:01 -07001919void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001920 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001922 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001923 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001924 stats_collector_->GetStatsReport(callback);
1925}
1926
Henrik Boström1df1bf82018-03-20 13:24:20 +01001927void PeerConnection::GetStats(
1928 rtc::scoped_refptr<RtpSenderInterface> selector,
1929 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1930 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001931 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001932 RTC_DCHECK(callback);
1933 RTC_DCHECK(stats_collector_);
1934 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1935 if (selector) {
1936 for (const auto& proxy_transceiver : transceivers_) {
1937 for (const auto& proxy_sender :
1938 proxy_transceiver->internal()->senders()) {
1939 if (proxy_sender == selector) {
1940 internal_sender = proxy_sender->internal();
1941 break;
1942 }
1943 }
1944 if (internal_sender)
1945 break;
1946 }
1947 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001948 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001949 // belong to the PeerConnection (in Plan B, senders can be removed from the
1950 // PeerConnection). This means that "all the stats objects representing the
1951 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1952 // produces an empty stats report.
1953 stats_collector_->GetStatsReport(internal_sender, callback);
1954}
1955
1956void PeerConnection::GetStats(
1957 rtc::scoped_refptr<RtpReceiverInterface> selector,
1958 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1959 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001960 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001961 RTC_DCHECK(callback);
1962 RTC_DCHECK(stats_collector_);
1963 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1964 if (selector) {
1965 for (const auto& proxy_transceiver : transceivers_) {
1966 for (const auto& proxy_receiver :
1967 proxy_transceiver->internal()->receivers()) {
1968 if (proxy_receiver == selector) {
1969 internal_receiver = proxy_receiver->internal();
1970 break;
1971 }
1972 }
1973 if (internal_receiver)
1974 break;
1975 }
1976 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001977 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001978 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1979 // the PeerConnection). This means that "all the stats objects representing
1980 // the selector" is an empty set. Invoking GetStatsReport() with a null
1981 // selector produces an empty stats report.
1982 stats_collector_->GetStatsReport(internal_receiver, callback);
1983}
1984
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001986 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 return signaling_state_;
1988}
1989
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990PeerConnectionInterface::IceConnectionState
1991PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001992 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 return ice_connection_state_;
1994}
1995
Alex Loiko9289eda2018-11-23 16:18:59 +00001996PeerConnectionInterface::IceConnectionState
1997PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001998 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001999 return standardized_ice_connection_state_;
2000}
2001
Jonas Olsson635474e2018-10-18 15:58:17 +02002002PeerConnectionInterface::PeerConnectionState
2003PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002004 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002005 return connection_state_;
2006}
2007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008PeerConnectionInterface::IceGatheringState
2009PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002010 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002011 return ice_gathering_state_;
2012}
2013
Yves Gerey665174f2018-06-19 15:03:05 +02002014rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 const std::string& label,
2016 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002017 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002018 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002019
deadbeefab9b2d12015-10-14 11:33:11 -07002020 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002021
kwibergd1fe2812016-04-27 06:47:29 -07002022 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002023 if (config) {
2024 internal_config.reset(new InternalDataChannelInit(*config));
2025 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002026 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002027 InternalCreateDataChannel(label, internal_config.get()));
2028 if (!channel.get()) {
2029 return nullptr;
2030 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002032 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2033 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002034 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002035 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002036 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002037 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 return DataChannelProxy::Create(signaling_thread(), channel.get());
2039}
2040
Henrik Boström79b69802019-07-18 11:16:56 +02002041void PeerConnection::RestartIce() {
2042 RTC_DCHECK_RUN_ON(signaling_thread());
2043 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2044 current_local_description_.get(), pending_local_description_.get());
2045 UpdateNegotiationNeeded();
2046}
2047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002049 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002050 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002051 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002052
nisse7ce109a2017-01-31 00:57:56 -08002053 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002054 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002055 return;
2056 }
deadbeefab9b2d12015-10-14 11:33:11 -07002057
Steve Anton8d3444d2017-10-20 15:30:51 -07002058 if (IsClosed()) {
2059 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002060 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002061 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002062 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002063 return;
2064 }
2065
Steve Anton25ca0ac2019-06-25 10:40:48 -07002066 // If a session error has occurred the PeerConnection is in a possibly
2067 // inconsistent state so fail right away.
2068 if (session_error() != SessionError::kNone) {
2069 std::string error_message = GetSessionErrorMsg();
2070 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2071 PostCreateSessionDescriptionFailure(
2072 observer,
2073 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2074 return;
2075 }
2076
zhihuang1c378ed2017-08-17 14:10:50 -07002077 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002078 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002079 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002080 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002081 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002082 return;
2083 }
2084
Steve Anton22da89f2018-01-25 13:58:07 -08002085 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2086 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2087 if (IsUnifiedPlan()) {
2088 RTCError error = HandleLegacyOfferOptions(options);
2089 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002090 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002091 return;
2092 }
2093 }
2094
zhihuang1c378ed2017-08-17 14:10:50 -07002095 cricket::MediaSessionOptions session_options;
2096 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002097 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002098}
2099
Steve Anton22da89f2018-01-25 13:58:07 -08002100RTCError PeerConnection::HandleLegacyOfferOptions(
2101 const RTCOfferAnswerOptions& options) {
2102 RTC_DCHECK(IsUnifiedPlan());
2103
2104 if (options.offer_to_receive_audio == 0) {
2105 RemoveRecvDirectionFromReceivingTransceiversOfType(
2106 cricket::MEDIA_TYPE_AUDIO);
2107 } else if (options.offer_to_receive_audio == 1) {
2108 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2109 } else if (options.offer_to_receive_audio > 1) {
2110 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2111 "offer_to_receive_audio > 1 is not supported.");
2112 }
2113
2114 if (options.offer_to_receive_video == 0) {
2115 RemoveRecvDirectionFromReceivingTransceiversOfType(
2116 cricket::MEDIA_TYPE_VIDEO);
2117 } else if (options.offer_to_receive_video == 1) {
2118 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2119 } else if (options.offer_to_receive_video > 1) {
2120 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2121 "offer_to_receive_video > 1 is not supported.");
2122 }
2123
2124 return RTCError::OK();
2125}
2126
2127void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2128 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002129 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002130 RtpTransceiverDirection new_direction =
2131 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2132 if (new_direction != transceiver->direction()) {
2133 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2134 << " transceiver (MID="
2135 << transceiver->mid().value_or("<not set>") << ") from "
2136 << RtpTransceiverDirectionToString(
2137 transceiver->direction())
2138 << " to "
2139 << RtpTransceiverDirectionToString(new_direction)
2140 << " since CreateOffer specified offer_to_receive=0";
2141 transceiver->internal()->set_direction(new_direction);
2142 }
Steve Anton22da89f2018-01-25 13:58:07 -08002143 }
2144}
2145
2146void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2147 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002148 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002149 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002150 RTC_LOG(LS_INFO)
2151 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2152 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002153 RtpTransceiverInit init;
2154 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002155 AddTransceiver(media_type, nullptr, init,
2156 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002157 }
2158}
2159
2160std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2161PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2162 std::vector<
2163 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2164 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002165 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002166 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002167 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2168 receiving_transceivers.push_back(transceiver);
2169 }
2170 }
2171 return receiving_transceivers;
2172}
2173
htaa2a49d92016-03-04 02:51:39 -08002174void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2175 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002176 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002177 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002178 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002179 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002180 return;
2181 }
2182
Steve Anton25ca0ac2019-06-25 10:40:48 -07002183 // If a session error has occurred the PeerConnection is in a possibly
2184 // inconsistent state so fail right away.
2185 if (session_error() != SessionError::kNone) {
2186 std::string error_message = GetSessionErrorMsg();
2187 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2188 PostCreateSessionDescriptionFailure(
2189 observer,
2190 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2191 return;
2192 }
2193
Steve Antondffead82018-02-06 10:31:29 -08002194 if (!(signaling_state_ == kHaveRemoteOffer ||
2195 signaling_state_ == kHaveLocalPrAnswer)) {
2196 std::string error =
2197 "PeerConnection cannot create an answer in a state other than "
2198 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002199 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002200 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002201 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002202 return;
2203 }
2204
Steve Antondffead82018-02-06 10:31:29 -08002205 // The remote description should be set if we're in the right state.
2206 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002207
Steve Anton22da89f2018-01-25 13:58:07 -08002208 if (IsUnifiedPlan()) {
2209 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2210 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2211 "supported with Unified Plan semantics. Use the "
2212 "RtpTransceiver API instead.";
2213 }
2214 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2215 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2216 "supported with Unified Plan semantics. Use the "
2217 "RtpTransceiver API instead.";
2218 }
2219 }
2220
htaa2a49d92016-03-04 02:51:39 -08002221 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002222 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002223
Steve Antond25da372017-11-06 14:50:29 -08002224 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225}
2226
2227void PeerConnection::SetLocalDescription(
2228 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002229 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002230 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002231 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002232
Steve Anton80dd7b52018-02-16 17:08:42 -08002233 // The SetLocalDescription contract is that we take ownership of the session
2234 // description regardless of the outcome, so wrap it in a unique_ptr right
2235 // away. Ideally, SetLocalDescription's signature will be changed to take the
2236 // description as a unique_ptr argument to formalize this agreement.
2237 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2238
nisse7ce109a2017-01-31 00:57:56 -08002239 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002240 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241 return;
2242 }
Steve Anton8a006912017-12-04 15:25:56 -08002243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002245 PostSetSessionDescriptionFailure(
2246 observer,
2247 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 return;
2249 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002250
Steve Anton80dd7b52018-02-16 17:08:42 -08002251 // If a session error has occurred the PeerConnection is in a possibly
2252 // inconsistent state so fail right away.
2253 if (session_error() != SessionError::kNone) {
2254 std::string error_message = GetSessionErrorMsg();
2255 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002256 PostSetSessionDescriptionFailure(
2257 observer,
2258 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002259 return;
2260 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002261
Eldar Rello5ab79e62019-10-09 18:29:44 +03002262 // For SLD we support only explicit rollback.
2263 if (desc->GetType() == SdpType::kRollback) {
2264 if (IsUnifiedPlan()) {
2265 RTCError error = Rollback();
2266 if (error.ok()) {
2267 PostSetSessionDescriptionSuccess(observer);
2268 } else {
2269 PostSetSessionDescriptionFailure(observer, std::move(error));
2270 }
2271 } else {
2272 PostSetSessionDescriptionFailure(
2273 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2274 "Rollback not supported in Plan B"));
2275 }
2276 return;
2277 }
2278
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2280 if (!error.ok()) {
2281 std::string error_message = GetSetDescriptionErrorMessage(
2282 cricket::CS_LOCAL, desc->GetType(), error);
2283 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002284 PostSetSessionDescriptionFailure(
2285 observer,
2286 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002287 return;
2288 }
2289
2290 // Grab the description type before moving ownership to ApplyLocalDescription,
2291 // which may destroy it before returning.
2292 const SdpType type = desc->GetType();
2293
2294 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002295 // |desc| may be destroyed at this point.
2296
2297 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002298 // If ApplyLocalDescription fails, the PeerConnection could be in an
2299 // inconsistent state, so act conservatively here and set the session error
2300 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2301 SetSessionError(SessionError::kContent, error.message());
2302 std::string error_message =
2303 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2304 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002305 PostSetSessionDescriptionFailure(
2306 observer,
2307 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002308 return;
2309 }
Steve Anton8a006912017-12-04 15:25:56 -08002310 RTC_DCHECK(local_description());
2311
2312 PostSetSessionDescriptionSuccess(observer);
2313
Steve Antonad182762018-09-05 20:22:40 +00002314 // MaybeStartGathering needs to be called after posting
2315 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2316 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002317 transport_controller_->MaybeStartGathering();
2318
Steve Antona3a92c22017-12-07 10:27:41 -08002319 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002320 // TODO(deadbeef): We already had to hop to the network thread for
2321 // MaybeStartGathering...
2322 network_thread()->Invoke<void>(
2323 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2324 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002325 // Make UMA notes about what was agreed to.
2326 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002327 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002328
2329 if (IsUnifiedPlan()) {
2330 bool was_negotiation_needed = is_negotiation_needed_;
2331 UpdateNegotiationNeeded();
2332 if (signaling_state() == kStable && was_negotiation_needed &&
2333 is_negotiation_needed_) {
2334 Observer()->OnRenegotiationNeeded();
2335 }
2336 }
2337
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002338 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002339}
2340
2341RTCError PeerConnection::ApplyLocalDescription(
2342 std::unique_ptr<SessionDescriptionInterface> desc) {
2343 RTC_DCHECK_RUN_ON(signaling_thread());
2344 RTC_DCHECK(desc);
2345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 // Update stats here so that we have the most recent stats for tracks and
2347 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002348 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002349
Steve Antondcc3c022017-12-22 16:02:54 -08002350 // Take a reference to the old local description since it's used below to
2351 // compare against the new local description. When setting the new local
2352 // description, grab ownership of the replaced session description in case it
2353 // is the same as |old_local_description|, to keep it alive for the duration
2354 // of the method.
2355 const SessionDescriptionInterface* old_local_description =
2356 local_description();
2357 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002358 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002359 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002360 replaced_local_description = pending_local_description_
2361 ? std::move(pending_local_description_)
2362 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002363 current_local_description_ = std::move(desc);
2364 pending_local_description_ = nullptr;
2365 current_remote_description_ = std::move(pending_remote_description_);
2366 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002367 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002368 pending_local_description_ = std::move(desc);
2369 }
2370 // The session description to apply now must be accessed by
2371 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002372 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002373
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002374 // Report statistics about any use of simulcast.
2375 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2376 *local_description()->description());
2377
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002378 if (!is_caller_) {
2379 if (remote_description()) {
2380 // Remote description was applied first, so this PC is the callee.
2381 is_caller_ = false;
2382 } else {
2383 // Local description is applied first, so this PC is the caller.
2384 is_caller_ = true;
2385 }
2386 }
2387
Zhi Huange830e682018-03-30 10:48:35 -07002388 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2389 if (!error.ok()) {
2390 return error;
2391 }
2392
Steve Antondcc3c022017-12-22 16:02:54 -08002393 if (IsUnifiedPlan()) {
2394 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002395 cricket::CS_LOCAL, *local_description(), old_local_description,
2396 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002397 if (!error.ok()) {
2398 return error;
2399 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002400 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2401 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002402 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002403 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2404 // Note that code paths that don't set MID won't be able to use
2405 // information about DTLS transports.
2406 if (transceiver->mid()) {
2407 auto dtls_transport =
2408 LookupDtlsTransportByMidInternal(*transceiver->mid());
2409 transceiver->internal()->sender_internal()->set_transport(
2410 dtls_transport);
2411 transceiver->internal()->receiver_internal()->set_transport(
2412 dtls_transport);
2413 }
2414
Steve Antondcc3c022017-12-22 16:02:54 -08002415 const ContentInfo* content =
2416 FindMediaSectionForTransceiver(transceiver, local_description());
2417 if (!content) {
2418 continue;
2419 }
2420 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002421 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2422 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002423 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002424 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2425 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2426 // "recvonly", process the removal of a remote track for the media
2427 // description, given transceiver, removeList, and muteTracks.
2428 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2429 (transceiver->internal()->fired_direction() &&
2430 RtpTransceiverDirectionHasRecv(
2431 *transceiver->internal()->fired_direction()))) {
2432 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2433 &removed_streams);
2434 }
2435 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2436 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002437 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002438 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002439 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002440 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002441 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002442 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002443 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002444 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002445 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002446 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
2448 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002449 // Media channels will be created only when offer is set. These may use new
2450 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002451 if (type == SdpType::kOffer) {
2452 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2453 // description is applied. Restore back to old description.
2454 RTCError error = CreateChannels(*local_description()->description());
2455 if (!error.ok()) {
2456 return error;
2457 }
2458 }
Steve Antondcc3c022017-12-22 16:02:54 -08002459 // Remove unused channels if MediaContentDescription is rejected.
2460 RemoveUnusedChannels(local_description()->description());
2461 }
Steve Anton8a006912017-12-04 15:25:56 -08002462
Zhi Huange830e682018-03-30 10:48:35 -07002463 error = UpdateSessionState(type, cricket::CS_LOCAL,
2464 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002465 if (!error.ok()) {
2466 return error;
2467 }
Steve Antondcc3c022017-12-22 16:02:54 -08002468
Steve Anton8a006912017-12-04 15:25:56 -08002469 if (remote_description()) {
2470 // Now that we have a local description, we can push down remote candidates.
2471 UseCandidatesInSessionDescription(remote_description());
2472 }
2473
2474 pending_ice_restarts_.clear();
2475 if (session_error() != SessionError::kNone) {
2476 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2477 }
2478
deadbeefab9b2d12015-10-14 11:33:11 -07002479 // If setting the description decided our SSL role, allocate any necessary
2480 // SCTP sids.
2481 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002482 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002483 AllocateSctpSids(role);
2484 }
2485
Steve Antond3679212018-01-17 17:41:02 -08002486 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002487 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002488 const ContentInfo* content =
2489 FindMediaSectionForTransceiver(transceiver, local_description());
2490 if (!content) {
2491 continue;
2492 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002493 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2494 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002495 // 0 is a special value meaning "this sender has no associated send
2496 // stream". Need to call this so the sender won't attempt to configure
2497 // a no longer existing stream and run into DCHECKs in the lower
2498 // layers.
2499 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002500 } else {
2501 // Get the StreamParams from the channel which could generate SSRCs.
2502 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002503 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002504 streams[0].stream_ids());
2505 transceiver->internal()->sender_internal()->SetSsrc(
2506 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002507 }
2508 }
2509 } else {
2510 // Plan B semantics.
2511
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // Update state and SSRC of local MediaStreams and DataChannels based on the
2513 // local session description.
2514 const cricket::ContentInfo* audio_content =
2515 GetFirstAudioContent(local_description()->description());
2516 if (audio_content) {
2517 if (audio_content->rejected) {
2518 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2519 } else {
2520 const cricket::AudioContentDescription* audio_desc =
2521 audio_content->media_description()->as_audio();
2522 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2523 }
deadbeeffaac4972015-11-12 15:33:07 -08002524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
Steve Antondcc3c022017-12-22 16:02:54 -08002526 const cricket::ContentInfo* video_content =
2527 GetFirstVideoContent(local_description()->description());
2528 if (video_content) {
2529 if (video_content->rejected) {
2530 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2531 } else {
2532 const cricket::VideoContentDescription* video_desc =
2533 video_content->media_description()->as_video();
2534 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2535 }
deadbeeffaac4972015-11-12 15:33:07 -08002536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537 }
2538
2539 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002540 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002541 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002542 const cricket::RtpDataContentDescription* rtp_data_desc =
2543 data_content->media_description()->as_rtp_data();
2544 // rtp_data_desc will be null if this is an SCTP description.
2545 if (rtp_data_desc) {
2546 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002547 }
2548 }
2549
Henrik Boström79b69802019-07-18 11:16:56 +02002550 if (type == SdpType::kAnswer &&
2551 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2552 *current_local_description_)) {
2553 local_ice_credentials_to_replace_->ClearIceCredentials();
2554 }
2555
Steve Anton8a006912017-12-04 15:25:56 -08002556 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002557}
2558
Steve Anton06817cd2018-12-18 15:55:30 -08002559// The SDP parser used to populate these values by default for the 'content
2560// name' if an a=mid line was absent.
2561static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2562 switch (media_type) {
2563 case cricket::MEDIA_TYPE_AUDIO:
2564 return cricket::CN_AUDIO;
2565 case cricket::MEDIA_TYPE_VIDEO:
2566 return cricket::CN_VIDEO;
2567 case cricket::MEDIA_TYPE_DATA:
2568 return cricket::CN_DATA;
2569 }
2570 RTC_NOTREACHED();
2571 return "";
2572}
2573
2574void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002575 cricket::SessionDescription* new_remote_description) {
2576 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002577 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002578 const cricket::ContentInfos& local_contents =
2579 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002580 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002581 const cricket::ContentInfos& remote_contents =
2582 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002583 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002584 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2585 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002586 if (!content.name.empty()) {
2587 continue;
2588 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002589 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002590 absl::string_view source_explanation;
2591 if (IsUnifiedPlan()) {
2592 if (i < local_contents.size()) {
2593 new_mid = local_contents[i].name;
2594 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002595 } else if (i < remote_contents.size()) {
2596 new_mid = remote_contents[i].name;
2597 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002598 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002599 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002600 source_explanation = "generated just now";
2601 }
2602 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002603 new_mid = std::string(
2604 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002605 source_explanation = "to match pre-existing behavior";
2606 }
Steve Antond7180cc2019-02-07 10:44:53 -08002607 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002608 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002609 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002610 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2611 << " is missing an a=mid line. Filling in the value '"
2612 << new_mid << "' " << source_explanation << ".";
2613 }
2614}
2615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002617 SetSessionDescriptionObserver* observer,
2618 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002619 SetRemoteDescription(
2620 std::unique_ptr<SessionDescriptionInterface>(desc),
2621 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2622 new SetRemoteDescriptionObserverAdapter(this, observer)));
2623}
2624
2625void PeerConnection::SetRemoteDescription(
2626 std::unique_ptr<SessionDescriptionInterface> desc,
2627 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002628 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002629 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002630
nisse7ce109a2017-01-31 00:57:56 -08002631 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002632 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633 return;
2634 }
Steve Anton8a006912017-12-04 15:25:56 -08002635
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002637 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002638 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639 return;
2640 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002641
Steve Anton80dd7b52018-02-16 17:08:42 -08002642 // If a session error has occurred the PeerConnection is in a possibly
2643 // inconsistent state so fail right away.
2644 if (session_error() != SessionError::kNone) {
2645 std::string error_message = GetSessionErrorMsg();
2646 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2647 observer->OnSetRemoteDescriptionComplete(
2648 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2649 return;
2650 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03002651 if (IsUnifiedPlan()) {
2652 if (configuration_.enable_implicit_rollback) {
2653 if (desc->GetType() == SdpType::kOffer &&
2654 signaling_state() == kHaveLocalOffer) {
2655 Rollback();
2656 }
2657 }
2658 // Explicit rollback.
2659 if (desc->GetType() == SdpType::kRollback) {
2660 observer->OnSetRemoteDescriptionComplete(Rollback());
2661 return;
2662 }
2663 } else if (desc->GetType() == SdpType::kRollback) {
2664 observer->OnSetRemoteDescriptionComplete(
2665 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2666 "Rollback not supported in Plan B"));
2667 return;
2668 }
Steve Antonba42e992018-04-09 14:10:01 -07002669 if (desc->GetType() == SdpType::kOffer) {
2670 // Report to UMA the format of the received offer.
2671 ReportSdpFormatReceived(*desc);
2672 }
2673
Steve Anton06817cd2018-12-18 15:55:30 -08002674 // Handle remote descriptions missing a=mid lines for interop with legacy end
2675 // points.
2676 FillInMissingRemoteMids(desc->description());
2677
Steve Anton80dd7b52018-02-16 17:08:42 -08002678 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002679 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002680 std::string error_message = GetSetDescriptionErrorMessage(
2681 cricket::CS_REMOTE, desc->GetType(), error);
2682 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002683 observer->OnSetRemoteDescriptionComplete(
2684 RTCError(error.type(), std::move(error_message)));
2685 return;
2686 }
Steve Anton71439a62018-02-15 11:53:06 -08002687
Steve Anton80dd7b52018-02-16 17:08:42 -08002688 // Grab the description type before moving ownership to
2689 // ApplyRemoteDescription, which may destroy it before returning.
2690 const SdpType type = desc->GetType();
2691
2692 error = ApplyRemoteDescription(std::move(desc));
2693 // |desc| may be destroyed at this point.
2694
2695 if (!error.ok()) {
2696 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2697 // inconsistent state, so act conservatively here and set the session error
2698 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2699 SetSessionError(SessionError::kContent, error.message());
2700 std::string error_message =
2701 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2702 RTC_LOG(LS_ERROR) << error_message;
2703 observer->OnSetRemoteDescriptionComplete(
2704 RTCError(error.type(), std::move(error_message)));
2705 return;
2706 }
2707 RTC_DCHECK(remote_description());
2708
2709 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002710 // TODO(deadbeef): We already had to hop to the network thread for
2711 // MaybeStartGathering...
2712 network_thread()->Invoke<void>(
2713 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2714 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002715 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002716 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002717 }
2718
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002719 if (IsUnifiedPlan()) {
2720 bool was_negotiation_needed = is_negotiation_needed_;
2721 UpdateNegotiationNeeded();
2722 if (signaling_state() == kStable && was_negotiation_needed &&
2723 is_negotiation_needed_) {
2724 Observer()->OnRenegotiationNeeded();
2725 }
2726 }
2727
Steve Anton8a006912017-12-04 15:25:56 -08002728 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002729 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002730}
2731
2732RTCError PeerConnection::ApplyRemoteDescription(
2733 std::unique_ptr<SessionDescriptionInterface> desc) {
2734 RTC_DCHECK_RUN_ON(signaling_thread());
2735 RTC_DCHECK(desc);
2736
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 // Update stats here so that we have the most recent stats for tracks and
2738 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002739 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002740
Steve Antondcc3c022017-12-22 16:02:54 -08002741 // Take a reference to the old remote description since it's used below to
2742 // compare against the new remote description. When setting the new remote
2743 // description, grab ownership of the replaced session description in case it
2744 // is the same as |old_remote_description|, to keep it alive for the duration
2745 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002746 const SessionDescriptionInterface* old_remote_description =
2747 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002748 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002749 SdpType type = desc->GetType();
2750 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002751 replaced_remote_description = pending_remote_description_
2752 ? std::move(pending_remote_description_)
2753 : std::move(current_remote_description_);
2754 current_remote_description_ = std::move(desc);
2755 pending_remote_description_ = nullptr;
2756 current_local_description_ = std::move(pending_local_description_);
2757 } else {
2758 replaced_remote_description = std::move(pending_remote_description_);
2759 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760 }
Steve Anton8a006912017-12-04 15:25:56 -08002761 // The session description to apply now must be accessed by
2762 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002763 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002764
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002765 // Report statistics about any use of simulcast.
2766 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2767 *remote_description()->description());
2768
Zhi Huange830e682018-03-30 10:48:35 -07002769 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2770 if (!error.ok()) {
2771 return error;
2772 }
Steve Anton8a006912017-12-04 15:25:56 -08002773 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002774 if (IsUnifiedPlan()) {
2775 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002776 cricket::CS_REMOTE, *remote_description(), local_description(),
2777 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002778 if (!error.ok()) {
2779 return error;
2780 }
Steve Antondcc3c022017-12-22 16:02:54 -08002781 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002782 // Media channels will be created only when offer is set. These may use new
2783 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002784 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002785 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002786 // description is applied. Restore back to old description.
2787 RTCError error = CreateChannels(*remote_description()->description());
2788 if (!error.ok()) {
2789 return error;
2790 }
2791 }
Steve Antondcc3c022017-12-22 16:02:54 -08002792 // Remove unused channels if MediaContentDescription is rejected.
2793 RemoveUnusedChannels(remote_description()->description());
2794 }
Steve Anton8a006912017-12-04 15:25:56 -08002795
Zhi Huange830e682018-03-30 10:48:35 -07002796 // NOTE: Candidates allocation will be initiated only when
2797 // SetLocalDescription is called.
2798 error = UpdateSessionState(type, cricket::CS_REMOTE,
2799 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002800 if (!error.ok()) {
2801 return error;
2802 }
2803
2804 if (local_description() &&
2805 !UseCandidatesInSessionDescription(remote_description())) {
2806 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2807 }
2808
2809 if (old_remote_description) {
2810 for (const cricket::ContentInfo& content :
2811 old_remote_description->description()->contents()) {
2812 // Check if this new SessionDescription contains new ICE ufrag and
2813 // password that indicates the remote peer requests an ICE restart.
2814 // TODO(deadbeef): When we start storing both the current and pending
2815 // remote description, this should reset pending_ice_restarts and compare
2816 // against the current description.
2817 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2818 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002819 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002820 pending_ice_restarts_.insert(content.name);
2821 }
2822 } else {
2823 // We retain all received candidates only if ICE is not restarted.
2824 // When ICE is restarted, all previous candidates belong to an old
2825 // generation and should not be kept.
2826 // TODO(deadbeef): This goes against the W3C spec which says the remote
2827 // description should only contain candidates from the last set remote
2828 // description plus any candidates added since then. We should remove
2829 // this once we're sure it won't break anything.
2830 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2831 old_remote_description, content.name, mutable_remote_description());
2832 }
2833 }
2834 }
2835
2836 if (session_error() != SessionError::kNone) {
2837 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2838 }
2839
2840 // Set the the ICE connection state to connecting since the connection may
2841 // become writable with peer reflexive candidates before any remote candidate
2842 // is signaled.
2843 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2844 // is to have a new signal the indicates a change in checking state from the
2845 // transport and expose a new checking() member from transport that can be
2846 // read to determine the current checking state. The existing SignalConnecting
2847 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002848 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002849 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002850 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2851 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2852 }
2853
deadbeefab9b2d12015-10-14 11:33:11 -07002854 // If setting the description decided our SSL role, allocate any necessary
2855 // SCTP sids.
2856 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002857 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002858 AllocateSctpSids(role);
2859 }
2860
Steve Antondcc3c022017-12-22 16:02:54 -08002861 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002862 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002863 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002864 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002865 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002866 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002867 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002868 const ContentInfo* content =
2869 FindMediaSectionForTransceiver(transceiver, remote_description());
2870 if (!content) {
2871 continue;
2872 }
2873 const MediaContentDescription* media_desc = content->media_description();
2874 RtpTransceiverDirection local_direction =
2875 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002876 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2877 // RTCSessionDescription: Set the associated remote streams given
2878 // transceiver.[[Receiver]], msids, addList, and removeList".
2879 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2880 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2881 std::vector<std::string> stream_ids;
2882 if (!media_desc->streams().empty()) {
2883 // The remote description has signaled the stream IDs.
2884 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002885 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002886 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2887 << " (" << GetStreamIdsString(stream_ids) << ").";
2888 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2889 stream_ids, &added_streams,
2890 &removed_streams);
2891 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2892 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2893 // and transceiver's current direction is neither sendrecv nor recvonly,
2894 // process the addition of a remote track for the media description.
2895 if (!transceiver->fired_direction() ||
2896 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2897 RTC_LOG(LS_INFO)
2898 << "Processing the addition of a remote track for MID="
2899 << content->name << ".";
2900 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002901 }
Steve Antondcc3c022017-12-22 16:02:54 -08002902 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002903 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002904 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2905 // removal of a remote track for the media description, given transceiver,
2906 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002907 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002908 (transceiver->fired_direction() &&
2909 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2910 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2911 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002912 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002913 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002914 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002915 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002916 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002917 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002918 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002919 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002920 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002921 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2922 if (transceiver->mid()) {
2923 auto dtls_transport =
2924 LookupDtlsTransportByMidInternal(*transceiver->mid());
2925 transceiver->internal()->sender_internal()->set_transport(
2926 dtls_transport);
2927 transceiver->internal()->receiver_internal()->set_transport(
2928 dtls_transport);
2929 }
Steve Antondcc3c022017-12-22 16:02:54 -08002930 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002931 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002932 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002933 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002934 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2935 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002936 transceiver->Stop();
2937 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002938 if (!content->rejected &&
2939 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002940 if (!media_desc->streams().empty() &&
2941 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07002942 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
2943 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
2944 } else {
2945 transceiver->internal()
2946 ->receiver_internal()
2947 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002948 }
Steve Antond3679212018-01-17 17:41:02 -08002949 }
Steve Antondcc3c022017-12-22 16:02:54 -08002950 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002951 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002952 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002953 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002954 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002955 observer->OnTrack(transceiver);
2956 observer->OnAddTrack(transceiver->receiver(),
2957 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002958 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002959 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002960 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002961 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002962 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002963 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002964 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002965 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002966 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002967 }
Steve Antondcc3c022017-12-22 16:02:54 -08002968 }
2969
Henrik Boströmfdb92012017-11-09 19:55:44 +01002970 const cricket::ContentInfo* audio_content =
2971 GetFirstAudioContent(remote_description()->description());
2972 const cricket::ContentInfo* video_content =
2973 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002974 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002975 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002976 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002977 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002978 const cricket::RtpDataContentDescription* rtp_data_desc =
2979 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002980
2981 // Check if the descriptions include streams, just in case the peer supports
2982 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002983 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002984 (audio_desc && !audio_desc->streams().empty()) ||
2985 (video_desc && !video_desc->streams().empty())) {
2986 remote_peer_supports_msid_ = true;
2987 }
deadbeefab9b2d12015-10-14 11:33:11 -07002988
2989 // We wait to signal new streams until we finish processing the description,
2990 // since only at that point will new streams have all their tracks.
2991 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2992
Steve Antondcc3c022017-12-22 16:02:54 -08002993 if (!IsUnifiedPlan()) {
2994 // TODO(steveanton): When removing RTP senders/receivers in response to a
2995 // rejected media section, there is some cleanup logic that expects the
2996 // voice/ video channel to still be set. But in this method the voice/video
2997 // channel would have been destroyed by the SetRemoteDescription caller
2998 // above so the cleanup that relies on them fails to run. The RemoveSenders
2999 // calls should be moved to right before the DestroyChannel calls to fix
3000 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003001
Steve Antondcc3c022017-12-22 16:02:54 -08003002 // Find all audio rtp streams and create corresponding remote AudioTracks
3003 // and MediaStreams.
3004 if (audio_content) {
3005 if (audio_content->rejected) {
3006 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3007 } else {
3008 bool default_audio_track_needed =
3009 !remote_peer_supports_msid_ &&
3010 RtpTransceiverDirectionHasSend(audio_desc->direction());
3011 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3012 default_audio_track_needed, audio_desc->type(),
3013 new_streams);
3014 }
deadbeeffaac4972015-11-12 15:33:07 -08003015 }
deadbeefab9b2d12015-10-14 11:33:11 -07003016
Steve Antondcc3c022017-12-22 16:02:54 -08003017 // Find all video rtp streams and create corresponding remote VideoTracks
3018 // and MediaStreams.
3019 if (video_content) {
3020 if (video_content->rejected) {
3021 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3022 } else {
3023 bool default_video_track_needed =
3024 !remote_peer_supports_msid_ &&
3025 RtpTransceiverDirectionHasSend(video_desc->direction());
3026 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3027 default_video_track_needed, video_desc->type(),
3028 new_streams);
3029 }
deadbeeffaac4972015-11-12 15:33:07 -08003030 }
deadbeefab9b2d12015-10-14 11:33:11 -07003031
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003032 // If this is an RTP data transport, update the DataChannels with the
3033 // information from the remote peer.
3034 if (rtp_data_desc) {
3035 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003036 }
deadbeefab9b2d12015-10-14 11:33:11 -07003037
Steve Antondcc3c022017-12-22 16:02:54 -08003038 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003039 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003040 for (size_t i = 0; i < new_streams->count(); ++i) {
3041 MediaStreamInterface* new_stream = new_streams->at(i);
3042 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003043 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003044 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3045 }
deadbeefab9b2d12015-10-14 11:33:11 -07003046
Steve Antondcc3c022017-12-22 16:02:54 -08003047 UpdateEndedRemoteMediaStreams();
3048 }
deadbeefab9b2d12015-10-14 11:33:11 -07003049
Henrik Boström79b69802019-07-18 11:16:56 +02003050 if (type == SdpType::kAnswer &&
3051 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3052 *current_local_description_)) {
3053 local_ice_credentials_to_replace_->ClearIceCredentials();
3054 }
3055
Steve Anton8a006912017-12-04 15:25:56 -08003056 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003057}
3058
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003059void PeerConnection::SetAssociatedRemoteStreams(
3060 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3061 const std::vector<std::string>& stream_ids,
3062 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3063 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3064 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3065 for (const std::string& stream_id : stream_ids) {
3066 rtc::scoped_refptr<MediaStreamInterface> stream =
3067 remote_streams_->find(stream_id);
3068 if (!stream) {
3069 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3070 MediaStream::Create(stream_id));
3071 remote_streams_->AddStream(stream);
3072 added_streams->push_back(stream);
3073 }
3074 media_streams.push_back(stream);
3075 }
3076 // Special case: "a=msid" missing, use random stream ID.
3077 if (media_streams.empty() &&
3078 !(remote_description()->description()->msid_signaling() &
3079 cricket::kMsidSignalingMediaSection)) {
3080 if (!missing_msid_default_stream_) {
3081 missing_msid_default_stream_ = MediaStreamProxy::Create(
3082 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3083 added_streams->push_back(missing_msid_default_stream_);
3084 }
3085 media_streams.push_back(missing_msid_default_stream_);
3086 }
3087 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3088 receiver->streams();
3089 // SetStreams() will add/remove the receiver's track to/from the streams. This
3090 // differs from the spec - the spec uses an "addList" and "removeList" to
3091 // update the stream-track relationships in a later step. We do this earlier,
3092 // changing the order of things, but the end-result is the same.
3093 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3094 // instead. https://crbug.com/webrtc/9480
3095 receiver->SetStreams(media_streams);
3096 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3097}
3098
Steve Anton0f5400a2018-07-17 14:25:36 -07003099void PeerConnection::ProcessRemovalOfRemoteTrack(
3100 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3101 transceiver,
3102 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3103 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3104 RTC_DCHECK(transceiver->mid());
3105 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3106 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003108 transceiver->internal()->receiver_internal()->streams();
3109 // This will remove the remote track from the streams.
3110 transceiver->internal()->receiver_internal()->set_stream_ids({});
3111 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003112 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3113}
3114
3115void PeerConnection::RemoveRemoteStreamsIfEmpty(
3116 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3117 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3118 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3119 // streams, see if the stream was removed by checking if this was the last
3120 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003121 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003122 if (remote_stream->GetAudioTracks().empty() &&
3123 remote_stream->GetVideoTracks().empty()) {
3124 remote_streams_->RemoveStream(remote_stream);
3125 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003126 }
3127 }
3128}
3129
Steve Antondcc3c022017-12-22 16:02:54 -08003130RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3131 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003132 const SessionDescriptionInterface& new_session,
3133 const SessionDescriptionInterface* old_local_description,
3134 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003135 RTC_DCHECK(IsUnifiedPlan());
3136
Steve Anton7464fca2018-01-19 11:10:37 -08003137 const cricket::ContentGroup* bundle_group = nullptr;
3138 if (new_session.GetType() == SdpType::kOffer) {
3139 auto bundle_group_or_error =
3140 GetEarlyBundleGroup(*new_session.description());
3141 if (!bundle_group_or_error.ok()) {
3142 return bundle_group_or_error.MoveError();
3143 }
3144 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003145 }
Steve Antondcc3c022017-12-22 16:02:54 -08003146
Steve Antondcc3c022017-12-22 16:02:54 -08003147 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003148 for (size_t i = 0; i < new_contents.size(); ++i) {
3149 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003150 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003151 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003152 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3153 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003154 const cricket::ContentInfo* old_local_content = nullptr;
3155 if (old_local_description &&
3156 i < old_local_description->description()->contents().size()) {
3157 old_local_content =
3158 &old_local_description->description()->contents()[i];
3159 }
3160 const cricket::ContentInfo* old_remote_content = nullptr;
3161 if (old_remote_description &&
3162 i < old_remote_description->description()->contents().size()) {
3163 old_remote_content =
3164 &old_remote_description->description()->contents()[i];
3165 }
Steve Antondcc3c022017-12-22 16:02:54 -08003166 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003167 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3168 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003169 if (!transceiver_or_error.ok()) {
3170 return transceiver_or_error.MoveError();
3171 }
3172 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003173 RTCError error =
3174 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3175 if (!error.ok()) {
3176 return error;
3177 }
3178 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003179 if (GetDataMid() && new_content.name != *GetDataMid()) {
3180 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003181 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3182 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003183 continue;
3184 }
3185 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3186 if (!error.ok()) {
3187 return error;
3188 }
Steve Antondcc3c022017-12-22 16:02:54 -08003189 } else {
3190 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3191 "Unknown section type.");
3192 }
3193 }
3194
3195 return RTCError::OK();
3196}
3197
3198RTCError PeerConnection::UpdateTransceiverChannel(
3199 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3200 transceiver,
3201 const cricket::ContentInfo& content,
3202 const cricket::ContentGroup* bundle_group) {
3203 RTC_DCHECK(IsUnifiedPlan());
3204 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003205 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003206 if (content.rejected) {
3207 if (channel) {
3208 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003209 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003210 }
3211 } else {
3212 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003213 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003214 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003215 } else {
Steve Anton69470252018-02-09 11:43:08 -08003216 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003217 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003218 }
3219 if (!channel) {
3220 LOG_AND_RETURN_ERROR(
3221 RTCErrorType::INTERNAL_ERROR,
3222 "Failed to create channel for mid=" + content.name);
3223 }
3224 transceiver->internal()->SetChannel(channel);
3225 }
3226 }
3227 return RTCError::OK();
3228}
3229
Steve Antonfa2260d2017-12-28 16:38:23 -08003230RTCError PeerConnection::UpdateDataChannel(
3231 cricket::ContentSource source,
3232 const cricket::ContentInfo& content,
3233 const cricket::ContentGroup* bundle_group) {
3234 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003235 // If data channels are disabled, ignore this media section. CreateAnswer
3236 // will take care of rejecting it.
3237 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003238 }
3239 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003240 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003241 DestroyDataChannel();
3242 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003243 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003244 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003245 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003246 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3247 "Failed to create data channel.");
3248 }
3249 }
3250 if (source == cricket::CS_REMOTE) {
3251 const MediaContentDescription* data_desc = content.media_description();
3252 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3253 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3254 }
3255 }
3256 }
3257 return RTCError::OK();
3258}
3259
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003260// This method will extract any send encodings that were sent by the remote
3261// connection. This is currently only relevant for Simulcast scenario (where
3262// the number of layers may be communicated by the server).
3263static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3264 const MediaContentDescription& desc) {
3265 if (!desc.HasSimulcast()) {
3266 return {};
3267 }
3268 std::vector<RtpEncodingParameters> result;
3269 const SimulcastDescription& simulcast = desc.simulcast_description();
3270
3271 // This is a remote description, the parameters we are after should appear
3272 // as receive streams.
3273 for (const auto& alternatives : simulcast.receive_layers()) {
3274 RTC_DCHECK(!alternatives.empty());
3275 // There is currently no way to specify or choose from alternatives.
3276 // We will always use the first alternative, which is the most preferred.
3277 const SimulcastLayer& layer = alternatives[0];
3278 RtpEncodingParameters parameters;
3279 parameters.rid = layer.rid;
3280 parameters.active = !layer.is_paused;
3281 result.push_back(parameters);
3282 }
3283
3284 return result;
3285}
3286
3287static RTCError UpdateSimulcastLayerStatusInSender(
3288 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003289 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003290 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003291 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003292 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003293
3294 // The simulcast envelope cannot be changed, only the status of the streams.
3295 // So we will iterate over the send encodings rather than the layers.
3296 for (RtpEncodingParameters& encoding : parameters.encodings) {
3297 auto iter = std::find_if(layers.begin(), layers.end(),
3298 [&encoding](const SimulcastLayer& layer) {
3299 return layer.rid == encoding.rid;
3300 });
3301 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003302 if (iter == layers.end()) {
3303 disabled_layers.push_back(encoding.rid);
3304 continue;
3305 }
3306
3307 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003308 }
3309
Amit Hilbuch619b2942019-02-26 15:55:19 -08003310 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003311 if (result.ok()) {
3312 result = sender->DisableEncodingLayers(disabled_layers);
3313 }
3314
3315 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003316}
3317
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003318static bool SimulcastIsRejected(
3319 const ContentInfo* local_content,
3320 const MediaContentDescription& answer_media_desc) {
3321 bool simulcast_offered = local_content &&
3322 local_content->media_description() &&
3323 local_content->media_description()->HasSimulcast();
3324 bool simulcast_answered = answer_media_desc.HasSimulcast();
3325 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3326 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3327 return simulcast_offered && (!simulcast_answered || !rids_supported);
3328}
3329
Amit Hilbuch2297d332019-02-19 12:49:22 -08003330static RTCError DisableSimulcastInSender(
3331 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003332 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003333 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003334 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003335 return RTCError::OK();
3336 }
3337
Amit Hilbuch2297d332019-02-19 12:49:22 -08003338 std::vector<std::string> disabled_layers;
3339 std::transform(
3340 parameters.encodings.begin() + 1, parameters.encodings.end(),
3341 std::back_inserter(disabled_layers),
3342 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3343 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003344}
3345
Steve Antondcc3c022017-12-22 16:02:54 -08003346RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3347PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003348 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003349 size_t mline_index,
3350 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003351 const ContentInfo* old_local_content,
3352 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003353 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003354 // If this is an offer then the m= section might be recycled. If the m=
3355 // section is being recycled (defined as: rejected in the current local or
3356 // remote description and not rejected in new description), dissociate the
3357 // currently associated RtpTransceiver by setting its mid property to null,
3358 // and discard the mapping between the transceiver and its m= section index.
3359 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3360 old_remote_content)) {
3361 // We want to dissociate the transceiver that has the rejected mid.
3362 const std::string& old_mid =
3363 (old_local_content && old_local_content->rejected)
3364 ? old_local_content->name
3365 : old_remote_content->name;
3366 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003367 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003368 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3369 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003370 old_transceiver->internal()->set_mid(absl::nullopt);
3371 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003372 }
3373 }
3374 const MediaContentDescription* media_desc = content.media_description();
3375 auto transceiver = GetAssociatedTransceiver(content.name);
3376 if (source == cricket::CS_LOCAL) {
3377 // Find the RtpTransceiver that corresponds to this m= section, using the
3378 // mapping between transceivers and m= section indices established when
3379 // creating the offer.
3380 if (!transceiver) {
3381 transceiver = GetTransceiverByMLineIndex(mline_index);
3382 }
3383 if (!transceiver) {
3384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3385 "Unknown transceiver");
3386 }
3387 } else {
3388 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3389 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3390 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003391 // When simulcast is requested, a transceiver cannot be associated because
3392 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003393 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003394 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3395 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003396 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3397 }
3398 // If no RtpTransceiver was found in the previous step, create one with a
3399 // recvonly direction.
3400 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003401 RTC_LOG(LS_INFO) << "Adding "
3402 << cricket::MediaTypeToString(media_desc->type())
3403 << " transceiver for MID=" << content.name
3404 << " at i=" << mline_index
3405 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003406 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003407 std::vector<RtpEncodingParameters> send_encodings =
3408 GetSendEncodingsFromRemoteDescription(*media_desc);
3409 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3410 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003411 std::string receiver_id;
3412 if (!media_desc->streams().empty()) {
3413 receiver_id = media_desc->streams()[0].id;
3414 } else {
3415 receiver_id = rtc::CreateRandomUuid();
3416 }
3417 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003418 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003419 transceiver->internal()->set_direction(
3420 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003421 if (type == SdpType::kOffer) {
3422 transceiver_stable_states_by_transceivers_[transceiver] =
3423 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3424 absl::nullopt, absl::nullopt, true);
3425 }
Steve Antondcc3c022017-12-22 16:02:54 -08003426 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003427 // Check if the offer indicated simulcast but the answer rejected it.
3428 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003429 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003430 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003431 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003432 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003433 if (!error.ok()) {
3434 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3435 return std::move(error);
3436 }
3437 }
Steve Antondcc3c022017-12-22 16:02:54 -08003438 }
3439 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003440 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003441 LOG_AND_RETURN_ERROR(
3442 RTCErrorType::INVALID_PARAMETER,
3443 "Transceiver type does not match media description type.");
3444 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003445 if (media_desc->HasSimulcast()) {
3446 std::vector<SimulcastLayer> layers =
3447 source == cricket::CS_LOCAL
3448 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3449 : media_desc->simulcast_description()
3450 .receive_layers()
3451 .GetAllLayers();
3452 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003453 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003454 if (!error.ok()) {
3455 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3456 return std::move(error);
3457 }
3458 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003459 if (type == SdpType::kOffer) {
3460 // Make sure we don't overwrite existing stable states and that the
3461 // state is really going to change when adding new record to the map.
3462 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3463 if (it == transceiver_stable_states_by_transceivers_.end() &&
3464 (transceiver->internal()->mid() != content.name ||
3465 transceiver->internal()->mline_index() != mline_index)) {
3466 transceiver_stable_states_by_transceivers_[transceiver] =
3467 TransceiverStableState(transceiver->internal()->direction(),
3468 transceiver->internal()->mid(),
3469 transceiver->internal()->mline_index(), false);
3470 }
3471 }
3472
Steve Antondcc3c022017-12-22 16:02:54 -08003473 // Associate the found or created RtpTransceiver with the m= section by
3474 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3475 // section, and establish a mapping between the transceiver and the index of
3476 // the m= section.
3477 transceiver->internal()->set_mid(content.name);
3478 transceiver->internal()->set_mline_index(mline_index);
3479 return std::move(transceiver);
3480}
3481
3482rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3483PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3484 RTC_DCHECK(IsUnifiedPlan());
3485 for (auto transceiver : transceivers_) {
3486 if (transceiver->mid() == mid) {
3487 return transceiver;
3488 }
3489 }
3490 return nullptr;
3491}
3492
3493rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3494PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3495 RTC_DCHECK(IsUnifiedPlan());
3496 for (auto transceiver : transceivers_) {
3497 if (transceiver->internal()->mline_index() == mline_index) {
3498 return transceiver;
3499 }
3500 }
3501 return nullptr;
3502}
3503
3504rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3505PeerConnection::FindAvailableTransceiverToReceive(
3506 cricket::MediaType media_type) const {
3507 RTC_DCHECK(IsUnifiedPlan());
3508 // From JSEP section 5.10 (Applying a Remote Description):
3509 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3510 // the same type that were added to the PeerConnection by addTrack and are not
3511 // associated with any m= section and are not stopped, find the first such
3512 // RtpTransceiver.
3513 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003514 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003515 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3516 !transceiver->stopped()) {
3517 return transceiver;
3518 }
3519 }
3520 return nullptr;
3521}
3522
Steve Antoned10bd92017-12-05 10:52:59 -08003523const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3524 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3525 transceiver,
3526 const SessionDescriptionInterface* sdesc) const {
3527 RTC_DCHECK(transceiver);
3528 RTC_DCHECK(sdesc);
3529 if (IsUnifiedPlan()) {
3530 if (!transceiver->internal()->mid()) {
3531 // This transceiver is not associated with a media section yet.
3532 return nullptr;
3533 }
3534 return sdesc->description()->GetContentByName(
3535 *transceiver->internal()->mid());
3536 } else {
3537 // Plan B only allows at most one audio and one video section, so use the
3538 // first media section of that type.
3539 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003540 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003541 }
3542}
3543
deadbeef46c73892016-11-16 19:42:04 -08003544PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003545 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003546 return configuration_;
3547}
3548
Niels Möller2579f0c2019-08-19 09:58:17 +02003549RTCError PeerConnection::SetConfiguration(
3550 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003551 RTC_DCHECK_RUN_ON(signaling_thread());
3552 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003553 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003554 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3556 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003557 }
3558
Qingsi Wanga2d60672018-04-11 16:57:45 -07003559 // According to JSEP, after setLocalDescription, changing the candidate pool
3560 // size is not allowed, and changing the set of ICE servers will not result
3561 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003562 if (local_description() && configuration.ice_candidate_pool_size !=
3563 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003564 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3565 "Can't change candidate pool size after calling "
3566 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003567 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003568
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003569 if (local_description() &&
3570 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3572 "Can't change media_transport after calling "
3573 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003574 }
3575
3576 if (remote_description() &&
3577 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3579 "Can't change media_transport after calling "
3580 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003581 }
3582
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003583 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003584 configuration.use_media_transport_for_data_channels !=
3585 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3587 "Can't change media_transport_for_data_channels "
3588 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003589 }
3590
3591 if (remote_description() &&
3592 configuration.use_media_transport_for_data_channels !=
3593 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003594 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3595 "Can't change media_transport_for_data_channels "
3596 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003597 }
3598
3599 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003600 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003601 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3602 "Can't change crypto_options after calling "
3603 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003604 }
3605
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003606 if (local_description() && configuration.use_datagram_transport !=
3607 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003608 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3609 "Can't change use_datagram_transport "
3610 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003611 }
3612
3613 if (remote_description() && configuration.use_datagram_transport !=
3614 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003615 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3616 "Can't change use_datagram_transport "
3617 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003618 }
3619
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003620 if (local_description() &&
3621 configuration.use_datagram_transport_for_data_channels !=
3622 configuration_.use_datagram_transport_for_data_channels) {
3623 LOG_AND_RETURN_ERROR(
3624 RTCErrorType::INVALID_MODIFICATION,
3625 "Can't change use_datagram_transport_for_data_channels "
3626 "after calling SetLocalDescription.");
3627 }
3628
3629 if (remote_description() &&
3630 configuration.use_datagram_transport_for_data_channels !=
3631 configuration_.use_datagram_transport_for_data_channels) {
3632 LOG_AND_RETURN_ERROR(
3633 RTCErrorType::INVALID_MODIFICATION,
3634 "Can't change use_datagram_transport_for_data_channels "
3635 "after calling SetRemoteDescription.");
3636 }
3637
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003638 if (local_description() &&
3639 configuration.use_datagram_transport_for_data_channels_receive_only !=
3640 configuration_
3641 .use_datagram_transport_for_data_channels_receive_only) {
3642 LOG_AND_RETURN_ERROR(
3643 RTCErrorType::INVALID_MODIFICATION,
3644 "Can't change use_datagram_transport_for_data_channels_receive_only "
3645 "after calling SetLocalDescription.");
3646 }
3647
3648 if (remote_description() &&
3649 configuration.use_datagram_transport_for_data_channels_receive_only !=
3650 configuration_
3651 .use_datagram_transport_for_data_channels_receive_only) {
3652 LOG_AND_RETURN_ERROR(
3653 RTCErrorType::INVALID_MODIFICATION,
3654 "Can't change use_datagram_transport_for_data_channels_receive_only "
3655 "after calling SetRemoteDescription.");
3656 }
3657
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003658 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003659 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003660 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003661 *configuration.use_datagram_transport) ||
3662 (configuration.use_datagram_transport_for_data_channels &&
3663 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003664 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3665 << "Media transport requires MaxBundle policy.";
3666 }
3667
deadbeef293e9262017-01-11 12:28:30 -08003668 // The simplest (and most future-compatible) way to tell if the config was
3669 // modified in an invalid way is to copy each property we do support
3670 // modifying, then use operator==. There are far more properties we don't
3671 // support modifying than those we do, and more could be added.
3672 RTCConfiguration modified_config = configuration_;
3673 modified_config.servers = configuration.servers;
3674 modified_config.type = configuration.type;
3675 modified_config.ice_candidate_pool_size =
3676 configuration.ice_candidate_pool_size;
3677 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003678 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3679 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003680 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003681 modified_config.ice_check_interval_strong_connectivity =
3682 configuration.ice_check_interval_strong_connectivity;
3683 modified_config.ice_check_interval_weak_connectivity =
3684 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003685 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3686 modified_config.ice_unwritable_min_checks =
3687 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003688 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003689 modified_config.stun_candidate_keepalive_interval =
3690 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003691 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003692 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003693 modified_config.active_reset_srtp_params =
3694 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003695 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003696 modified_config.use_media_transport_for_data_channels =
3697 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003698 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003699 modified_config.use_datagram_transport_for_data_channels =
3700 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003701 modified_config.use_datagram_transport_for_data_channels_receive_only =
3702 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02003703 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003704 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3706 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003707 }
3708
Steve Anton038834f2017-07-14 15:59:59 -07003709 // Validate the modified configuration.
3710 RTCError validate_error = ValidateConfiguration(modified_config);
3711 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003712 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003713 }
3714
deadbeef293e9262017-01-11 12:28:30 -08003715 // Note that this isn't possible through chromium, since it's an unsigned
3716 // short in WebIDL.
3717 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003718 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003719 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003720 }
3721
3722 // Parse ICE servers before hopping to network thread.
3723 cricket::ServerAddresses stun_servers;
3724 std::vector<cricket::RelayServerConfig> turn_servers;
3725 RTCErrorType parse_error =
3726 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3727 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003728 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003729 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003730 // Add the turn logging id to all turn servers
3731 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3732 turn_server.turn_logging_id = configuration.turn_logging_id;
3733 }
3734
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003735 // Note if STUN or TURN servers were supplied.
3736 if (!stun_servers.empty()) {
3737 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3738 }
3739 if (!turn_servers.empty()) {
3740 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3741 }
deadbeef293e9262017-01-11 12:28:30 -08003742
3743 // In theory this shouldn't fail.
3744 if (!network_thread()->Invoke<bool>(
3745 RTC_FROM_HERE,
3746 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3747 stun_servers, turn_servers, modified_config.type,
3748 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003749 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003750 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003751 modified_config.stun_candidate_keepalive_interval,
3752 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003753 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3754 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003755 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003756
deadbeefd1a38b52016-12-10 13:15:33 -08003757 // As described in JSEP, calling setConfiguration with new ICE servers or
3758 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3759 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003760 if (modified_config.servers != configuration_.servers ||
3761 modified_config.type != configuration_.type ||
3762 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003763 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003764 }
skvladd1f5fda2017-02-03 16:54:05 -08003765
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003766 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003767
3768 use_datagram_transport_ = datagram_transport_config_.enabled &&
3769 modified_config.use_datagram_transport.value_or(
3770 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003771 use_datagram_transport_for_data_channels_ =
3772 datagram_transport_data_channel_config_.enabled &&
3773 modified_config.use_datagram_transport_for_data_channels.value_or(
3774 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003775 use_datagram_transport_for_data_channels_receive_only_ =
3776 modified_config.use_datagram_transport_for_data_channels_receive_only
3777 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003778 transport_controller_->SetMediaTransportSettings(
3779 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003780 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003781 use_datagram_transport_, use_datagram_transport_for_data_channels_,
3782 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08003783
Zhi Huangb57e1692018-06-12 11:41:11 -07003784 if (configuration_.active_reset_srtp_params !=
3785 modified_config.active_reset_srtp_params) {
3786 transport_controller_->SetActiveResetSrtpParams(
3787 modified_config.active_reset_srtp_params);
3788 }
3789
deadbeef293e9262017-01-11 12:28:30 -08003790 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003791 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003792 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003793}
3794
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003795bool PeerConnection::AddIceCandidate(
3796 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003797 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003798 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003799 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003800 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003801 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003802 return false;
3803 }
Steve Antond25da372017-11-06 14:50:29 -08003804
3805 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003806 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003807 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003808 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003809 return false;
3810 }
3811
3812 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003813 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003814 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003815 return false;
3816 }
3817
3818 bool valid = false;
3819 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3820 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003821 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003822 return false;
3823 }
3824
3825 // Add this candidate to the remote session description.
3826 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003827 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003828 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003829 return false;
3830 }
3831
3832 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003833 bool result = UseCandidate(ice_candidate);
3834 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003835 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003836 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3837 } else {
3838 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3839 }
3840 return result;
Steve Antond25da372017-11-06 14:50:29 -08003841 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003842 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003843 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003844 return true;
3845 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003846}
3847
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003848bool PeerConnection::RemoveIceCandidates(
3849 const std::vector<cricket::Candidate>& candidates) {
3850 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003851 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003852 if (IsClosed()) {
3853 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3854 return false;
3855 }
3856
Steve Antond25da372017-11-06 14:50:29 -08003857 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003858 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3859 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003860 return false;
3861 }
3862
3863 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003864 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003865 return false;
3866 }
3867
3868 size_t number_removed =
3869 mutable_remote_description()->RemoveCandidates(candidates);
3870 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003871 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003872 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003873 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003874 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003875 }
3876
3877 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003878 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3879 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003880 RTC_LOG(LS_ERROR)
3881 << "RemoveIceCandidates: Error when removing remote candidates: "
3882 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003883 }
3884 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003885}
3886
Niels Möller0c4f7be2018-05-07 14:01:37 +02003887RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003888 if (!worker_thread()->IsCurrent()) {
3889 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003890 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003891 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003892 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003893
Niels Möller0c4f7be2018-05-07 14:01:37 +02003894 const bool has_min = bitrate.min_bitrate_bps.has_value();
3895 const bool has_start = bitrate.start_bitrate_bps.has_value();
3896 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003897 if (has_min && *bitrate.min_bitrate_bps < 0) {
3898 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3899 "min_bitrate_bps <= 0");
3900 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003901 if (has_start) {
3902 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003903 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003904 "start_bitrate_bps < min_bitrate_bps");
3905 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003906 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3907 "curent_bitrate_bps < 0");
3908 }
3909 }
3910 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003911 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003912 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003913 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003914 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3915 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3916 "max_bitrate_bps < min_bitrate_bps");
3917 } else if (*bitrate.max_bitrate_bps < 0) {
3918 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3919 "max_bitrate_bps < 0");
3920 }
3921 }
3922
zstein4b979802017-06-02 14:37:37 -07003923 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003924 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003925
3926 return RTCError::OK();
3927}
3928
henrika5f6bf242017-11-01 11:06:56 +01003929void PeerConnection::SetAudioPlayout(bool playout) {
3930 if (!worker_thread()->IsCurrent()) {
3931 worker_thread()->Invoke<void>(
3932 RTC_FROM_HERE,
3933 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3934 return;
3935 }
3936 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003937 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003938 audio_state->SetPlayout(playout);
3939}
3940
3941void PeerConnection::SetAudioRecording(bool recording) {
3942 if (!worker_thread()->IsCurrent()) {
3943 worker_thread()->Invoke<void>(
3944 RTC_FROM_HERE,
3945 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
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->SetRecording(recording);
3951}
3952
Steve Anton8c0f7a72017-10-03 10:03:10 -07003953std::unique_ptr<rtc::SSLCertificate>
3954PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003955 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3956 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003957 return nullptr;
3958 }
Steve Antonf25303e2018-10-16 15:23:31 -07003959 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003960}
3961
Zhi Huang70b820f2018-01-27 14:16:15 -08003962std::unique_ptr<rtc::SSLCertChain>
3963PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003964 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003965 auto audio_transceiver = GetFirstAudioTransceiver();
3966 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003967 return nullptr;
3968 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003969 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003970 audio_transceiver->internal()->channel()->transport_name());
3971}
3972
3973rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3974PeerConnection::GetFirstAudioTransceiver() const {
3975 for (auto transceiver : transceivers_) {
3976 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3977 return transceiver;
3978 }
3979 }
3980 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003981}
3982
Bjorn Tereliusde939432017-11-20 17:38:14 +01003983bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3984 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003985 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02003986 RTC_FROM_HERE,
3987 [this, output = std::move(output), output_period_ms]() mutable {
3988 return StartRtcEventLog_w(std::move(output), output_period_ms);
3989 });
ivoc14d5dbe2016-07-04 07:06:55 -07003990}
3991
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003992bool PeerConnection::StartRtcEventLog(
3993 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003994 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3995 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3996 output_period_ms = 5000;
3997 }
3998 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003999}
4000
ivoc14d5dbe2016-07-04 07:06:55 -07004001void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004002 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004003 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4004}
4005
Harald Alvestrandad88c882018-11-28 16:47:46 +01004006rtc::scoped_refptr<DtlsTransportInterface>
4007PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004008 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004009 return transport_controller_->LookupDtlsTransportByMid(mid);
4010}
4011
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004012rtc::scoped_refptr<DtlsTransport>
4013PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004014 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004015 return transport_controller_->LookupDtlsTransportByMid(mid);
4016}
4017
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004018rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4019 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004020 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004021 if (!sctp_mid_) {
4022 return nullptr;
4023 }
4024 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004025}
4026
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004027const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004028 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004029 return pending_local_description_ ? pending_local_description_.get()
4030 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004031}
4032
4033const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004034 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004035 return pending_remote_description_ ? pending_remote_description_.get()
4036 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004037}
4038
deadbeeffe4a8a42016-12-20 17:56:17 -08004039const SessionDescriptionInterface* PeerConnection::current_local_description()
4040 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004041 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004042 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004043}
4044
4045const SessionDescriptionInterface* PeerConnection::current_remote_description()
4046 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004047 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004048 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004049}
4050
4051const SessionDescriptionInterface* PeerConnection::pending_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 pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004055}
4056
4057const SessionDescriptionInterface* PeerConnection::pending_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 pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004061}
4062
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004063void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004064 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004065 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004066 // Update stats here so that we have the most recent stats for tracks and
4067 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004068 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004069
Steve Anton75737c02017-11-06 10:37:17 -08004070 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004071 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004072
Mirko Bonadei739baf02019-01-27 17:29:42 +01004073 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004074 transceiver->Stop();
4075 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004076
4077 // Ensure that all asynchronous stats requests are completed before destroying
4078 // the transport controller below.
4079 if (stats_collector_) {
4080 stats_collector_->WaitForPendingRequest();
4081 }
4082
4083 // Don't destroy BaseChannels until after stats has been cleaned up so that
4084 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004085 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004086
Qingsi Wang93a84392018-01-30 17:13:09 -08004087 // The event log is used in the transport controller, which must be outlived
4088 // by the former. CreateOffer by the peer connection is implemented
4089 // asynchronously and if the peer connection is closed without resetting the
4090 // WebRTC session description factory, the session description factory would
4091 // call the transport controller.
4092 webrtc_session_desc_factory_.reset();
4093 transport_controller_.reset();
4094
deadbeef42a42632017-03-10 15:18:00 -08004095 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004096 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4097 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004098
Steve Anton978b8762017-09-29 12:15:02 -07004099 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004100 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004101 call_.reset();
4102 // The event log must outlive call (and any other object that uses it).
4103 event_log_.reset();
4104 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004105 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004106 // The .h file says that observer can be discarded after close() returns.
4107 // Make sure this is true.
4108 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004109}
4110
Steve Antonad182762018-09-05 20:22:40 +00004111void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004112 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004113 switch (msg->message_id) {
4114 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4115 SetSessionDescriptionMsg* param =
4116 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4117 param->observer->OnSuccess();
4118 delete param;
4119 break;
4120 }
4121 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4122 SetSessionDescriptionMsg* param =
4123 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4124 param->observer->OnFailure(std::move(param->error));
4125 delete param;
4126 break;
4127 }
4128 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4129 CreateSessionDescriptionMsg* param =
4130 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4131 param->observer->OnFailure(std::move(param->error));
4132 delete param;
4133 break;
4134 }
4135 case MSG_GETSTATS: {
4136 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4137 StatsReports reports;
4138 stats_->GetStats(param->track, &reports);
4139 param->observer->OnComplete(reports);
4140 delete param;
4141 break;
4142 }
4143 case MSG_FREE_DATACHANNELS: {
4144 sctp_data_channels_to_free_.clear();
4145 break;
4146 }
4147 case MSG_REPORT_USAGE_PATTERN: {
4148 ReportUsagePattern();
4149 break;
4150 }
4151 default:
4152 RTC_NOTREACHED() << "Not implemented";
4153 break;
4154 }
4155}
4156
Steve Antonafb0bb72018-02-20 11:35:37 -08004157cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4158 RTC_DCHECK(!IsUnifiedPlan());
4159 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4160 GetAudioTransceiver()->internal()->channel());
4161 if (voice_channel) {
4162 return voice_channel->media_channel();
4163 } else {
4164 return nullptr;
4165 }
4166}
4167
4168cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4169 RTC_DCHECK(!IsUnifiedPlan());
4170 auto* video_channel = static_cast<cricket::VideoChannel*>(
4171 GetVideoTransceiver()->internal()->channel());
4172 if (video_channel) {
4173 return video_channel->media_channel();
4174 } else {
4175 return nullptr;
4176 }
4177}
4178
Steve Anton4171afb2017-11-20 10:20:22 -08004179void PeerConnection::CreateAudioReceiver(
4180 MediaStreamInterface* stream,
4181 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004182 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4183 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004184 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4185 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004186 auto* audio_receiver = new AudioRtpReceiver(
4187 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004188 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004189 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4190 audio_receiver->SetupUnsignaledMediaChannel();
4191 } else {
4192 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4193 }
Steve Antond3679212018-01-17 17:41:02 -08004194 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4195 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004196 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004197 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004198 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004199}
4200
Steve Anton4171afb2017-11-20 10:20:22 -08004201void PeerConnection::CreateVideoReceiver(
4202 MediaStreamInterface* stream,
4203 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004204 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4205 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004206 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4207 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004208 auto* video_receiver = new VideoRtpReceiver(
4209 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004210 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004211 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4212 video_receiver->SetupUnsignaledMediaChannel();
4213 } else {
4214 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4215 }
Steve Antond3679212018-01-17 17:41:02 -08004216 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4217 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004218 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004219 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004220 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004221}
4222
deadbeef70ab1a12015-09-28 16:53:55 -07004223// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4224// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004225rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004226 const RtpSenderInfo& remote_sender_info) {
4227 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4228 if (!receiver) {
4229 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4230 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004231 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004232 }
Steve Anton4171afb2017-11-20 10:20:22 -08004233 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4234 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4235 } else {
4236 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4237 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004238 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004239}
4240
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004241void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4242 MediaStreamInterface* stream) {
4243 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004244 RTC_DCHECK(track);
4245 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004246 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004247 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004248 // We already have a sender for this track, so just change the stream_id
4249 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004250 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004251 return;
4252 }
4253
4254 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004255 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004256 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004257 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004258 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004259 // If the sender has already been configured in SDP, we call SetSsrc,
4260 // which will connect the sender to the underlying transport. This can
4261 // occur if a local session description that contains the ID of the sender
4262 // is set before AddStream is called. It can also occur if the local
4263 // session description is not changed and RemoveStream is called, and
4264 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004265 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004266 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004267 if (sender_info) {
4268 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004269 }
4270}
4271
4272// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4273// indefinitely, when we have unified plan SDP.
4274void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4275 MediaStreamInterface* stream) {
4276 RTC_DCHECK(!IsClosed());
4277 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004278 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004279 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4280 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004281 return;
4282 }
Steve Anton4171afb2017-11-20 10:20:22 -08004283 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004284}
4285
4286void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4287 MediaStreamInterface* stream) {
4288 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004289 RTC_DCHECK(track);
4290 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004291 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004292 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004293 // We already have a sender for this track, so just change the stream_id
4294 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004295 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004296 return;
4297 }
4298
4299 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004300 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004301 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004302 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004303 GetVideoTransceiver()->internal()->AddSender(new_sender);
4304 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004305 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004306 if (sender_info) {
4307 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004308 }
4309}
4310
4311void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4312 MediaStreamInterface* stream) {
4313 RTC_DCHECK(!IsClosed());
4314 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004315 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004316 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4317 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004318 return;
4319 }
Steve Anton4171afb2017-11-20 10:20:22 -08004320 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004321}
4322
Steve Antonba818672017-11-06 10:21:57 -08004323void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004324 if (ice_connection_state_ == new_state) {
4325 return;
4326 }
4327
deadbeefcbecd352015-09-23 11:50:27 -07004328 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004329 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004330 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004331 return;
4332 }
Steve Antonba818672017-11-06 10:21:57 -08004333
Mirko Bonadei675513b2017-11-09 11:09:25 +01004334 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4335 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004336 RTC_DCHECK(ice_connection_state_ !=
4337 PeerConnectionInterface::kIceConnectionClosed);
4338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004339 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004340 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004341}
4342
Alex Loiko9289eda2018-11-23 16:18:59 +00004343void PeerConnection::SetStandardizedIceConnectionState(
4344 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004345 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004346 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004347 }
4348
4349 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004350 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004351 }
4352
4353 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4354 << standardized_ice_connection_state_ << " => " << new_state;
4355
Alex Loiko9289eda2018-11-23 16:18:59 +00004356 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004357 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004358}
4359
Jonas Olsson635474e2018-10-18 15:58:17 +02004360void PeerConnection::SetConnectionState(
4361 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004362 if (connection_state_ == new_state)
4363 return;
4364 if (IsClosed())
4365 return;
4366 connection_state_ = new_state;
4367 Observer()->OnConnectionChange(new_state);
4368}
4369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004370void PeerConnection::OnIceGatheringChange(
4371 PeerConnectionInterface::IceGatheringState new_state) {
4372 if (IsClosed()) {
4373 return;
4374 }
4375 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004376 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004377}
4378
jbauch81bf7b02017-03-25 08:31:12 -07004379void PeerConnection::OnIceCandidate(
4380 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004381 if (IsClosed()) {
4382 return;
4383 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004384 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004385 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004386}
4387
Eldar Relloda13ea22019-06-01 12:23:43 +03004388void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4389 const std::string& url,
4390 int error_code,
4391 const std::string& error_text) {
4392 if (IsClosed()) {
4393 return;
4394 }
4395 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4396}
4397
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004398void PeerConnection::OnIceCandidatesRemoved(
4399 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004400 if (IsClosed()) {
4401 return;
4402 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004403 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004404}
4405
Alex Drake00c7ecf2019-08-06 10:54:47 -07004406void PeerConnection::OnSelectedCandidatePairChanged(
4407 const cricket::CandidatePairChangeEvent& event) {
4408 if (IsClosed()) {
4409 return;
4410 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004411
Qingsi Wangcc46b102019-09-12 11:19:01 -07004412 if (event.selected_candidate_pair.local_candidate().type() ==
4413 LOCAL_PORT_TYPE &&
4414 event.selected_candidate_pair.remote_candidate().type() ==
4415 LOCAL_PORT_TYPE) {
4416 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4417 }
4418
Alex Drake00c7ecf2019-08-06 10:54:47 -07004419 Observer()->OnIceSelectedCandidatePairChanged(event);
4420}
4421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004422void PeerConnection::ChangeSignalingState(
4423 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004424 if (signaling_state_ == signaling_state) {
4425 return;
4426 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004427 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4428 << GetSignalingStateString(signaling_state_)
4429 << " New state: "
4430 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004431 signaling_state_ = signaling_state;
4432 if (signaling_state == kClosed) {
4433 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004434 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004435 standardized_ice_connection_state_ =
4436 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004437 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4438 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004439 if (ice_gathering_state_ != kIceGatheringComplete) {
4440 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004441 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004442 }
4443 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004444 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004445}
4446
deadbeefeb459812015-12-15 19:24:43 -08004447void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4448 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004449 if (IsClosed()) {
4450 return;
4451 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004452 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004453 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004454}
4455
deadbeefeb459812015-12-15 19:24:43 -08004456void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4457 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004458 if (IsClosed()) {
4459 return;
4460 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004461 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004462 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004463}
4464
4465void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4466 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004467 if (IsClosed()) {
4468 return;
4469 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004470 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004471 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004472}
4473
4474void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4475 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004476 if (IsClosed()) {
4477 return;
4478 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004479 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004480 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004481}
4482
Henrik Boström31638672017-11-23 17:48:32 +01004483void PeerConnection::PostSetSessionDescriptionSuccess(
4484 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004485 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4486 signaling_thread()->Post(RTC_FROM_HERE, this,
4487 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004488}
4489
deadbeefab9b2d12015-10-14 11:33:11 -07004490void PeerConnection::PostSetSessionDescriptionFailure(
4491 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004492 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004493 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004494 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4495 msg->error = std::move(error);
4496 signaling_thread()->Post(RTC_FROM_HERE, this,
4497 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004498}
4499
4500void PeerConnection::PostCreateSessionDescriptionFailure(
4501 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004502 RTCError error) {
4503 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004504 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4505 msg->error = std::move(error);
4506 signaling_thread()->Post(RTC_FROM_HERE, this,
4507 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004508}
4509
zhihuang1c378ed2017-08-17 14:10:50 -07004510void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004511 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004512 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004513 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004514
Steve Antondcc3c022017-12-22 16:02:54 -08004515 if (IsUnifiedPlan()) {
4516 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4517 } else {
4518 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4519 }
4520
Steve Antonfa2260d2017-12-28 16:38:23 -08004521 // Intentionally unset the data channel type for RTP data channel with the
4522 // second condition. Otherwise the RTP data channels would be successfully
4523 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4524 // when building with chromium. We want to leave RTP data channels broken, so
4525 // people won't try to use them.
4526 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4527 session_options->data_channel_type = data_channel_type();
4528 }
4529
Steve Antondcc3c022017-12-22 16:02:54 -08004530 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004531 bool ice_restart = offer_answer_options.ice_restart ||
4532 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004533 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004534 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004535 options.transport_options.enable_ice_renomination =
4536 configuration_.enable_ice_renomination;
4537 }
4538
4539 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004540 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004541 session_options->pooled_ice_credentials =
4542 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4543 RTC_FROM_HERE,
4544 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4545 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004546 session_options->offer_extmap_allow_mixed =
4547 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004548
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004549 if (configuration_.use_media_transport ||
4550 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004551 session_options->media_transport_settings =
4552 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4553 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004554
4555 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004556 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004557 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004558 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004559 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004560 if (!params) {
4561 continue;
4562 }
4563 options.transport_options.opaque_parameters = params;
4564 if ((use_datagram_transport_ &&
4565 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4566 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4567 (use_datagram_transport_for_data_channels_ &&
4568 options.type == cricket::MEDIA_TYPE_DATA)) {
4569 options.alt_protocol = params->protocol;
4570 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004571 }
4572 }
4573
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004574 // Allow fallback for using obsolete SCTP syntax.
4575 // Note that the default in |session_options| is true, while
4576 // the default in |options| is false.
4577 session_options->use_obsolete_sctp_sdp =
4578 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004579}
4580
4581void PeerConnection::GetOptionsForPlanBOffer(
4582 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4583 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004584 // Figure out transceiver directional preferences.
4585 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4586 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4587
4588 // By default, generate sendrecv/recvonly m= sections.
4589 bool recv_audio = true;
4590 bool recv_video = true;
4591
4592 // By default, only offer a new m= section if we have media to send with it.
4593 bool offer_new_audio_description = send_audio;
4594 bool offer_new_video_description = send_video;
4595 bool offer_new_data_description = HasDataChannels();
4596
4597 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004598 if (offer_answer_options.offer_to_receive_audio !=
4599 RTCOfferAnswerOptions::kUndefined) {
4600 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004601 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004602 offer_new_audio_description ||
4603 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004604 }
Steve Antondcc3c022017-12-22 16:02:54 -08004605 if (offer_answer_options.offer_to_receive_video !=
4606 RTCOfferAnswerOptions::kUndefined) {
4607 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004608 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004609 offer_new_video_description ||
4610 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004611 }
4612
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004613 absl::optional<size_t> audio_index;
4614 absl::optional<size_t> video_index;
4615 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004616 // If a current description exists, generate m= sections in the same order,
4617 // using the first audio/video/data section that appears and rejecting
4618 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004619 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004620 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004621 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004622 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4623 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4624 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004625 }
4626
zhihuang1c378ed2017-08-17 14:10:50 -07004627 // Add audio/video/data m= sections to the end if needed.
4628 if (!audio_index && offer_new_audio_description) {
4629 session_options->media_description_options.push_back(
4630 cricket::MediaDescriptionOptions(
4631 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004632 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4633 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004634 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004635 }
zhihuang1c378ed2017-08-17 14:10:50 -07004636 if (!video_index && offer_new_video_description) {
4637 session_options->media_description_options.push_back(
4638 cricket::MediaDescriptionOptions(
4639 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004640 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4641 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004642 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004643 }
zhihuang1c378ed2017-08-17 14:10:50 -07004644 if (!data_index && offer_new_data_description) {
4645 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004646 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004647 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004648 }
4649
4650 cricket::MediaDescriptionOptions* audio_media_description_options =
4651 !audio_index ? nullptr
4652 : &session_options->media_description_options[*audio_index];
4653 cricket::MediaDescriptionOptions* video_media_description_options =
4654 !video_index ? nullptr
4655 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004656
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004657 AddPlanBRtpSenderOptions(GetSendersInternal(),
4658 audio_media_description_options,
4659 video_media_description_options,
4660 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004661}
4662
Steve Antondcc3c022017-12-22 16:02:54 -08004663static cricket::MediaDescriptionOptions
4664GetMediaDescriptionOptionsForTransceiver(
4665 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4666 transceiver,
4667 const std::string& mid) {
4668 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004669 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004670 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004671 media_description_options.codec_preferences =
4672 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004673 // This behavior is specified in JSEP. The gist is that:
4674 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4675 // sendrecv.
4676 // 2. If the MSID is included, then it must be included in any subsequent
4677 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004678 if (transceiver->stopped() ||
4679 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4680 !transceiver->internal()->has_ever_been_used_to_send())) {
4681 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004682 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004683
4684 cricket::SenderOptions sender_options;
4685 sender_options.track_id = transceiver->sender()->id();
4686 sender_options.stream_ids = transceiver->sender()->stream_ids();
4687
4688 // The following sets up RIDs and Simulcast.
4689 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004690 RtpParameters send_parameters =
4691 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004692 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4693 send_parameters.encodings.end(),
4694 [](const RtpEncodingParameters& encoding) {
4695 return !encoding.rid.empty();
4696 });
4697
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004698 std::vector<RidDescription> send_rids;
4699 SimulcastLayerList send_layers;
4700 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4701 if (encoding.rid.empty()) {
4702 continue;
4703 }
4704 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4705 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4706 }
4707
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004708 if (has_rids) {
4709 sender_options.rids = send_rids;
4710 }
4711
4712 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004713 // When RIDs are configured, we must set num_sim_layers to 0 to.
4714 // Otherwise, num_sim_layers must be 1 because either there is no
4715 // simulcast, or simulcast is acheived by munging the SDP.
4716 sender_options.num_sim_layers = has_rids ? 0 : 1;
4717 media_description_options.sender_options.push_back(sender_options);
4718
Steve Antondcc3c022017-12-22 16:02:54 -08004719 return media_description_options;
4720}
4721
Steve Anton5c72e712018-12-10 14:25:30 -08004722// Returns the ContentInfo at mline index |i|, or null if none exists.
4723static const ContentInfo* GetContentByIndex(
4724 const SessionDescriptionInterface* sdesc,
4725 size_t i) {
4726 if (!sdesc) {
4727 return nullptr;
4728 }
4729 const ContentInfos& contents = sdesc->description()->contents();
4730 return (i < contents.size() ? &contents[i] : nullptr);
4731}
4732
Steve Antondcc3c022017-12-22 16:02:54 -08004733void PeerConnection::GetOptionsForUnifiedPlanOffer(
4734 const RTCOfferAnswerOptions& offer_answer_options,
4735 cricket::MediaSessionOptions* session_options) {
4736 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4737 // Offers) and 5.2.2 (Subsequent Offers).
4738 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004739 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004740 const ContentInfos& local_contents =
4741 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004742 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004743 const ContentInfos& remote_contents =
4744 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004745 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004746 // The mline indices that can be recycled. New transceivers should reuse these
4747 // slots first.
4748 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004749 // First, go through each media section that exists in either the local or
4750 // remote description and generate a media section in this offer for the
4751 // associated transceiver. If a media section can be recycled, generate a
4752 // default, rejected media section here that can be later overwritten.
4753 for (size_t i = 0;
4754 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4755 // Either |local_content| or |remote_content| is non-null.
4756 const ContentInfo* local_content =
4757 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004758 const ContentInfo* current_local_content =
4759 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004760 const ContentInfo* remote_content =
4761 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004762 const ContentInfo* current_remote_content =
4763 GetContentByIndex(current_remote_description(), i);
4764 bool had_been_rejected =
4765 (current_local_content && current_local_content->rejected) ||
4766 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004767 const std::string& mid =
4768 (local_content ? local_content->name : remote_content->name);
4769 cricket::MediaType media_type =
4770 (local_content ? local_content->media_description()->type()
4771 : remote_content->media_description()->type());
4772 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4773 media_type == cricket::MEDIA_TYPE_VIDEO) {
4774 auto transceiver = GetAssociatedTransceiver(mid);
4775 RTC_CHECK(transceiver);
4776 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004777 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004778 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004779 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004780 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4781 RtpTransceiverDirection::kInactive,
4782 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004783 recycleable_mline_indices.push(i);
4784 } else {
4785 session_options->media_description_options.push_back(
4786 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4787 // CreateOffer shouldn't really cause any state changes in
4788 // PeerConnection, but we need a way to match new transceivers to new
4789 // media sections in SetLocalDescription and JSEP specifies this is done
4790 // by recording the index of the media section generated for the
4791 // transceiver in the offer.
4792 transceiver->internal()->set_mline_index(i);
4793 }
4794 } else {
4795 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004796 RTC_CHECK(GetDataMid());
4797 if (had_been_rejected || mid != *GetDataMid()) {
4798 session_options->media_description_options.push_back(
4799 GetMediaDescriptionOptionsForRejectedData(mid));
4800 } else {
4801 session_options->media_description_options.push_back(
4802 GetMediaDescriptionOptionsForActiveData(mid));
4803 }
Steve Antondcc3c022017-12-22 16:02:54 -08004804 }
4805 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004806
Steve Antondcc3c022017-12-22 16:02:54 -08004807 // Next, look for transceivers that are newly added (that is, are not stopped
4808 // and not associated). Reuse media sections marked as recyclable first,
4809 // otherwise append to the end of the offer. New media sections should be
4810 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004811 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004812 if (transceiver->mid() || transceiver->stopped()) {
4813 continue;
4814 }
4815 size_t mline_index;
4816 if (!recycleable_mline_indices.empty()) {
4817 mline_index = recycleable_mline_indices.front();
4818 recycleable_mline_indices.pop();
4819 session_options->media_description_options[mline_index] =
4820 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004821 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004822 } else {
4823 mline_index = session_options->media_description_options.size();
4824 session_options->media_description_options.push_back(
4825 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004826 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004827 }
4828 // See comment above for why CreateOffer changes the transceiver's state.
4829 transceiver->internal()->set_mline_index(mline_index);
4830 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004831 // Lastly, add a m-section if we have local data channels and an m section
4832 // does not already exist.
4833 if (!GetDataMid() && HasDataChannels()) {
4834 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004835 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004836 }
Steve Antondcc3c022017-12-22 16:02:54 -08004837}
4838
4839void PeerConnection::GetOptionsForAnswer(
4840 const RTCOfferAnswerOptions& offer_answer_options,
4841 cricket::MediaSessionOptions* session_options) {
4842 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4843
4844 if (IsUnifiedPlan()) {
4845 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4846 } else {
4847 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4848 }
4849
Steve Antonfa2260d2017-12-28 16:38:23 -08004850 // Intentionally unset the data channel type for RTP data channel. Otherwise
4851 // the RTP data channels would be successfully negotiated by default and the
4852 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4853 // We want to leave RTP data channels broken, so people won't try to use them.
4854 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4855 session_options->data_channel_type = data_channel_type();
4856 }
4857
Steve Antondcc3c022017-12-22 16:02:54 -08004858 // Apply ICE renomination flag.
4859 for (auto& options : session_options->media_description_options) {
4860 options.transport_options.enable_ice_renomination =
4861 configuration_.enable_ice_renomination;
4862 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004863
4864 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004865 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004866 session_options->pooled_ice_credentials =
4867 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4868 RTC_FROM_HERE,
4869 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4870 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004871
4872 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004873 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004874 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004875 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004876 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004877 if (!params) {
4878 continue;
4879 }
4880 options.transport_options.opaque_parameters = params;
4881 if ((use_datagram_transport_ &&
4882 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4883 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4884 (use_datagram_transport_for_data_channels_ &&
4885 options.type == cricket::MEDIA_TYPE_DATA)) {
4886 options.alt_protocol = params->protocol;
4887 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004888 }
4889 }
deadbeefab9b2d12015-10-14 11:33:11 -07004890}
4891
Steve Antondcc3c022017-12-22 16:02:54 -08004892void PeerConnection::GetOptionsForPlanBAnswer(
4893 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004894 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004895 // Figure out transceiver directional preferences.
4896 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4897 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4898
4899 // By default, generate sendrecv/recvonly m= sections. The direction is also
4900 // restricted by the direction in the offer.
4901 bool recv_audio = true;
4902 bool recv_video = true;
4903
4904 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004905 if (offer_answer_options.offer_to_receive_audio !=
4906 RTCOfferAnswerOptions::kUndefined) {
4907 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004908 }
Steve Antondcc3c022017-12-22 16:02:54 -08004909 if (offer_answer_options.offer_to_receive_video !=
4910 RTCOfferAnswerOptions::kUndefined) {
4911 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004912 }
4913
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004914 absl::optional<size_t> audio_index;
4915 absl::optional<size_t> video_index;
4916 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004917
4918 // Generate m= sections that match those in the offer.
4919 // Note that mediasession.cc will handle intersection our preferred
4920 // direction with the offered direction.
4921 GenerateMediaDescriptionOptions(
4922 remote_description(),
4923 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4924 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4925 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004926
4927 cricket::MediaDescriptionOptions* audio_media_description_options =
4928 !audio_index ? nullptr
4929 : &session_options->media_description_options[*audio_index];
4930 cricket::MediaDescriptionOptions* video_media_description_options =
4931 !video_index ? nullptr
4932 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004933
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004934 AddPlanBRtpSenderOptions(GetSendersInternal(),
4935 audio_media_description_options,
4936 video_media_description_options,
4937 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004938}
zhihuangaf388472016-11-02 16:49:48 -07004939
Steve Antondcc3c022017-12-22 16:02:54 -08004940void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4941 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4942 cricket::MediaSessionOptions* session_options) {
4943 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4944 // Answers) and 5.3.2 (Subsequent Answers).
4945 RTC_DCHECK(remote_description());
4946 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4947 for (const ContentInfo& content :
4948 remote_description()->description()->contents()) {
4949 cricket::MediaType media_type = content.media_description()->type();
4950 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4951 media_type == cricket::MEDIA_TYPE_VIDEO) {
4952 auto transceiver = GetAssociatedTransceiver(content.name);
4953 RTC_CHECK(transceiver);
4954 session_options->media_description_options.push_back(
4955 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4956 } else {
4957 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004958 // Reject all data sections if data channels are disabled.
4959 // Reject a data section if it has already been rejected.
4960 // Reject all data sections except for the first one.
4961 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4962 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004963 session_options->media_description_options.push_back(
4964 GetMediaDescriptionOptionsForRejectedData(content.name));
4965 } else {
4966 session_options->media_description_options.push_back(
4967 GetMediaDescriptionOptionsForActiveData(content.name));
4968 }
Steve Antondcc3c022017-12-22 16:02:54 -08004969 }
4970 }
htaa2a49d92016-03-04 02:51:39 -08004971}
4972
zhihuang1c378ed2017-08-17 14:10:50 -07004973void PeerConnection::GenerateMediaDescriptionOptions(
4974 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004975 RtpTransceiverDirection audio_direction,
4976 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004977 absl::optional<size_t>* audio_index,
4978 absl::optional<size_t>* video_index,
4979 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004980 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004981 for (const cricket::ContentInfo& content :
4982 session_desc->description()->contents()) {
4983 if (IsAudioContent(&content)) {
4984 // If we already have an audio m= section, reject this extra one.
4985 if (*audio_index) {
4986 session_options->media_description_options.push_back(
4987 cricket::MediaDescriptionOptions(
4988 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004989 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004990 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004991 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004992 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004993 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4994 content.name, audio_direction,
4995 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004996 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004997 }
4998 } else if (IsVideoContent(&content)) {
4999 // If we already have an video m= section, reject this extra one.
5000 if (*video_index) {
5001 session_options->media_description_options.push_back(
5002 cricket::MediaDescriptionOptions(
5003 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005004 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005005 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005006 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005007 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005008 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5009 content.name, video_direction,
5010 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005011 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005012 }
5013 } else {
5014 RTC_DCHECK(IsDataContent(&content));
5015 // If we already have an data m= section, reject this extra one.
5016 if (*data_index) {
5017 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005018 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005019 } else {
5020 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005021 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005022 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005023 }
5024 }
htaa2a49d92016-03-04 02:51:39 -08005025 }
deadbeefab9b2d12015-10-14 11:33:11 -07005026}
5027
Steve Antonfa2260d2017-12-28 16:38:23 -08005028cricket::MediaDescriptionOptions
5029PeerConnection::GetMediaDescriptionOptionsForActiveData(
5030 const std::string& mid) const {
5031 // Direction for data sections is meaningless, but legacy endpoints might
5032 // expect sendrecv.
5033 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5034 RtpTransceiverDirection::kSendRecv,
5035 /*stopped=*/false);
5036 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5037 return options;
5038}
5039
5040cricket::MediaDescriptionOptions
5041PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5042 const std::string& mid) const {
5043 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5044 RtpTransceiverDirection::kInactive,
5045 /*stopped=*/true);
5046 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5047 return options;
5048}
5049
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005050absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005051 switch (data_channel_type_) {
5052 case cricket::DCT_RTP:
5053 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005054 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005055 }
5056 return rtp_data_channel_->content_name();
5057 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005058 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005059 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5060 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5061 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005062 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005063 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005064 }
5065}
5066
Steve Anton4171afb2017-11-20 10:20:22 -08005067void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5068 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5069 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005070 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005071}
5072
Steve Anton4171afb2017-11-20 10:20:22 -08005073void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005074 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005075 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005076 cricket::MediaType media_type,
5077 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005078 RTC_DCHECK(!IsUnifiedPlan());
5079
Steve Anton4171afb2017-11-20 10:20:22 -08005080 std::vector<RtpSenderInfo>* current_senders =
5081 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005082
Steve Anton4171afb2017-11-20 10:20:22 -08005083 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005084 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005085 for (auto sender_it = current_senders->begin();
5086 sender_it != current_senders->end();
5087 /* incremented manually */) {
5088 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005089 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005090 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005091 std::string params_stream_id;
5092 if (params) {
5093 params_stream_id =
5094 (!params->first_stream_id().empty() ? params->first_stream_id()
5095 : kDefaultStreamId);
5096 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005097 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005098 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005099 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005100 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005101 sender_exists) {
5102 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005103 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005104 OnRemoteSenderRemoved(info, media_type);
5105 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005106 }
5107 }
5108
Steve Anton4171afb2017-11-20 10:20:22 -08005109 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005110 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005111 if (!params.has_ssrcs()) {
5112 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5113 // sender, this means it is coming from a Unified Plan endpoint,so we just
5114 // create a default.
5115 default_sender_needed = true;
5116 break;
5117 }
5118
Seth Hampson845e8782018-03-02 11:34:10 -08005119 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005120 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005121 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5122 // not supported in Plan B, we just take the first here and create the
5123 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005124 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005125 (!params.first_stream_id().empty() ? params.first_stream_id()
5126 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005127 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005128 uint32_t ssrc = params.first_ssrc();
5129
5130 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005131 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005132 if (!stream) {
5133 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005134 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005135 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005136 remote_streams_->AddStream(stream);
5137 new_streams->AddStream(stream);
5138 }
5139
Steve Anton4171afb2017-11-20 10:20:22 -08005140 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005141 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005142 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005143 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005144 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005145 }
5146 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005147
Steve Anton4171afb2017-11-20 10:20:22 -08005148 // Add default sender if necessary.
5149 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005150 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005151 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005152 if (!default_stream) {
5153 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005154 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005155 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005156 remote_streams_->AddStream(default_stream);
5157 new_streams->AddStream(default_stream);
5158 }
Steve Anton4171afb2017-11-20 10:20:22 -08005159 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5160 ? kDefaultAudioSenderId
5161 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005162 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005163 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005164 if (!default_sender_info) {
5165 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005166 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005167 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005168 }
5169 }
deadbeefab9b2d12015-10-14 11:33:11 -07005170}
5171
Steve Anton4171afb2017-11-20 10:20:22 -08005172void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5173 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005174 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5175 << " receiver for track_id=" << sender_info.sender_id
5176 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005177
Steve Anton3d954a62018-04-02 11:27:23 -07005178 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005179 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005180 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005181 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005182 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005183 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005184 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005185 }
5186}
5187
Steve Anton4171afb2017-11-20 10:20:22 -08005188void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5189 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005190 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5191 << " receiver for track_id=" << sender_info.sender_id
5192 << " and stream_id=" << sender_info.stream_id;
5193
Seth Hampson845e8782018-03-02 11:34:10 -08005194 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005195
Henrik Boström933d8b02017-10-10 10:05:16 -07005196 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005197 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005198 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5199 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005200 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005201 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005202 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005203 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005204 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005205 }
5206 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005207 // Stopping or destroying a VideoRtpReceiver will end the
5208 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005209 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005210 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005211 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005212 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005213 // There's no guarantee the track is still available, e.g. the track may
5214 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005215 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005216 }
5217 } else {
nisseede5da42017-01-12 05:15:36 -08005218 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005219 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005220 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005221 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005222 }
deadbeefab9b2d12015-10-14 11:33:11 -07005223}
5224
5225void PeerConnection::UpdateEndedRemoteMediaStreams() {
5226 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5227 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5228 MediaStreamInterface* stream = remote_streams_->at(i);
5229 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5230 streams_to_remove.push_back(stream);
5231 }
5232 }
5233
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005234 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005235 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005236 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005237 }
5238}
5239
Steve Anton4171afb2017-11-20 10:20:22 -08005240void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005241 const std::vector<cricket::StreamParams>& streams,
5242 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005243 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005244
Seth Hampson845e8782018-03-02 11:34:10 -08005245 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005246 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005247 for (auto sender_it = current_senders->begin();
5248 sender_it != current_senders->end();
5249 /* incremented manually */) {
5250 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005251 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005252 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5253 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005254 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005255 OnLocalSenderRemoved(info, media_type);
5256 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005257 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005258 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005259 }
5260 }
5261
Steve Anton4171afb2017-11-20 10:20:22 -08005262 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005263 for (const cricket::StreamParams& params : streams) {
5264 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005265 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005266 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005267 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005268 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005269 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005270 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005271 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005272 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005273 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005274 }
5275 }
5276}
5277
Steve Anton4171afb2017-11-20 10:20:22 -08005278void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5279 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005280 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005281 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005282 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005283 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5284 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005285 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005286 return;
5287 }
5288
deadbeeffac06552015-11-25 11:26:01 -08005289 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005290 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005291 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005292 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005293 }
deadbeeffac06552015-11-25 11:26:01 -08005294
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005295 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005296 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005297}
5298
Steve Anton4171afb2017-11-20 10:20:22 -08005299void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5300 cricket::MediaType media_type) {
5301 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005302 if (!sender) {
5303 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005304 // SessionDescriptions has been renegotiated.
5305 return;
5306 }
deadbeeffac06552015-11-25 11:26:01 -08005307
5308 // A sender has been removed from the SessionDescription but it's still
5309 // associated with the PeerConnection. This only occurs if the SDP doesn't
5310 // match with the calls to CreateSender, AddStream and RemoveStream.
5311 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005312 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005313 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005314 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005315 }
deadbeeffac06552015-11-25 11:26:01 -08005316
Steve Anton4171afb2017-11-20 10:20:22 -08005317 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005318}
5319
5320void PeerConnection::UpdateLocalRtpDataChannels(
5321 const cricket::StreamParamsVec& streams) {
5322 std::vector<std::string> existing_channels;
5323
5324 // Find new and active data channels.
5325 for (const cricket::StreamParams& params : streams) {
5326 // |it->sync_label| is actually the data channel label. The reason is that
5327 // we use the same naming of data channels as we do for
5328 // MediaStreams and Tracks.
5329 // For MediaStreams, the sync_label is the MediaStream label and the
5330 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005331 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005332 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005333 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005334 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005335 continue;
5336 }
5337 // Set the SSRC the data channel should use for sending.
5338 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5339 existing_channels.push_back(data_channel_it->first);
5340 }
5341
5342 UpdateClosingRtpDataChannels(existing_channels, true);
5343}
5344
5345void PeerConnection::UpdateRemoteRtpDataChannels(
5346 const cricket::StreamParamsVec& streams) {
5347 std::vector<std::string> existing_channels;
5348
5349 // Find new and active data channels.
5350 for (const cricket::StreamParams& params : streams) {
5351 // The data channel label is either the mslabel or the SSRC if the mslabel
5352 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005353 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005354 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005355 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005356 auto data_channel_it = rtp_data_channels_.find(label);
5357 if (data_channel_it == rtp_data_channels_.end()) {
5358 // This is a new data channel.
5359 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5360 } else {
5361 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5362 }
5363 existing_channels.push_back(label);
5364 }
5365
5366 UpdateClosingRtpDataChannels(existing_channels, false);
5367}
5368
5369void PeerConnection::UpdateClosingRtpDataChannels(
5370 const std::vector<std::string>& active_channels,
5371 bool is_local_update) {
5372 auto it = rtp_data_channels_.begin();
5373 while (it != rtp_data_channels_.end()) {
5374 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005375 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005376 ++it;
5377 continue;
5378 }
5379
5380 if (is_local_update) {
5381 data_channel->SetSendSsrc(0);
5382 } else {
5383 data_channel->RemotePeerRequestClose();
5384 }
5385
5386 if (data_channel->state() == DataChannel::kClosed) {
5387 rtp_data_channels_.erase(it);
5388 it = rtp_data_channels_.begin();
5389 } else {
5390 ++it;
5391 }
5392 }
5393}
5394
5395void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5396 uint32_t remote_ssrc) {
5397 rtc::scoped_refptr<DataChannel> channel(
5398 InternalCreateDataChannel(label, nullptr));
5399 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005400 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005401 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005402 return;
5403 }
5404 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005405 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5406 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005407 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005408}
5409
5410rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5411 const std::string& label,
5412 const InternalDataChannelInit* config) {
5413 if (IsClosed()) {
5414 return nullptr;
5415 }
Steve Anton75737c02017-11-06 10:37:17 -08005416 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005417 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005418 << "InternalCreateDataChannel: Data is not supported in this call.";
5419 return nullptr;
5420 }
5421 InternalDataChannelInit new_config =
5422 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005423 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005424 if (new_config.id < 0) {
5425 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005426 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005427 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005428 RTC_LOG(LS_ERROR)
5429 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005430 return nullptr;
5431 }
5432 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005433 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005434 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005435 return nullptr;
5436 }
5437 }
5438
Steve Anton75737c02017-11-06 10:37:17 -08005439 rtc::scoped_refptr<DataChannel> channel(
5440 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005441 if (!channel) {
5442 sid_allocator_.ReleaseSid(new_config.id);
5443 return nullptr;
5444 }
5445
5446 if (channel->data_channel_type() == cricket::DCT_RTP) {
5447 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005448 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5449 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005450 return nullptr;
5451 }
5452 rtp_data_channels_[channel->label()] = channel;
5453 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005454 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005455 sctp_data_channels_.push_back(channel);
5456 channel->SignalClosed.connect(this,
5457 &PeerConnection::OnSctpDataChannelClosed);
5458 }
5459
Steve Anton2d8609c2018-01-23 16:38:46 -08005460 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005461 return channel;
5462}
5463
5464bool PeerConnection::HasDataChannels() const {
5465 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5466}
5467
5468void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005469 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005470 for (const auto& channel : sctp_data_channels_) {
5471 if (channel->id() < 0) {
5472 int sid;
5473 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005474 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5475 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005476 continue;
5477 }
5478 channel->SetSctpSid(sid);
5479 }
5480 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005481 // Since closing modifies the list of channels, we have to do the actual
5482 // closing outside the loop.
5483 for (const auto& channel : channels_to_close) {
5484 channel->CloseAbruptly();
5485 }
deadbeefab9b2d12015-10-14 11:33:11 -07005486}
5487
5488void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005489 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005490 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5491 ++it) {
5492 if (it->get() == channel) {
5493 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005494 // After the closing procedure is done, it's safe to use this ID for
5495 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005496 sid_allocator_.ReleaseSid(channel->id());
5497 }
deadbeefbd292462015-12-14 18:15:29 -08005498 // Since this method is triggered by a signal from the DataChannel,
5499 // we can't free it directly here; we need to free it asynchronously.
5500 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005501 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005502 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5503 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005504 return;
5505 }
5506 }
5507}
5508
deadbeefab9b2d12015-10-14 11:33:11 -07005509void PeerConnection::OnDataChannelDestroyed() {
5510 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5511 // DataChannel may callback to us and try to modify the list.
5512 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5513 temp_rtp_dcs.swap(rtp_data_channels_);
5514 for (const auto& kv : temp_rtp_dcs) {
5515 kv.second->OnTransportChannelDestroyed();
5516 }
5517
5518 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5519 temp_sctp_dcs.swap(sctp_data_channels_);
5520 for (const auto& channel : temp_sctp_dcs) {
5521 channel->OnTransportChannelDestroyed();
5522 }
5523}
5524
5525void PeerConnection::OnDataChannelOpenMessage(
5526 const std::string& label,
5527 const InternalDataChannelInit& config) {
5528 rtc::scoped_refptr<DataChannel> channel(
5529 InternalCreateDataChannel(label, &config));
5530 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005531 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005532 return;
5533 }
5534
deadbeefa601f5c2016-06-06 14:27:39 -07005535 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5536 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005537 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005538 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005539}
5540
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005541bool PeerConnection::HandleOpenMessage_s(
5542 const cricket::ReceiveDataParams& params,
5543 const rtc::CopyOnWriteBuffer& buffer) {
5544 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5545 // Received OPEN message; parse and signal that a new data channel should
5546 // be created.
5547 std::string label;
5548 InternalDataChannelInit config;
5549 config.id = params.ssrc;
5550 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5551 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5552 << params.ssrc;
5553 return true;
5554 }
5555 config.open_handshake_role = InternalDataChannelInit::kAcker;
5556 OnDataChannelOpenMessage(label, config);
5557 return true;
5558 }
5559 return false;
5560}
5561
Steve Anton4171afb2017-11-20 10:20:22 -08005562rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5563PeerConnection::GetAudioTransceiver() const {
5564 // This method only works with Plan B SDP, where there is a single
5565 // audio/video transceiver.
5566 RTC_DCHECK(!IsUnifiedPlan());
5567 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005568 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005569 return transceiver;
5570 }
5571 }
5572 RTC_NOTREACHED();
5573 return nullptr;
5574}
5575
5576rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5577PeerConnection::GetVideoTransceiver() const {
5578 // This method only works with Plan B SDP, where there is a single
5579 // audio/video transceiver.
5580 RTC_DCHECK(!IsUnifiedPlan());
5581 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005582 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005583 return transceiver;
5584 }
5585 }
5586 RTC_NOTREACHED();
5587 return nullptr;
5588}
5589
5590// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5591// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005592bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005593 switch (type) {
5594 case cricket::MEDIA_TYPE_AUDIO:
5595 return !GetAudioTransceiver()->internal()->senders().empty();
5596 case cricket::MEDIA_TYPE_VIDEO:
5597 return !GetVideoTransceiver()->internal()->senders().empty();
5598 case cricket::MEDIA_TYPE_DATA:
5599 return false;
5600 }
5601 RTC_NOTREACHED();
5602 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005603}
5604
Steve Anton4171afb2017-11-20 10:20:22 -08005605rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5606PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005607 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005608 for (auto sender : transceiver->internal()->senders()) {
5609 if (sender->track() == track) {
5610 return sender;
5611 }
5612 }
5613 }
5614 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005615}
5616
Steve Anton4171afb2017-11-20 10:20:22 -08005617rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5618PeerConnection::FindSenderById(const std::string& sender_id) 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->id() == sender_id) {
5622 return sender;
5623 }
5624 }
5625 }
5626 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005627}
5628
Steve Anton4171afb2017-11-20 10:20:22 -08005629rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5630PeerConnection::FindReceiverById(const std::string& receiver_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 receiver : transceiver->internal()->receivers()) {
5633 if (receiver->id() == receiver_id) {
5634 return receiver;
5635 }
5636 }
5637 }
5638 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005639}
5640
Steve Anton4171afb2017-11-20 10:20:22 -08005641std::vector<PeerConnection::RtpSenderInfo>*
5642PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5643 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5644 media_type == cricket::MEDIA_TYPE_VIDEO);
5645 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5646 ? &remote_audio_sender_infos_
5647 : &remote_video_sender_infos_;
5648}
5649
5650std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005651 cricket::MediaType media_type) {
5652 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5653 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005654 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5655 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005656}
5657
Steve Anton4171afb2017-11-20 10:20:22 -08005658const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5659 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005660 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005661 const std::string sender_id) const {
5662 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005663 if (sender_info.stream_id == stream_id &&
5664 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005665 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005666 }
5667 }
5668 return nullptr;
5669}
5670
5671DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5672 for (const auto& channel : sctp_data_channels_) {
5673 if (channel->id() == sid) {
5674 return channel;
5675 }
5676 }
5677 return nullptr;
5678}
5679
Karl Wibergfb3be392019-03-22 14:13:22 +01005680PeerConnection::InitializePortAllocatorResult
5681PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005682 const cricket::ServerAddresses& stun_servers,
5683 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005684 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005685 RTC_DCHECK_RUN_ON(network_thread());
5686
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005687 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005688 // To handle both internal and externally created port allocator, we will
5689 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005690 int port_allocator_flags = port_allocator_->flags();
5691 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5692 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5693 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005694 // If the disable-IPv6 flag was specified, we'll not override it
5695 // by experiment.
5696 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005697 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005698 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5699 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005700 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005701 }
5702
zhihuangb09b3f92017-03-07 14:40:51 -08005703 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005704 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005705 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005706 }
5707
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005708 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005709 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005710 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005711 }
5712
honghaiz60347052016-05-31 18:29:12 -07005713 if (configuration.candidate_network_policy ==
5714 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005715 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005716 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005717 }
5718
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005719 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005720 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005721 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5722 }
5723
Karl Wibergfb3be392019-03-22 14:13:22 +01005724 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005725 // No step delay is used while allocating ports.
5726 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005727 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005728 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005729 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005730
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005731 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005732 for (auto& turn_server : turn_servers_copy) {
5733 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005734 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005735 // Call this last since it may create pooled allocator sessions using the
5736 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005737 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005738 stun_servers, std::move(turn_servers_copy),
5739 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5740 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005741 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005742
5743 InitializePortAllocatorResult res;
5744 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5745 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005746}
5747
deadbeef91dd5672016-05-18 16:55:30 -07005748bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005749 const cricket::ServerAddresses& stun_servers,
5750 const std::vector<cricket::RelayServerConfig>& turn_servers,
5751 IceTransportsType type,
5752 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005753 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005754 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005755 absl::optional<int> stun_candidate_keepalive_interval,
5756 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005757 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005758 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005759 // According to JSEP, after setLocalDescription, changing the candidate pool
5760 // size is not allowed, and changing the set of ICE servers will not result
5761 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005762 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005763 port_allocator_->FreezeCandidatePool();
5764 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005765 // Add the custom tls turn servers if they exist.
5766 auto turn_servers_copy = turn_servers;
5767 for (auto& turn_server : turn_servers_copy) {
5768 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5769 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005770 // Call this last since it may create pooled allocator sessions using the
5771 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005772 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005773 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5774 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005775}
5776
Steve Antonba818672017-11-06 10:21:57 -08005777cricket::ChannelManager* PeerConnection::channel_manager() const {
5778 return factory_->channel_manager();
5779}
5780
Elad Alon99c3fe52017-10-13 16:29:40 +02005781bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005782 std::unique_ptr<RtcEventLogOutput> output,
5783 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005784 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005785 if (!event_log_) {
5786 return false;
5787 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005788 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005789}
5790
5791void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005792 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005793 if (event_log_) {
5794 event_log_->StopLogging();
5795 }
ivoc14d5dbe2016-07-04 07:06:55 -07005796}
nisseeaabdf62017-05-05 02:23:02 -07005797
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005798cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005799 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005800 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005801 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005802 if (channel && channel->content_name() == content_name) {
5803 return channel;
5804 }
Steve Anton75737c02017-11-06 10:37:17 -08005805 }
5806 if (rtp_data_channel() &&
5807 rtp_data_channel()->content_name() == content_name) {
5808 return rtp_data_channel();
5809 }
5810 return nullptr;
5811}
5812
5813bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005814 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005815 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005816 RTC_LOG(LS_INFO)
5817 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005818 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005819 return false;
5820 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005821 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005822 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005823 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005824 return false;
5825 }
5826
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005827 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005828 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005829 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005830 if (!dtls_role && is_caller_.has_value()) {
5831 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5832 }
Zhi Huange830e682018-03-30 10:48:35 -07005833 *role = *dtls_role;
5834 return true;
5835 }
5836 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005837}
5838
5839bool PeerConnection::GetSslRole(const std::string& content_name,
5840 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005841 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005842 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005843 RTC_LOG(LS_INFO)
5844 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005845 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005846 return false;
5847 }
5848
Zhi Huange830e682018-03-30 10:48:35 -07005849 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5850 if (dtls_role) {
5851 *role = *dtls_role;
5852 return true;
5853 }
5854 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005855}
5856
Steve Antonf8470812017-12-04 10:46:21 -08005857void PeerConnection::SetSessionError(SessionError error,
5858 const std::string& error_desc) {
5859 RTC_DCHECK_RUN_ON(signaling_thread());
5860 if (error != session_error_) {
5861 session_error_ = error;
5862 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005863 }
5864}
5865
Zhi Huange830e682018-03-30 10:48:35 -07005866RTCError PeerConnection::UpdateSessionState(
5867 SdpType type,
5868 cricket::ContentSource source,
5869 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005870 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005871
5872 // If there's already a pending error then no state transition should happen.
5873 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005874 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005875
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005876 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005877 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005878 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005879 }
5880
5881 // Update the signaling state according to the specified state machine (see
5882 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005883 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005884 ChangeSignalingState(source == cricket::CS_LOCAL
5885 ? PeerConnectionInterface::kHaveLocalOffer
5886 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005887 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005888 ChangeSignalingState(source == cricket::CS_LOCAL
5889 ? PeerConnectionInterface::kHaveLocalPrAnswer
5890 : PeerConnectionInterface::kHaveRemotePrAnswer);
5891 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005892 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005893 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03005894 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005895 }
5896
5897 // Update internal objects according to the session description's media
5898 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005899 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005900 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005901 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005902 }
5903
Steve Anton8a006912017-12-04 15:25:56 -08005904 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005905}
5906
Steve Anton8a006912017-12-04 15:25:56 -08005907RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005908 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005909 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005910 const SessionDescriptionInterface* sdesc =
5911 (source == cricket::CS_LOCAL ? local_description()
5912 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005913 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005914
5915 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005916 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005917 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005918 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005919 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005920 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005921 continue;
5922 }
5923 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005924 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005925 if (!content_desc) {
5926 continue;
5927 }
5928 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005929 bool success = (source == cricket::CS_LOCAL)
5930 ? channel->SetLocalContent(content_desc, type, &error)
5931 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005932 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005933 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005934 }
5935 }
5936
5937 // If using the RtpDataChannel, push down the new SDP section for it too.
5938 if (rtp_data_channel_) {
5939 const ContentInfo* data_content =
5940 cricket::GetFirstDataContent(sdesc->description());
5941 if (data_content && !data_content->rejected) {
5942 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005943 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005944 if (data_desc) {
5945 std::string error;
5946 bool success =
5947 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005948 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005949 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005950 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005951 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005952 }
Steve Anton75737c02017-11-06 10:37:17 -08005953 }
5954 }
5955 }
Steve Antoned10bd92017-12-05 10:52:59 -08005956
Steve Anton75737c02017-11-06 10:37:17 -08005957 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5958 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005959 if (sctp_mid_ && local_description() && remote_description()) {
5960 rtc::scoped_refptr<SctpTransport> sctp_transport =
5961 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005962 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5963 local_description()->description());
5964 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5965 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005966 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005967 int max_message_size;
5968 // A remote max message size of zero means "any size supported".
5969 // We configure the connection with our own max message size.
5970 if (remote_sctp_description->max_message_size() == 0) {
5971 max_message_size = local_sctp_description->max_message_size();
5972 } else {
5973 max_message_size =
5974 std::min(local_sctp_description->max_message_size(),
5975 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005976 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005977 sctp_transport->Start(local_sctp_description->port(),
5978 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005979 }
Steve Anton75737c02017-11-06 10:37:17 -08005980 }
Steve Antoned10bd92017-12-05 10:52:59 -08005981
Steve Anton8a006912017-12-04 15:25:56 -08005982 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005983}
5984
Steve Anton8a006912017-12-04 15:25:56 -08005985RTCError PeerConnection::PushdownTransportDescription(
5986 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005987 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005988 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005989
Zhi Huange830e682018-03-30 10:48:35 -07005990 if (source == cricket::CS_LOCAL) {
5991 const SessionDescriptionInterface* sdesc = local_description();
5992 RTC_DCHECK(sdesc);
5993 return transport_controller_->SetLocalDescription(type,
5994 sdesc->description());
5995 } else {
5996 const SessionDescriptionInterface* sdesc = remote_description();
5997 RTC_DCHECK(sdesc);
5998 return transport_controller_->SetRemoteDescription(type,
5999 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006000 }
Steve Anton75737c02017-11-06 10:37:17 -08006001}
6002
6003bool PeerConnection::GetTransportDescription(
6004 const SessionDescription* description,
6005 const std::string& content_name,
6006 cricket::TransportDescription* tdesc) {
6007 if (!description || !tdesc) {
6008 return false;
6009 }
6010 const TransportInfo* transport_info =
6011 description->GetTransportInfoByName(content_name);
6012 if (!transport_info) {
6013 return false;
6014 }
6015 *tdesc = transport_info->description;
6016 return true;
6017}
6018
Steve Anton75737c02017-11-06 10:37:17 -08006019cricket::IceConfig PeerConnection::ParseIceConfig(
6020 const PeerConnectionInterface::RTCConfiguration& config) const {
6021 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006022 switch (config.continual_gathering_policy) {
6023 case PeerConnectionInterface::GATHER_ONCE:
6024 gathering_policy = cricket::GATHER_ONCE;
6025 break;
6026 case PeerConnectionInterface::GATHER_CONTINUALLY:
6027 gathering_policy = cricket::GATHER_CONTINUALLY;
6028 break;
6029 default:
6030 RTC_NOTREACHED();
6031 gathering_policy = cricket::GATHER_ONCE;
6032 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006033
Steve Anton75737c02017-11-06 10:37:17 -08006034 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006035 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6036 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006037 ice_config.prioritize_most_likely_candidate_pairs =
6038 config.prioritize_most_likely_ice_candidate_pairs;
6039 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006040 RTCConfigurationToIceConfigOptionalInt(
6041 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006042 ice_config.continual_gathering_policy = gathering_policy;
6043 ice_config.presume_writable_when_fully_relayed =
6044 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006045 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6046 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006047 ice_config.ice_check_interval_strong_connectivity =
6048 config.ice_check_interval_strong_connectivity;
6049 ice_config.ice_check_interval_weak_connectivity =
6050 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006051 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006052 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6053 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006054 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006055 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006056 ice_config.regather_all_networks_interval_range =
6057 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006058 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006059 return ice_config;
6060}
6061
Steve Anton75737c02017-11-06 10:37:17 -08006062bool PeerConnection::SendData(const cricket::SendDataParams& params,
6063 const rtc::CopyOnWriteBuffer& payload,
6064 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006065 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006066 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006067 SendDataParams send_params;
6068 send_params.type = ToWebrtcDataMessageType(params.type);
6069 send_params.ordered = params.ordered;
6070 if (params.max_rtx_count >= 0) {
6071 send_params.max_rtx_count = params.max_rtx_count;
6072 } else if (params.max_rtx_ms >= 0) {
6073 send_params.max_rtx_ms = params.max_rtx_ms;
6074 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006075
6076 RTCError error = network_thread()->Invoke<RTCError>(
6077 RTC_FROM_HERE, [this, params, send_params, payload] {
6078 return data_channel_transport_->SendData(params.sid, send_params,
6079 payload);
6080 });
6081
6082 if (error.ok()) {
6083 *result = cricket::SendDataResult::SDR_SUCCESS;
6084 return true;
6085 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6086 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6087 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6088 *result = cricket::SendDataResult::SDR_BLOCK;
6089 return false;
6090 }
6091 *result = cricket::SendDataResult::SDR_ERROR;
6092 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006093 } else if (rtp_data_channel_) {
6094 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006095 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006096 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6097 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006098}
6099
6100bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006101 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006102 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006103 // Don't log an error here, because DataChannels are expected to call
6104 // ConnectDataChannel in this state. It's the only way to initially tell
6105 // whether or not the underlying transport is ready.
6106 return false;
6107 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006108 if (data_channel_transport_) {
6109 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6110 &DataChannel::OnChannelReady);
6111 SignalDataChannelTransportReceivedData_s.connect(
6112 webrtc_data_channel, &DataChannel::OnDataReceived);
6113 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006114 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006115 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006116 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006117 }
6118 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006119 rtp_data_channel_->SignalReadyToSendData.connect(
6120 webrtc_data_channel, &DataChannel::OnChannelReady);
6121 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6122 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006123 }
Steve Anton75737c02017-11-06 10:37:17 -08006124 return true;
6125}
6126
6127void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006128 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006129 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006130 RTC_LOG(LS_ERROR)
6131 << "DisconnectDataChannel called when rtp_data_channel_ and "
6132 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006133 return;
6134 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006135 if (data_channel_transport_) {
6136 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6137 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6138 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6139 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6140 }
6141 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006142 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6143 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006144 }
Steve Anton75737c02017-11-06 10:37:17 -08006145}
6146
6147void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006148 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006149 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6150 if (data_channel_transport_) {
6151 data_channel_transport_->OpenChannel(sid);
6152 }
6153 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006154 }
Steve Anton75737c02017-11-06 10:37:17 -08006155}
6156
6157void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006158 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006159 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6160 if (data_channel_transport_) {
6161 data_channel_transport_->CloseChannel(sid);
6162 }
6163 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006164 }
Steve Anton75737c02017-11-06 10:37:17 -08006165}
6166
6167bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006168 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006169 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006170 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006171}
6172
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006173void PeerConnection::OnDataReceived(int channel_id,
6174 DataMessageType type,
6175 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006176 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006177 cricket::ReceiveDataParams params;
6178 params.sid = channel_id;
6179 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006180 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006181 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6182 RTC_DCHECK_RUN_ON(signaling_thread());
6183 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006184 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006185 }
6186 });
6187}
6188
6189void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006190 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006191 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006192 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6193 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006194 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006195 });
6196}
6197
6198void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006199 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006200 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006201 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6202 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006203 SignalDataChannelTransportChannelClosed_s(channel_id);
6204 });
6205}
6206
6207void PeerConnection::OnReadyToSend() {
6208 RTC_DCHECK_RUN_ON(network_thread());
6209 data_channel_transport_invoker_->AsyncInvoke<void>(
6210 RTC_FROM_HERE, signaling_thread(), [this] {
6211 RTC_DCHECK_RUN_ON(signaling_thread());
6212 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006213 SignalDataChannelTransportWritable_s(
6214 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006215 });
6216}
6217
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006218absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006219 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006220 if (sctp_mid_ && transport_controller_) {
6221 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6222 if (dtls_transport) {
6223 return dtls_transport->transport_name();
6224 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006225 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006226 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006227 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006228}
6229
Qingsi Wang72a43a12018-02-20 16:03:18 -08006230cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6231 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006232 network_thread()->Invoke<void>(
6233 RTC_FROM_HERE,
6234 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6235 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006236 return candidate_states_list;
6237}
6238
Steve Anton5dfde182018-02-06 10:34:40 -08006239std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6240 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006241 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006242 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006243 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006244 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006245 if (channel) {
6246 transport_names_by_mid[channel->content_name()] =
6247 channel->transport_name();
6248 }
Steve Anton75737c02017-11-06 10:37:17 -08006249 }
Steve Anton5dfde182018-02-06 10:34:40 -08006250 if (rtp_data_channel_) {
6251 transport_names_by_mid[rtp_data_channel_->content_name()] =
6252 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006253 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006254 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006255 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006256 RTC_DCHECK(transport_name);
6257 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
Steve Anton5dfde182018-02-06 10:34:40 -08006259 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006260}
6261
Steve Anton5dfde182018-02-06 10:34:40 -08006262std::map<std::string, cricket::TransportStats>
6263PeerConnection::GetTransportStatsByNames(
6264 const std::set<std::string>& transport_names) {
6265 if (!network_thread()->IsCurrent()) {
6266 return network_thread()
6267 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6268 RTC_FROM_HERE,
6269 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006270 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006271 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006272 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6273 for (const std::string& transport_name : transport_names) {
6274 cricket::TransportStats transport_stats;
6275 bool success =
6276 transport_controller_->GetStats(transport_name, &transport_stats);
6277 if (success) {
6278 transport_stats_by_name[transport_name] = std::move(transport_stats);
6279 } else {
6280 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6281 << transport_name;
6282 }
6283 }
6284 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006285}
6286
6287bool PeerConnection::GetLocalCertificate(
6288 const std::string& transport_name,
6289 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006290 if (!certificate) {
6291 return false;
6292 }
6293 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6294 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006295}
6296
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006297std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006298 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006299 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006300}
6301
6302cricket::DataChannelType PeerConnection::data_channel_type() const {
6303 return data_channel_type_;
6304}
6305
6306bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006307 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006308 return pending_ice_restarts_.find(content_name) !=
6309 pending_ice_restarts_.end();
6310}
6311
Steve Anton75737c02017-11-06 10:37:17 -08006312bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6313 return transport_controller_->NeedsIceRestart(content_name);
6314}
6315
6316void PeerConnection::OnCertificateReady(
6317 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6318 transport_controller_->SetLocalCertificate(certificate);
6319}
6320
6321void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006322 SetSessionError(SessionError::kTransport,
6323 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006324}
6325
Alex Loiko9289eda2018-11-23 16:18:59 +00006326void PeerConnection::OnTransportControllerConnectionState(
6327 cricket::IceConnectionState state) {
6328 switch (state) {
6329 case cricket::kIceConnectionConnecting:
6330 // If the current state is Connected or Completed, then there were
6331 // writable channels but now there are not, so the next state must
6332 // be Disconnected.
6333 // kIceConnectionConnecting is currently used as the default,
6334 // un-connected state by the TransportController, so its only use is
6335 // detecting disconnections.
6336 if (ice_connection_state_ ==
6337 PeerConnectionInterface::kIceConnectionConnected ||
6338 ice_connection_state_ ==
6339 PeerConnectionInterface::kIceConnectionCompleted) {
6340 SetIceConnectionState(
6341 PeerConnectionInterface::kIceConnectionDisconnected);
6342 }
6343 break;
6344 case cricket::kIceConnectionFailed:
6345 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6346 break;
6347 case cricket::kIceConnectionConnected:
6348 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6349 "all transports are writable.";
6350 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6351 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6352 break;
6353 case cricket::kIceConnectionCompleted:
6354 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6355 "all transports are complete.";
6356 if (ice_connection_state_ !=
6357 PeerConnectionInterface::kIceConnectionConnected) {
6358 // If jumping directly from "checking" to "connected",
6359 // signal "connected" first.
6360 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6361 }
6362 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6363 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6364 ReportTransportStats();
6365 break;
6366 default:
6367 RTC_NOTREACHED();
6368 }
6369}
6370
Steve Anton75737c02017-11-06 10:37:17 -08006371void PeerConnection::OnTransportControllerCandidatesGathered(
6372 const std::string& transport_name,
6373 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006374 int sdp_mline_index;
6375 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006376 RTC_LOG(LS_ERROR)
6377 << "OnTransportControllerCandidatesGathered: content name "
6378 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006379 return;
6380 }
6381
6382 for (cricket::Candidates::const_iterator citer = candidates.begin();
6383 citer != candidates.end(); ++citer) {
6384 // Use transport_name as the candidate media id.
6385 std::unique_ptr<JsepIceCandidate> candidate(
6386 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6387 if (local_description()) {
6388 mutable_local_description()->AddCandidate(candidate.get());
6389 }
6390 OnIceCandidate(std::move(candidate));
6391 }
6392}
6393
Eldar Relloda13ea22019-06-01 12:23:43 +03006394void PeerConnection::OnTransportControllerCandidateError(
6395 const cricket::IceCandidateErrorEvent& event) {
6396 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6397 event.error_text);
6398}
6399
Steve Anton75737c02017-11-06 10:37:17 -08006400void PeerConnection::OnTransportControllerCandidatesRemoved(
6401 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006402 // Sanity check.
6403 for (const cricket::Candidate& candidate : candidates) {
6404 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006405 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006406 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006407 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006408 return;
6409 }
6410 }
6411
6412 if (local_description()) {
6413 mutable_local_description()->RemoveCandidates(candidates);
6414 }
6415 OnIceCandidatesRemoved(candidates);
6416}
6417
Alex Drake00c7ecf2019-08-06 10:54:47 -07006418void PeerConnection::OnTransportControllerCandidateChanged(
6419 const cricket::CandidatePairChangeEvent& event) {
6420 OnSelectedCandidatePairChanged(event);
6421}
6422
Steve Anton75737c02017-11-06 10:37:17 -08006423void PeerConnection::OnTransportControllerDtlsHandshakeError(
6424 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006425 RTC_HISTOGRAM_ENUMERATION(
6426 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6427 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006428}
6429
Steve Antoned10bd92017-12-05 10:52:59 -08006430void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006431 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006432 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006433 if (channel && !channel->enabled()) {
6434 channel->Enable(true);
6435 }
Steve Anton75737c02017-11-06 10:37:17 -08006436 }
6437
Steve Anton4171afb2017-11-20 10:20:22 -08006438 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006439 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006440 }
Steve Anton75737c02017-11-06 10:37:17 -08006441}
6442
6443// Returns the media index for a local ice candidate given the content name.
6444bool PeerConnection::GetLocalCandidateMediaIndex(
6445 const std::string& content_name,
6446 int* sdp_mline_index) {
6447 if (!local_description() || !sdp_mline_index) {
6448 return false;
6449 }
6450
6451 bool content_found = false;
6452 const ContentInfos& contents = local_description()->description()->contents();
6453 for (size_t index = 0; index < contents.size(); ++index) {
6454 if (contents[index].name == content_name) {
6455 *sdp_mline_index = static_cast<int>(index);
6456 content_found = true;
6457 break;
6458 }
6459 }
6460 return content_found;
6461}
6462
6463bool PeerConnection::UseCandidatesInSessionDescription(
6464 const SessionDescriptionInterface* remote_desc) {
6465 if (!remote_desc) {
6466 return true;
6467 }
6468 bool ret = true;
6469
6470 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6471 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6472 for (size_t n = 0; n < candidates->count(); ++n) {
6473 const IceCandidateInterface* candidate = candidates->at(n);
6474 bool valid = false;
6475 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6476 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006477 RTC_LOG(LS_INFO)
6478 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006479 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006480 }
6481 continue;
6482 }
6483 ret = UseCandidate(candidate);
6484 if (!ret) {
6485 break;
6486 }
6487 }
6488 }
6489 return ret;
6490}
6491
6492bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006493 RTCErrorOr<const cricket::ContentInfo*> result =
6494 FindContentInfo(remote_description(), candidate);
6495 if (!result.ok()) {
6496 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6497 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006498 return false;
6499 }
Steve Anton75737c02017-11-06 10:37:17 -08006500 std::vector<cricket::Candidate> candidates;
6501 candidates.push_back(candidate->candidate());
6502 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006503 RTCError error = transport_controller_->AddRemoteCandidates(
6504 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006505 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006506 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006507 // Candidates successfully submitted for checking.
6508 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6509 ice_connection_state_ ==
6510 PeerConnectionInterface::kIceConnectionDisconnected) {
6511 // If state is New, then the session has just gotten its first remote ICE
6512 // candidates, so go to Checking.
6513 // If state is Disconnected, the session is re-using old candidates or
6514 // receiving additional ones, so go to Checking.
6515 // If state is Connected, stay Connected.
6516 // TODO(bemasc): If state is Connected, and the new candidates are for a
6517 // newly added transport, then the state actually _should_ move to
6518 // checking. Add a way to distinguish that case.
6519 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6520 }
6521 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006522 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006523 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006524 }
6525 return true;
6526}
6527
Guido Urdaneta41633172019-05-23 20:12:29 +02006528RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6529 const SessionDescriptionInterface* description,
6530 const IceCandidateInterface* candidate) {
6531 if (candidate->sdp_mline_index() >= 0) {
6532 size_t mediacontent_index =
6533 static_cast<size_t>(candidate->sdp_mline_index());
6534 size_t content_size = description->description()->contents().size();
6535 if (mediacontent_index < content_size) {
6536 return &description->description()->contents()[mediacontent_index];
6537 } else {
6538 return RTCError(RTCErrorType::INVALID_RANGE,
6539 "Media line index (" +
6540 rtc::ToString(candidate->sdp_mline_index()) +
6541 ") out of range (number of mlines: " +
6542 rtc::ToString(content_size) + ").");
6543 }
6544 } else if (!candidate->sdp_mid().empty()) {
6545 auto& contents = description->description()->contents();
6546 auto it = absl::c_find_if(
6547 contents, [candidate](const cricket::ContentInfo& content_info) {
6548 return content_info.mid() == candidate->sdp_mid();
6549 });
6550 if (it == contents.end()) {
6551 return RTCError(
6552 RTCErrorType::INVALID_PARAMETER,
6553 "Mid " + candidate->sdp_mid() +
6554 " specified but no media section with that mid found.");
6555 } else {
6556 return &*it;
6557 }
6558 }
6559
6560 return RTCError(RTCErrorType::INVALID_PARAMETER,
6561 "Neither sdp_mline_index nor sdp_mid specified.");
6562}
6563
Steve Anton75737c02017-11-06 10:37:17 -08006564void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006565 // Destroy video channel first since it may have a pointer to the
6566 // voice channel.
6567 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006568 if (!video_info || video_info->rejected) {
6569 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006570 }
6571
Steve Anton6fec8802017-12-04 10:37:29 -08006572 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6573 if (!audio_info || audio_info->rejected) {
6574 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006575 }
6576
6577 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6578 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006579 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006580 }
6581}
6582
Steve Antondcc3c022017-12-22 16:02:54 -08006583RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6584 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006585 const cricket::ContentGroup* bundle_group = nullptr;
6586 if (configuration_.bundle_policy ==
6587 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006588 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006589 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6591 "max-bundle configured but session description "
6592 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006593 }
6594 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006595 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006596}
6597
6598RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006599 // Creating the media channels. Transports should already have been created
6600 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006601 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006602 if (voice && !voice->rejected &&
6603 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006604 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006605 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006606 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6607 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006608 }
6609 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6610 }
6611
Steve Antondcc3c022017-12-22 16:02:54 -08006612 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006613 if (video && !video->rejected &&
6614 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006615 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006616 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006617 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6618 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006619 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006620 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006621 }
6622
Steve Antondcc3c022017-12-22 16:02:54 -08006623 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006624 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006625 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006626 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006627 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6628 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006629 }
6630 }
6631
Steve Anton8a006912017-12-04 15:25:56 -08006632 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006633}
6634
Steve Anton4171afb2017-11-20 10:20:22 -08006635// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006636cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006637 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006638 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006639 MediaTransportConfig media_transport_config =
6640 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006641
Steve Anton75737c02017-11-06 10:37:17 -08006642 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006643 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006644 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6645 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006646 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006647 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006648 }
Steve Anton75737c02017-11-06 10:37:17 -08006649 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6650 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006651 voice_channel->SignalSentPacket.connect(this,
6652 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006653 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006654
Steve Antoneda6ccd2017-12-04 10:21:55 -08006655 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006656}
6657
Steve Anton4171afb2017-11-20 10:20:22 -08006658// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006659cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006660 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006661 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006662 MediaTransportConfig media_transport_config =
6663 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006664
Steve Anton75737c02017-11-06 10:37:17 -08006665 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006666 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006667 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6668 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006669 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006670 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006671 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006672 }
Steve Anton75737c02017-11-06 10:37:17 -08006673 video_channel->SignalDtlsSrtpSetupFailure.connect(
6674 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006675 video_channel->SignalSentPacket.connect(this,
6676 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006677 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006678
Steve Antoneda6ccd2017-12-04 10:21:55 -08006679 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006680}
6681
Zhi Huange830e682018-03-30 10:48:35 -07006682bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006683 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006684 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006685 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006686 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6687 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006688 if (!network_thread()->Invoke<bool>(
6689 RTC_FROM_HERE,
6690 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6691 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006692 return false;
6693 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006694
6695 // All non-RTP data channels must initialize |sctp_data_channels_|.
6696 for (const auto& channel : sctp_data_channels_) {
6697 channel->OnTransportChannelCreated();
6698 }
6699 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006700 case cricket::DCT_RTP:
6701 default:
6702 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6703 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6704 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006705 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006706 if (!rtp_data_channel_) {
6707 return false;
6708 }
6709 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6710 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6711 rtp_data_channel_->SignalSentPacket.connect(
6712 this, &PeerConnection::OnSentPacket_w);
6713 rtp_data_channel_->SetRtpTransport(rtp_transport);
6714 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006715 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006716 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006717}
6718
6719Call::Stats PeerConnection::GetCallStats() {
6720 if (!worker_thread()->IsCurrent()) {
6721 return worker_thread()->Invoke<Call::Stats>(
6722 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6723 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006724 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006725 if (call_) {
6726 return call_->GetStats();
6727 } else {
6728 return Call::Stats();
6729 }
6730}
6731
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006732bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006733 DataChannelTransportInterface* transport =
6734 transport_controller_->GetDataChannelTransport(mid);
6735 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006736 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006737 << "Data channel transport is not available for data channels, mid="
6738 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006739 return false;
6740 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006741 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006742
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006743 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02006744 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006745 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006746
6747 // Note: setting the data sink and checking initial state must be done last,
6748 // after setting up the data channel. Setting the data sink may trigger
6749 // callbacks to PeerConnection which require the transport to be completely
6750 // set up (eg. OnReadyToSend()).
6751 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006752 return true;
6753}
6754
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006755void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006756 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006757 return;
6758 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006759 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6760 << *sctp_mid_;
6761
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006762 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6763 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006764 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00006765 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006766 if (data_channel_transport_) {
6767 data_channel_transport_->SetDataSink(nullptr);
6768 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006769 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006770}
6771
Steve Anton75737c02017-11-06 10:37:17 -08006772// Returns false if bundle is enabled and rtcp_mux is disabled.
6773bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6774 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6775 if (!bundle_enabled)
6776 return true;
6777
6778 const cricket::ContentGroup* bundle_group =
6779 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6780 RTC_DCHECK(bundle_group != NULL);
6781
6782 const cricket::ContentInfos& contents = desc->contents();
6783 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6784 citer != contents.end(); ++citer) {
6785 const cricket::ContentInfo* content = (&*citer);
6786 RTC_DCHECK(content != NULL);
6787 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006788 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006789 if (!HasRtcpMuxEnabled(content))
6790 return false;
6791 }
6792 }
6793 // RTCP-MUX is enabled in all the contents.
6794 return true;
6795}
6796
6797bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006798 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006799}
6800
Steve Anton06817cd2018-12-18 15:55:30 -08006801static RTCError ValidateMids(const cricket::SessionDescription& description) {
6802 std::set<std::string> mids;
6803 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006804 if (content.name.empty()) {
6805 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6806 "A media section is missing a MID attribute.");
6807 }
Steve Anton06817cd2018-12-18 15:55:30 -08006808 if (!mids.insert(content.name).second) {
6809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6810 "Duplicate a=mid value '" + content.name + "'.");
6811 }
6812 }
6813 return RTCError::OK();
6814}
6815
Steve Anton8a006912017-12-04 15:25:56 -08006816RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006817 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006818 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006819 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006820 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006821 }
6822
6823 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006824 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006825 }
6826
Steve Anton3828c062017-12-06 10:34:51 -08006827 SdpType type = sdesc->GetType();
6828 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6829 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006830 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006831 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006832 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006833 }
6834
Steve Anton06817cd2018-12-18 15:55:30 -08006835 RTCError error = ValidateMids(*sdesc->description());
6836 if (!error.ok()) {
6837 return error;
6838 }
6839
Steve Anton75737c02017-11-06 10:37:17 -08006840 // Verify crypto settings.
6841 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006842 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6843 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006844 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006845 if (!crypto_error.ok()) {
6846 return crypto_error;
6847 }
Steve Anton75737c02017-11-06 10:37:17 -08006848 }
6849
6850 // Verify ice-ufrag and ice-pwd.
6851 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006852 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6853 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006854 }
6855
6856 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6858 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006859 }
6860
6861 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6862 // m-lines that do not rtcp-mux enabled.
6863
6864 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006865 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006866 // With an answer we want to compare the new answer session description with
6867 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006868 const cricket::SessionDescription* offer_desc =
6869 (source == cricket::CS_LOCAL) ? remote_description()->description()
6870 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006871 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6872 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6873 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006874 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6875 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006876 }
6877 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006878 // The re-offers should respect the order of m= sections in current
6879 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006880 // With a re-offer, either the current local or current remote descriptions
6881 // could be the most up to date, so we would like to check against both of
6882 // them if they exist. It could be the case that one of them has a 0 port
6883 // for a media section, but the other does not. This is important to check
6884 // against in the case that we are recycling an m= section.
6885 const cricket::SessionDescription* current_desc = nullptr;
6886 const cricket::SessionDescription* secondary_current_desc = nullptr;
6887 if (local_description()) {
6888 current_desc = local_description()->description();
6889 if (remote_description()) {
6890 secondary_current_desc = remote_description()->description();
6891 }
6892 } else if (remote_description()) {
6893 current_desc = remote_description()->description();
6894 }
Steve Anton75737c02017-11-06 10:37:17 -08006895 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006896 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6897 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006898 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6899 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006900 }
6901 }
6902
Steve Antonba42e992018-04-09 14:10:01 -07006903 if (IsUnifiedPlan()) {
6904 // Ensure that each audio and video media section has at most one
6905 // "StreamParams". This will return an error if receiving a session
6906 // description from a "Plan B" endpoint which adds multiple tracks of the
6907 // same type. With Unified Plan, there can only be at most one track per
6908 // media section.
6909 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006910 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006911 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6912 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6913 desc.streams().size() > 1u) {
6914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6915 "Media section has more than one track specified "
6916 "with a=ssrc lines which is not supported with "
6917 "Unified Plan.");
6918 }
6919 }
6920 }
6921
Steve Anton8a006912017-12-04 15:25:56 -08006922 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006923}
6924
Steve Anton3828c062017-12-06 10:34:51 -08006925bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006926 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006927 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006928 return (state == PeerConnectionInterface::kStable) ||
6929 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006930 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006931 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006932 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6933 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6934 }
6935}
6936
Steve Anton3828c062017-12-06 10:34:51 -08006937bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006938 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006939 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006940 return (state == PeerConnectionInterface::kStable) ||
6941 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006942 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006943 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006944 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6945 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6946 }
6947}
6948
Steve Antonf8470812017-12-04 10:46:21 -08006949const char* PeerConnection::SessionErrorToString(SessionError error) const {
6950 switch (error) {
6951 case SessionError::kNone:
6952 return "ERROR_NONE";
6953 case SessionError::kContent:
6954 return "ERROR_CONTENT";
6955 case SessionError::kTransport:
6956 return "ERROR_TRANSPORT";
6957 }
6958 RTC_NOTREACHED();
6959 return "";
6960}
6961
Steve Anton75737c02017-11-06 10:37:17 -08006962std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006963 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006964 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6965 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006966 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006967}
6968
Steve Anton8e20f172018-03-06 10:55:04 -08006969void PeerConnection::ReportSdpFormatReceived(
6970 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006971 int num_audio_mlines = 0;
6972 int num_video_mlines = 0;
6973 int num_audio_tracks = 0;
6974 int num_video_tracks = 0;
6975 for (const ContentInfo& content : remote_offer.description()->contents()) {
6976 cricket::MediaType media_type = content.media_description()->type();
6977 int num_tracks = std::max(
6978 1, static_cast<int>(content.media_description()->streams().size()));
6979 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6980 num_audio_mlines += 1;
6981 num_audio_tracks += num_tracks;
6982 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6983 num_video_mlines += 1;
6984 num_video_tracks += num_tracks;
6985 }
6986 }
6987 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6988 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6989 format = kSdpFormatReceivedComplexUnifiedPlan;
6990 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6991 format = kSdpFormatReceivedComplexPlanB;
6992 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6993 format = kSdpFormatReceivedSimple;
6994 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006995 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6996 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006997}
6998
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006999void PeerConnection::ReportIceCandidateCollected(
7000 const cricket::Candidate& candidate) {
7001 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7002 if (candidate.address().IsPrivateIP()) {
7003 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7004 }
7005 if (candidate.address().IsUnresolvedIP()) {
7006 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7007 }
7008 if (candidate.address().family() == AF_INET6) {
7009 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7010 }
7011}
7012
7013void PeerConnection::ReportRemoteIceCandidateAdded(
7014 const cricket::Candidate& candidate) {
7015 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7016 if (candidate.address().IsPrivateIP()) {
7017 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7018 }
7019 if (candidate.address().IsUnresolvedIP()) {
7020 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7021 }
7022 if (candidate.address().family() == AF_INET6) {
7023 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7024 }
7025}
7026
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007027void PeerConnection::NoteUsageEvent(UsageEvent event) {
7028 RTC_DCHECK_RUN_ON(signaling_thread());
7029 usage_event_accumulator_ |= static_cast<int>(event);
7030}
7031
7032void PeerConnection::ReportUsagePattern() const {
7033 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007034 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7035 usage_event_accumulator_,
7036 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007037 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007038 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007039 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7040 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007041 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007042 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7043 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7044 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7045 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007046 // If called after close(), we can't report, because observer may have
7047 // been deallocated, and therefore pointer is null. Write to log instead.
7048 if (observer_) {
7049 Observer()->OnInterestingUsage(usage_event_accumulator_);
7050 } else {
7051 RTC_LOG(LS_INFO) << "Interesting usage signature "
7052 << usage_event_accumulator_
7053 << " observed after observer shutdown";
7054 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007055 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007056}
7057
Steve Anton0ffaaa22018-02-23 10:31:30 -08007058void PeerConnection::ReportNegotiatedSdpSemantics(
7059 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007060 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007061 switch (answer.description()->msid_signaling()) {
7062 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007063 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007064 break;
7065 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007066 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007067 break;
7068 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007069 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007070 break;
7071 case cricket::kMsidSignalingMediaSection |
7072 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007073 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007074 break;
7075 default:
7076 RTC_NOTREACHED();
7077 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007078 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7079 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007080}
7081
Steve Anton75737c02017-11-06 10:37:17 -08007082// We need to check the local/remote description for the Transport instead of
7083// the session, because a new Transport added during renegotiation may have
7084// them unset while the session has them set from the previous negotiation.
7085// Not doing so may trigger the auto generation of transport description and
7086// mess up DTLS identity information, ICE credential, etc.
7087bool PeerConnection::ReadyToUseRemoteCandidate(
7088 const IceCandidateInterface* candidate,
7089 const SessionDescriptionInterface* remote_desc,
7090 bool* valid) {
7091 *valid = true;
7092
7093 const SessionDescriptionInterface* current_remote_desc =
7094 remote_desc ? remote_desc : remote_description();
7095
7096 if (!current_remote_desc) {
7097 return false;
7098 }
7099
Guido Urdaneta41633172019-05-23 20:12:29 +02007100 RTCErrorOr<const cricket::ContentInfo*> result =
7101 FindContentInfo(current_remote_desc, candidate);
7102 if (!result.ok()) {
7103 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7104 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007105
7106 *valid = false;
7107 return false;
7108 }
7109
Guido Urdaneta41633172019-05-23 20:12:29 +02007110 std::string transport_name = GetTransportName(result.value()->name);
7111 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007112}
7113
7114bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007115 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007116 (dtls_enabled_ ||
7117 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007118}
7119
7120void PeerConnection::OnTransportControllerGatheringState(
7121 cricket::IceGatheringState state) {
7122 RTC_DCHECK(signaling_thread()->IsCurrent());
7123 if (state == cricket::kIceGatheringGathering) {
7124 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7125 } else if (state == cricket::kIceGatheringComplete) {
7126 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7127 }
7128}
7129
7130void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007131 std::map<std::string, std::set<cricket::MediaType>>
7132 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007133 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007134 if (transceiver->internal()->channel()) {
7135 const std::string& transport_name =
7136 transceiver->internal()->channel()->transport_name();
7137 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007138 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007139 }
Steve Anton75737c02017-11-06 10:37:17 -08007140 }
7141 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007142 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7143 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007144 }
Zhi Huange830e682018-03-30 10:48:35 -07007145
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007146 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007147 if (transport_name) {
7148 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007149 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007150 }
Zhi Huange830e682018-03-30 10:48:35 -07007151
Steve Antonc7b964c2018-02-01 14:39:45 -08007152 for (const auto& entry : media_types_by_transport_name) {
7153 const std::string& transport_name = entry.first;
7154 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007155 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007156 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007157 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007158 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007159 }
7160 }
7161}
7162// Walk through the ConnectionInfos to gather best connection usage
7163// for IPv4 and IPv6.
7164void PeerConnection::ReportBestConnectionState(
7165 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007166 for (const cricket::TransportChannelStats& channel_stats :
7167 stats.channel_stats) {
7168 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007169 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007170 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007171 continue;
7172 }
7173
Steve Antonc7b964c2018-02-01 14:39:45 -08007174 const cricket::Candidate& local = connection_info.local_candidate;
7175 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007176
7177 // Increment the counter for IceCandidatePairType.
7178 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7179 (local.type() == RELAY_PORT_TYPE &&
7180 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007181 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7182 GetIceCandidatePairCounter(local, remote),
7183 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007184 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007185 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7186 GetIceCandidatePairCounter(local, remote),
7187 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007188 } else {
7189 RTC_CHECK(0);
7190 }
Steve Anton75737c02017-11-06 10:37:17 -08007191
7192 // Increment the counter for IP type.
7193 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007194 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7195 kBestConnections_IPv4,
7196 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007197 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007198 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7199 kBestConnections_IPv6,
7200 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007201 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007202 RTC_CHECK(!local.address().hostname().empty() &&
7203 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007204 }
7205
7206 return;
7207 }
7208 }
7209}
7210
7211void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007212 const cricket::TransportStats& stats,
7213 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007214 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7215 return;
7216 }
7217
7218 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7219 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7220 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7221 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7222 return;
7223 }
7224
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007225 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7226 for (cricket::MediaType media_type : media_types) {
7227 switch (media_type) {
7228 case cricket::MEDIA_TYPE_AUDIO:
7229 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7230 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7231 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7232 break;
7233 case cricket::MEDIA_TYPE_VIDEO:
7234 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7235 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7236 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7237 break;
7238 case cricket::MEDIA_TYPE_DATA:
7239 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7240 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7241 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7242 break;
7243 default:
7244 RTC_NOTREACHED();
7245 continue;
7246 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007247 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007248 }
7249
7250 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7251 for (cricket::MediaType media_type : media_types) {
7252 switch (media_type) {
7253 case cricket::MEDIA_TYPE_AUDIO:
7254 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7255 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7256 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7257 break;
7258 case cricket::MEDIA_TYPE_VIDEO:
7259 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7260 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7261 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7262 break;
7263 case cricket::MEDIA_TYPE_DATA:
7264 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7265 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7266 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7267 break;
7268 default:
7269 RTC_NOTREACHED();
7270 continue;
7271 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007272 }
Steve Anton75737c02017-11-06 10:37:17 -08007273 }
7274}
7275
7276void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007277 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007278 RTC_DCHECK(call_);
7279 call_->OnSentPacket(sent_packet);
7280}
7281
7282const std::string PeerConnection::GetTransportName(
7283 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007284 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007285 if (channel) {
7286 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007287 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007288 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007289 RTC_DCHECK(sctp_mid_);
7290 if (content_name == *sctp_mid_) {
7291 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007292 }
7293 }
7294 // Return an empty string if failed to retrieve the transport name.
7295 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007296}
7297
Steve Anton6fec8802017-12-04 10:37:29 -08007298void PeerConnection::DestroyTransceiverChannel(
7299 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7300 transceiver) {
7301 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007302
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007303 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007304 if (channel) {
7305 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007306 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007307 }
7308}
7309
7310void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007311 if (rtp_data_channel_) {
7312 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007313 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007314 rtp_data_channel_ = nullptr;
7315 }
7316
7317 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7318 // grab a reference to this PeerConnection. If this is called from the
7319 // PeerConnection destructor, the RefCountedObject vtable will have already
7320 // been destroyed (since it is a subclass of PeerConnection) and using
7321 // rtc::Bind will cause "Pure virtual function called" error to appear.
7322
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007323 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007324 OnDataChannelDestroyed();
7325 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7326 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007327 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007328 });
7329 }
Steve Anton6fec8802017-12-04 10:37:29 -08007330}
7331
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007332void PeerConnection::DestroyChannelInterface(
7333 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007334 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007335 switch (channel->media_type()) {
7336 case cricket::MEDIA_TYPE_AUDIO:
7337 channel_manager()->DestroyVoiceChannel(
7338 static_cast<cricket::VoiceChannel*>(channel));
7339 break;
7340 case cricket::MEDIA_TYPE_VIDEO:
7341 channel_manager()->DestroyVideoChannel(
7342 static_cast<cricket::VideoChannel*>(channel));
7343 break;
7344 case cricket::MEDIA_TYPE_DATA:
7345 channel_manager()->DestroyRtpDataChannel(
7346 static_cast<cricket::RtpDataChannel*>(channel));
7347 break;
7348 default:
7349 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7350 break;
7351 }
Zhi Huange830e682018-03-30 10:48:35 -07007352}
Steve Anton6fec8802017-12-04 10:37:29 -08007353
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007354bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007355 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007356 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007357 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007358 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007359 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007360 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007361 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007362 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007363 auto base_channel = GetChannel(mid);
7364 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007365 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007366 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007367
Karl Wiberg5966c502019-02-21 23:55:09 +01007368 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007369 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007370 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007371
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007372 if (data_channel_transport_ && mid == sctp_mid_ &&
7373 data_channel_transport_ != data_channel_transport) {
7374 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7375 // it's bundled).
7376 data_channel_transport_->SetDataSink(nullptr);
7377 data_channel_transport_ = data_channel_transport;
7378 if (data_channel_transport) {
7379 data_channel_transport->SetDataSink(this);
7380
7381 // There's a new data channel transport. This needs to be signaled to the
7382 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7383 // necessary when bundling is applied.
7384 data_channel_transport_invoker_->AsyncInvoke<void>(
7385 RTC_FROM_HERE, signaling_thread(), [this] {
7386 RTC_DCHECK_RUN_ON(signaling_thread());
7387 for (auto channel : sctp_data_channels_) {
7388 channel->OnTransportChannelCreated();
7389 }
7390 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007391 }
7392 }
7393
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007394 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007395}
7396
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007397void PeerConnection::OnSetStreams() {
7398 RTC_DCHECK_RUN_ON(signaling_thread());
7399 if (IsUnifiedPlan())
7400 UpdateNegotiationNeeded();
7401}
7402
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007403PeerConnectionObserver* PeerConnection::Observer() const {
7404 // In earlier production code, the pointer was not cleared on close,
7405 // which might have led to undefined behavior if the observer was not
7406 // deallocated, or strange crashes if it was.
7407 // We use CHECK in order to catch such behavior if it exists.
7408 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7409 RTC_CHECK(observer_);
7410 return observer_;
7411}
7412
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007413CryptoOptions PeerConnection::GetCryptoOptions() {
7414 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7415 // after it has been removed.
7416 return configuration_.crypto_options.has_value()
7417 ? *configuration_.crypto_options
7418 : factory_->options().crypto_options;
7419}
7420
Harald Alvestrand89061872018-01-02 14:08:34 +01007421void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007422 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007423 if (stats_collector_) {
7424 stats_collector_->ClearCachedStatsReport();
7425 }
7426}
7427
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007428void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007429 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7430 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007431}
7432
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007433void PeerConnection::UpdateNegotiationNeeded() {
7434 RTC_DCHECK_RUN_ON(signaling_thread());
7435 if (!IsUnifiedPlan()) {
7436 Observer()->OnRenegotiationNeeded();
7437 return;
7438 }
7439
7440 // If connection's [[IsClosed]] slot is true, abort these steps.
7441 if (IsClosed())
7442 return;
7443
7444 // If connection's signaling state is not "stable", abort these steps.
7445 if (signaling_state() != kStable)
7446 return;
7447
7448 // NOTE
7449 // The negotiation-needed flag will be updated once the state transitions to
7450 // "stable", as part of the steps for setting an RTCSessionDescription.
7451
7452 // If the result of checking if negotiation is needed is false, clear the
7453 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7454 // to false, and abort these steps.
7455 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7456 if (!is_negotiation_needed) {
7457 is_negotiation_needed_ = false;
7458 return;
7459 }
7460
7461 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7462 // steps.
7463 if (is_negotiation_needed_)
7464 return;
7465
7466 // Set connection's [[NegotiationNeeded]] slot to true.
7467 is_negotiation_needed_ = true;
7468
7469 // Queue a task that runs the following steps:
7470 // If connection's [[IsClosed]] slot is true, abort these steps.
7471 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7472 // Fire an event named negotiationneeded at connection.
7473 Observer()->OnRenegotiationNeeded();
7474}
7475
7476bool PeerConnection::CheckIfNegotiationIsNeeded() {
7477 RTC_DCHECK_RUN_ON(signaling_thread());
7478 // 1. If any implementation-specific negotiation is required, as described at
7479 // the start of this section, return true.
7480
Henrik Boström79b69802019-07-18 11:16:56 +02007481 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7482 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7483 return true;
7484 }
7485
7486 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007487 const SessionDescriptionInterface* description = current_local_description();
7488 if (!description)
7489 return true;
7490
Henrik Boström79b69802019-07-18 11:16:56 +02007491 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007492 // description has been negotiated yet for data, return true.
7493 if (!sctp_data_channels_.empty()) {
7494 if (!cricket::GetFirstDataContent(description->description()->contents()))
7495 return true;
7496 }
7497
Henrik Boström79b69802019-07-18 11:16:56 +02007498 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007499 // following checks:
7500 for (const auto& transceiver : transceivers_) {
7501 const ContentInfo* current_local_msection =
7502 FindTransceiverMSection(transceiver.get(), description);
7503
7504 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7505 transceiver.get(), current_remote_description());
7506
Henrik Boström79b69802019-07-18 11:16:56 +02007507 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007508 // but the associated m= section is not yet rejected in
7509 // connection.[[CurrentLocalDescription]] or
7510 // connection.[[CurrentRemoteDescription]], return true.
7511 if (transceiver->stopped()) {
7512 if (current_local_msection && !current_local_msection->rejected &&
7513 ((current_remote_msection && !current_remote_msection->rejected) ||
7514 !current_remote_msection)) {
7515 return true;
7516 }
7517 continue;
7518 }
7519
Henrik Boström79b69802019-07-18 11:16:56 +02007520 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007521 // section in description, return true.
7522 if (!current_local_msection)
7523 return true;
7524
7525 const MediaContentDescription* current_local_media_description =
7526 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007527 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007528 // in description then perform the following checks:
7529
Henrik Boström79b69802019-07-18 11:16:56 +02007530 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007531 // associated m= section in description either doesn't contain a single
7532 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7533 // m= section, or the MSID values themselves, differ from what is in
7534 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7535 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7536 if (current_local_media_description->streams().size() == 0)
7537 return true;
7538
7539 std::vector<std::string> msection_msids;
7540 for (const auto& stream : current_local_media_description->streams()) {
7541 for (const std::string& msid : stream.stream_ids())
7542 msection_msids.push_back(msid);
7543 }
7544
7545 std::vector<std::string> transceiver_msids =
7546 transceiver->sender()->stream_ids();
7547 if (msection_msids.size() != transceiver_msids.size())
7548 return true;
7549
7550 absl::c_sort(transceiver_msids);
7551 absl::c_sort(msection_msids);
7552 if (transceiver_msids != msection_msids)
7553 return true;
7554 }
7555
Henrik Boström79b69802019-07-18 11:16:56 +02007556 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007557 // associated m= section in neither connection.[[CurrentLocalDescription]]
7558 // nor connection.[[CurrentRemoteDescription]] matches
7559 // transceiver.[[Direction]], return true.
7560 if (description->GetType() == SdpType::kOffer) {
7561 if (!current_remote_description())
7562 return true;
7563
7564 if (!current_remote_msection)
7565 return true;
7566
7567 RtpTransceiverDirection current_local_direction =
7568 current_local_media_description->direction();
7569 RtpTransceiverDirection current_remote_direction =
7570 current_remote_msection->media_description()->direction();
7571 if (transceiver->direction() != current_local_direction &&
7572 transceiver->direction() !=
7573 RtpTransceiverDirectionReversed(current_remote_direction)) {
7574 return true;
7575 }
7576 }
7577
Henrik Boström79b69802019-07-18 11:16:56 +02007578 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007579 // associated m= section in the description does not match
7580 // transceiver.[[Direction]] intersected with the offered direction (as
7581 // described in [JSEP] (section 5.3.1.)), return true.
7582 if (description->GetType() == SdpType::kAnswer) {
7583 if (!remote_description())
7584 return true;
7585
7586 const ContentInfo* offered_remote_msection =
7587 FindTransceiverMSection(transceiver.get(), remote_description());
7588
7589 RtpTransceiverDirection offered_direction =
7590 offered_remote_msection
7591 ? offered_remote_msection->media_description()->direction()
7592 : RtpTransceiverDirection::kInactive;
7593
7594 if (current_local_media_description->direction() !=
7595 (RtpTransceiverDirectionIntersection(
7596 transceiver->direction(),
7597 RtpTransceiverDirectionReversed(offered_direction)))) {
7598 return true;
7599 }
7600 }
7601 }
7602
7603 // If all the preceding checks were performed and true was not returned,
7604 // nothing remains to be negotiated; return false.
7605 return false;
7606}
7607
Eldar Rello5ab79e62019-10-09 18:29:44 +03007608RTCError PeerConnection::Rollback() {
7609 auto state = signaling_state();
7610 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7611 state != PeerConnectionInterface::kHaveRemoteOffer) {
7612 return RTCError(RTCErrorType::INVALID_STATE,
7613 "Called in wrong signalingState: " +
7614 GetSignalingStateString(signaling_state()));
7615 }
7616 RTC_DCHECK_RUN_ON(signaling_thread());
7617 RTC_DCHECK(IsUnifiedPlan());
7618
7619 for (auto&& transceivers_stable_state_pair :
7620 transceiver_stable_states_by_transceivers_) {
7621 auto transceiver = transceivers_stable_state_pair.first;
7622 auto state = transceivers_stable_state_pair.second;
7623 RTC_DCHECK(transceiver->internal()->mid().has_value());
7624 std::string mid = transceiver->internal()->mid().value();
7625 transport_controller_->RollbackTransportForMid(mid);
7626 DestroyTransceiverChannel(transceiver);
7627
7628 if (state.newly_created()) {
7629 // Remove added transceivers with no added track.
7630 if (transceiver->internal()->sender()->track()) {
7631 transceiver->internal()->set_created_by_addtrack(true);
7632 } else {
7633 int remaining_transceiver_count = 0;
7634 for (auto&& t : transceivers_) {
7635 if (t != transceiver) {
7636 transceivers_[remaining_transceiver_count++] = t;
7637 }
7638 }
7639 transceivers_.resize(remaining_transceiver_count);
7640 }
7641 }
7642 transceiver->internal()->sender_internal()->set_transport(nullptr);
7643 transceiver->internal()->receiver_internal()->set_transport(nullptr);
7644 transceiver->internal()->set_direction(state.direction());
7645 transceiver->internal()->set_mid(state.mid());
7646 transceiver->internal()->set_mline_index(state.mline_index());
7647 }
7648 transceiver_stable_states_by_transceivers_.clear();
7649 pending_local_description_.reset();
7650 pending_remote_description_.reset();
7651 ChangeSignalingState(PeerConnectionInterface::kStable);
7652 return RTCError::OK();
7653}
7654
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007655} // namespace webrtc