blob: 494a649e8f3320c3d29829526d2f0ec0bb6908a1 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Steve Antondcc3c022017-12-22 16:02:54 -080016#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080017#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080018#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020
Steve Anton64b626b2019-01-28 17:25:26 -080021#include "absl/algorithm/container.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 10:44:59 -070059#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/trace_event.h"
61#include "system_wrappers/include/clock.h"
62#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070063#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080071using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080072using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080074using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080075using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080076using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080079using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070080using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080082
Steve Antonba818672017-11-06 10:21:57 -080083namespace webrtc {
84
Steve Anton75737c02017-11-06 10:37:17 -080085// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080089const char kInvalidCandidates[] = "Description contains invalid candidates.";
90const char kInvalidSdp[] = "Invalid session description.";
91const char kMlineMismatchInAnswer[] =
92 "The order of m-lines in answer doesn't match order in offer. Rejecting "
93 "answer.";
94const char kMlineMismatchInSubsequentOffer[] =
95 "The order of m-lines in subsequent offer doesn't match order from "
96 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080097const char kSdpWithoutDtlsFingerprint[] =
98 "Called with SDP without DTLS fingerprint.";
99const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
100const char kSdpWithoutIceUfragPwd[] =
101 "Called with SDP without ice-ufrag and ice-pwd.";
102const char kSessionError[] = "Session error code: ";
103const char kSessionErrorDesc[] = "Session error description: ";
104const char kDtlsSrtpSetupFailureRtp[] =
105 "Couldn't set up DTLS-SRTP on RTP channel.";
106const char kDtlsSrtpSetupFailureRtcp[] =
107 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108
Steve Anton75737c02017-11-06 10:37:17 -0800109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700117
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800118// UMA metric names.
119const char kSimulcastVersionApplyLocalDescription[] =
120 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
121const char kSimulcastVersionApplyRemoteDescription[] =
122 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
123const char kSimulcastNumberOfEncodings[] =
124 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
125const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
126
Seth Hampson845e8782018-03-02 11:34:10 -0800127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700130
zhihuang8f65cdf2016-05-06 18:40:30 -0700131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40 +0000134enum {
135 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
136 MSG_SET_SESSIONDESCRIPTION_FAILED,
137 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
138 MSG_GETSTATS,
139 MSG_FREE_DATACHANNELS,
140 MSG_REPORT_USAGE_PATTERN,
141};
142
Harald Alvestrand19793842018-06-25 12:03:50 +0200143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40 +0000145struct SetSessionDescriptionMsg : public rtc::MessageData {
146 explicit SetSessionDescriptionMsg(
147 webrtc::SetSessionDescriptionObserver* observer)
148 : observer(observer) {}
149
150 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
151 RTCError error;
152};
153
154struct CreateSessionDescriptionMsg : public rtc::MessageData {
155 explicit CreateSessionDescriptionMsg(
156 webrtc::CreateSessionDescriptionObserver* observer)
157 : observer(observer) {}
158
159 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
160 RTCError error;
161};
162
163struct GetStatsMsg : public rtc::MessageData {
164 GetStatsMsg(webrtc::StatsObserver* observer,
165 webrtc::MediaStreamTrackInterface* track)
166 : observer(observer), track(track) {}
167 rtc::scoped_refptr<webrtc::StatsObserver> observer;
168 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
169};
170
deadbeefab9b2d12015-10-14 11:33:11 -0700171// Check if we can send |new_stream| on a PeerConnection.
172bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
173 webrtc::MediaStreamInterface* new_stream) {
174 if (!new_stream || !current_streams) {
175 return false;
176 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 12:49:08 -0700185// If the direction is "recvonly" or "inactive", treat the description
186// as containing no streams.
187// See: https://code.google.com/p/webrtc/issues/detail?id=5054
188std::vector<cricket::StreamParams> GetActiveStreams(
189 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 11:33:11 -0700195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 14:10:50 -0700201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700213 }
214 } else {
215 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
216 if (video_media_description_options) {
217 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700220 }
221 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700222 }
zhihuang1c378ed2017-08-17 14:10:50 -0700223}
olka3c747662017-08-17 06:50:32 -0700224
zhihuang1c378ed2017-08-17 14:10:50 -0700225// Add options to |session_options| from |rtp_data_channels|.
226void AddRtpDataChannelOptions(
227 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
228 rtp_data_channels,
229 cricket::MediaDescriptionOptions* data_media_description_options) {
230 if (!data_media_description_options) {
231 return;
232 }
deadbeefab9b2d12015-10-14 11:33:11 -0700233 // Check for data channels.
234 for (const auto& kv : rtp_data_channels) {
235 const DataChannel* channel = kv.second;
236 if (channel->state() == DataChannel::kConnecting ||
237 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700238 // Legacy RTP data channels are signaled with the track/stream ID set to
239 // the data channel's label.
240 data_media_description_options->AddRtpDataChannel(channel->label(),
241 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246uint32_t ConvertIceTransportTypeToCandidateFilter(
247 PeerConnectionInterface::IceTransportsType type) {
248 switch (type) {
249 case PeerConnectionInterface::kNone:
250 return cricket::CF_NONE;
251 case PeerConnectionInterface::kRelay:
252 return cricket::CF_RELAY;
253 case PeerConnectionInterface::kNoHost:
254 return (cricket::CF_ALL & ~cricket::CF_HOST);
255 case PeerConnectionInterface::kAll:
256 return cricket::CF_ALL;
257 default:
nissec80e7412017-01-11 05:56:46 -0800258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 10:21:57 -0800263std::string GetSignalingStateString(
264 PeerConnectionInterface::SignalingState state) {
265 switch (state) {
266 case PeerConnectionInterface::kStable:
267 return "kStable";
268 case PeerConnectionInterface::kHaveLocalOffer:
269 return "kHaveLocalOffer";
270 case PeerConnectionInterface::kHaveLocalPrAnswer:
271 return "kHavePrAnswer";
272 case PeerConnectionInterface::kHaveRemoteOffer:
273 return "kHaveRemoteOffer";
274 case PeerConnectionInterface::kHaveRemotePrAnswer:
275 return "kHaveRemotePrAnswer";
276 case PeerConnectionInterface::kClosed:
277 return "kClosed";
278 }
279 RTC_NOTREACHED();
280 return "";
281}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282
Steve Anton75737c02017-11-06 10:37:17 -0800283IceCandidatePairType GetIceCandidatePairCounter(
284 const cricket::Candidate& local,
285 const cricket::Candidate& remote) {
286 const auto& l = local.type();
287 const auto& r = remote.type();
288 const auto& host = LOCAL_PORT_TYPE;
289 const auto& srflx = STUN_PORT_TYPE;
290 const auto& relay = RELAY_PORT_TYPE;
291 const auto& prflx = PRFLX_PORT_TYPE;
292 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 bool local_hostname =
294 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
295 bool remote_hostname = !remote.address().hostname().empty() &&
296 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800299 if (local_hostname) {
300 if (remote_hostname) {
301 return kIceCandidatePairHostNameHostName;
302 } else if (remote_private) {
303 return kIceCandidatePairHostNameHostPrivate;
304 } else {
305 return kIceCandidatePairHostNameHostPublic;
306 }
307 } else if (local_private) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostPrivateHostName;
310 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPublicHostPrivate;
320 } else {
321 return kIceCandidatePairHostPublicHostPublic;
322 }
323 }
324 }
325 if (l == host && r == srflx)
326 return kIceCandidatePairHostSrflx;
327 if (l == host && r == relay)
328 return kIceCandidatePairHostRelay;
329 if (l == host && r == prflx)
330 return kIceCandidatePairHostPrflx;
331 if (l == srflx && r == host)
332 return kIceCandidatePairSrflxHost;
333 if (l == srflx && r == srflx)
334 return kIceCandidatePairSrflxSrflx;
335 if (l == srflx && r == relay)
336 return kIceCandidatePairSrflxRelay;
337 if (l == srflx && r == prflx)
338 return kIceCandidatePairSrflxPrflx;
339 if (l == relay && r == host)
340 return kIceCandidatePairRelayHost;
341 if (l == relay && r == srflx)
342 return kIceCandidatePairRelaySrflx;
343 if (l == relay && r == relay)
344 return kIceCandidatePairRelayRelay;
345 if (l == relay && r == prflx)
346 return kIceCandidatePairRelayPrflx;
347 if (l == prflx && r == host)
348 return kIceCandidatePairPrflxHost;
349 if (l == prflx && r == srflx)
350 return kIceCandidatePairPrflxSrflx;
351 if (l == prflx && r == relay)
352 return kIceCandidatePairPrflxRelay;
353 return kIceCandidatePairMax;
354}
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356// Logic to decide if an m= section can be recycled. This means that the new
357// m= section is not rejected, but the old local or remote m= section is
358// rejected. |old_content_one| and |old_content_two| refer to the m= section
359// of the old remote and old local descriptions in no particular order.
360// We need to check both the old local and remote because either
361// could be the most current from the latest negotation.
362bool IsMediaSectionBeingRecycled(SdpType type,
363 const ContentInfo& content,
364 const ContentInfo* old_content_one,
365 const ContentInfo* old_content_two) {
366 return type == SdpType::kOffer && !content.rejected &&
367 ((old_content_one && old_content_one->rejected) ||
368 (old_content_two && old_content_two->rejected));
369}
370
Steve Anton75737c02017-11-06 10:37:17 -0800371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372// |current_desc|. The number of m= sections in |new_desc| should be no
373// less than |current_desc|. In the case of checking an answer's
374// |new_desc|, the |current_desc| is the last offer that was set as the
375// local or remote. In the case of checking an offer's |new_desc| we
376// check against the local and remote descriptions stored from the last
377// negotiation, because either of these could be the most up to date for
378// possible rejected m sections. These are the |current_desc| and
379// |secondary_current_desc|.
380bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
381 const SessionDescription* secondary_current_desc,
382 const SessionDescription& new_desc,
383 const SdpType type) {
384 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
389 const cricket::ContentInfo* secondary_content_info = nullptr;
390 if (secondary_current_desc &&
391 i < secondary_current_desc->contents().size()) {
392 secondary_content_info = &secondary_current_desc->contents()[i];
393 }
394 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
395 &current_desc.contents()[i],
396 secondary_content_info)) {
397 // For new offer descriptions, if the media section can be recycled, it's
398 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800405 new_desc.contents()[i].media_description();
406 const MediaContentDescription* current_desc_mdesc =
407 current_desc.contents()[i].media_description();
408 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800418}
419
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200422 // Array of structs needed to map {KeyExchangeProtocolType,
423 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
424 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
425 static constexpr struct {
426 KeyExchangeProtocolType protocol_type;
427 cricket::MediaType media_type;
428 KeyExchangeProtocolMedia protocol_media;
429 } kEnumCounterKeyProtocolMediaMap[] = {
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
434 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeDtlsData},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
437 kEnumCounterKeyProtocolMediaTypeSdesAudio},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
439 kEnumCounterKeyProtocolMediaTypeSdesVideo},
440 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
441 kEnumCounterKeyProtocolMediaTypeSdesData},
442 };
443
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446
Mirko Bonadeiab499822018-09-11 10:43:20 +0200447 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
448 if (i.protocol_type == protocol_type && i.media_type == media_type) {
449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
450 i.protocol_media,
451 kEnumCounterKeyProtocolMediaTypeMax);
452 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100453 }
454}
455
Harald Alvestrand76829d72018-07-18 23:24:36 +0200456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 10:37:17 -0800461// Checks that each non-rejected content has SDES crypto keys or a DTLS
462// fingerprint, unless it's in a BUNDLE group, in which case only the
463// BUNDLE-tag section (first media section/description in the BUNDLE group)
464// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
465// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
466// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800472 continue;
473 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100474 // Note what media is used with each crypto protocol, for all sections.
475 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
476 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 // This isn't the first media section in the BUNDLE group, so it's not
482 // required to have crypto attributes, since only the crypto attributes
483 // from the first section actually get used.
484 continue;
485 }
486
487 // If the content isn't rejected or bundled into another m= section, crypto
488 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800508 }
509 }
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800512}
513
514// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
515// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
516// media section/description in the BUNDLE group) needs a ufrag and pwd.
517bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
518 const cricket::ContentGroup* bundle =
519 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 continue;
523 }
Steve Anton8a006912017-12-04 15:25:56 -0800524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 // This isn't the first media section in the BUNDLE group, so it's not
528 // required to have ufrag/password, since only the ufrag/password from
529 // the first section actually get used.
530 continue;
531 }
532
533 // If the content isn't rejected or bundled into another m= section,
534 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 10:37:17 -0800550// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
551bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
552 const SessionDescriptionInterface* new_desc,
553 const std::string& content_name) {
554 if (!old_desc) {
555 return false;
556 }
557 const SessionDescription* new_sd = new_desc->description();
558 const SessionDescription* old_sd = old_desc->description();
559 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
560 if (!cinfo || cinfo->rejected) {
561 return false;
562 }
563 // If the content isn't rejected, check if ufrag and password has changed.
564 const cricket::TransportDescription* new_transport_desc =
565 new_sd->GetTransportDescriptionByName(content_name);
566 const cricket::TransportDescription* old_transport_desc =
567 old_sd->GetTransportDescriptionByName(content_name);
568 if (!new_transport_desc || !old_transport_desc) {
569 // No transport description exists. This is not an ICE restart.
570 return false;
571 }
572 if (cricket::IceCredentialsChanged(
573 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
574 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-16 17:08:42 -0800582// Generates a string error message for SetLocalDescription/SetRemoteDescription
583// from an RTCError.
584std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
585 SdpType type,
586 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200590 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800591}
592
Seth Hampson5b4f0752018-04-02 16:31:36 -0700593std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
594 std::string output = "streams=[";
595 const char* separator = "";
596 for (const auto& stream_id : stream_ids) {
597 output.append(separator).append(stream_id);
598 separator = ", ";
599 }
600 output.append("]");
601 return output;
602}
603
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200608 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700609 }
610 return rtc_configuration_parameter;
611}
612
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800613void ReportSimulcastApiVersion(const char* name,
614 const SessionDescription& session) {
615 bool has_legacy = false;
616 bool has_spec_compliant = false;
617 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200618 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800619 continue;
620 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200621 has_spec_compliant |= content.media_description()->HasSimulcast();
622 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800623 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
624 }
625 }
626
627 if (has_legacy) {
628 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
629 kSimulcastApiVersionMax);
630 }
631 if (has_spec_compliant) {
632 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
633 kSimulcastApiVersionMax);
634 }
635 if (!has_legacy && !has_spec_compliant) {
636 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
637 kSimulcastApiVersionMax);
638 }
639}
640
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200641const ContentInfo* FindTransceiverMSection(
642 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
643 const SessionDescriptionInterface* session_description) {
644 return transceiver->mid()
645 ? session_description->description()->GetContentByName(
646 *transceiver->mid())
647 : nullptr;
648}
649
Steve Anton75737c02017-11-06 10:37:17 -0800650} // namespace
651
Henrik Boström79b69802019-07-18 11:16:56 +0200652class PeerConnection::LocalIceCredentialsToReplace {
653 public:
654 // Sets the ICE credentials that need restarting to the ICE credentials of
655 // the current and pending descriptions.
656 void SetIceCredentialsFromLocalDescriptions(
657 const SessionDescriptionInterface* current_local_description,
658 const SessionDescriptionInterface* pending_local_description) {
659 ice_credentials_.clear();
660 if (current_local_description) {
661 AppendIceCredentialsFromSessionDescription(*current_local_description);
662 }
663 if (pending_local_description) {
664 AppendIceCredentialsFromSessionDescription(*pending_local_description);
665 }
666 }
667
668 void ClearIceCredentials() { ice_credentials_.clear(); }
669
670 // Returns true if we have ICE credentials that need restarting.
671 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
672
673 // Returns true if |local_description| shares no ICE credentials with the
674 // ICE credentials that need restarting.
675 bool SatisfiesIceRestart(
676 const SessionDescriptionInterface& local_description) const {
677 for (const auto& transport_info :
678 local_description.description()->transport_infos()) {
679 if (ice_credentials_.find(std::make_pair(
680 transport_info.description.ice_ufrag,
681 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
682 return false;
683 }
684 }
685 return true;
686 }
687
688 private:
689 void AppendIceCredentialsFromSessionDescription(
690 const SessionDescriptionInterface& desc) {
691 for (const auto& transport_info : desc.description()->transport_infos()) {
692 ice_credentials_.insert(
693 std::make_pair(transport_info.description.ice_ufrag,
694 transport_info.description.ice_pwd));
695 }
696 }
697
698 std::set<std::pair<std::string, std::string>> ice_credentials_;
699};
700
Henrik Boström31638672017-11-23 17:48:32 +0100701// Upon completion, posts a task to execute the callback of the
702// SetSessionDescriptionObserver asynchronously on the same thread. At this
703// point, the state of the peer connection might no longer reflect the effects
704// of the SetRemoteDescription operation, as the peer connection could have been
705// modified during the post.
706// TODO(hbos): Remove this class once we remove the version of
707// PeerConnectionInterface::SetRemoteDescription() that takes a
708// SetSessionDescriptionObserver as an argument.
709class PeerConnection::SetRemoteDescriptionObserverAdapter
710 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
711 public:
712 SetRemoteDescriptionObserverAdapter(
713 rtc::scoped_refptr<PeerConnection> pc,
714 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
715 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
716
717 // SetRemoteDescriptionObserverInterface implementation.
718 void OnSetRemoteDescriptionComplete(RTCError error) override {
719 if (error.ok())
720 pc_->PostSetSessionDescriptionSuccess(wrapper_);
721 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100722 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100723 }
724
725 private:
726 rtc::scoped_refptr<PeerConnection> pc_;
727 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
728};
729
deadbeef293e9262017-01-11 12:28:30 -0800730bool PeerConnectionInterface::RTCConfiguration::operator==(
731 const PeerConnectionInterface::RTCConfiguration& o) const {
732 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800734 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000735 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800737 BundlePolicy bundle_policy;
738 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700739 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
740 int ice_candidate_pool_size;
741 bool disable_ipv6;
742 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700743 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100744 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200746 absl::optional<int> screencast_min_bitrate;
747 absl::optional<bool> combined_audio_video_bwe;
748 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800749 TcpCandidatePolicy tcp_candidate_policy;
750 CandidateNetworkPolicy candidate_network_policy;
751 int audio_jitter_buffer_max_packets;
752 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100753 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800755 int ice_connection_receiving_timeout;
756 int ice_backup_candidate_pair_ping_interval;
757 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800758 bool prioritize_most_likely_ice_candidate_pairs;
759 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800760 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700761 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800762 bool presume_writable_when_fully_relayed;
763 bool enable_ice_renomination;
764 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700765 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200766 absl::optional<int> ice_check_interval_strong_connectivity;
767 absl::optional<int> ice_check_interval_weak_connectivity;
768 absl::optional<int> ice_check_min_interval;
769 absl::optional<int> ice_unwritable_timeout;
770 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800771 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200772 absl::optional<int> stun_candidate_keepalive_interval;
773 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200774 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800775 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200776 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700777 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700778 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700779 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700780 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700781 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700782 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700783 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100784 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200785 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300786 bool enable_implicit_rollback;
deadbeef293e9262017-01-11 12:28:30 -0800787 };
788 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
789 "Did you add something to RTCConfiguration and forget to "
790 "update operator==?");
791 return type == o.type && servers == o.servers &&
792 bundle_policy == o.bundle_policy &&
793 rtcp_mux_policy == o.rtcp_mux_policy &&
794 tcp_candidate_policy == o.tcp_candidate_policy &&
795 candidate_network_policy == o.candidate_network_policy &&
796 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
797 audio_jitter_buffer_fast_accelerate ==
798 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100799 audio_jitter_buffer_min_delay_ms ==
800 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100801 audio_jitter_buffer_enable_rtx_handling ==
802 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800803 ice_connection_receiving_timeout ==
804 o.ice_connection_receiving_timeout &&
805 ice_backup_candidate_pair_ping_interval ==
806 o.ice_backup_candidate_pair_ping_interval &&
807 continual_gathering_policy == o.continual_gathering_policy &&
808 certificates == o.certificates &&
809 prioritize_most_likely_ice_candidate_pairs ==
810 o.prioritize_most_likely_ice_candidate_pairs &&
811 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800812 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700813 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100814 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800815 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800816 screencast_min_bitrate == o.screencast_min_bitrate &&
817 combined_audio_video_bwe == o.combined_audio_video_bwe &&
818 enable_dtls_srtp == o.enable_dtls_srtp &&
819 ice_candidate_pool_size == o.ice_candidate_pool_size &&
820 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700821 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800822 presume_writable_when_fully_relayed ==
823 o.presume_writable_when_fully_relayed &&
824 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800825 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700826 surface_ice_candidates_on_ice_transport_type_changed ==
827 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800828 ice_check_interval_strong_connectivity ==
829 o.ice_check_interval_strong_connectivity &&
830 ice_check_interval_weak_connectivity ==
831 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700832 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700833 ice_unwritable_timeout == o.ice_unwritable_timeout &&
834 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800835 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800836 stun_candidate_keepalive_interval ==
837 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200838 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800839 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800840 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700841 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700842 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700843 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700844 use_media_transport_for_data_channels ==
845 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700846 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700847 use_datagram_transport_for_data_channels ==
848 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700849 use_datagram_transport_for_data_channels_receive_only ==
850 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100851 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200852 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300853 turn_logging_id == o.turn_logging_id &&
854 enable_implicit_rollback == o.enable_implicit_rollback;
deadbeef293e9262017-01-11 12:28:30 -0800855}
856
857bool PeerConnectionInterface::RTCConfiguration::operator!=(
858 const PeerConnectionInterface::RTCConfiguration& o) const {
859 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800860}
861
zhihuang8f65cdf2016-05-06 18:40:30 -0700862// Generate a RTCP CNAME when a PeerConnection is created.
863std::string GenerateRtcpCname() {
864 std::string cname;
865 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100866 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800867 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700868 }
869 return cname;
870}
871
zhihuang1c378ed2017-08-17 14:10:50 -0700872bool ValidateOfferAnswerOptions(
873 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
874 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
875 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700876}
877
zhihuang1c378ed2017-08-17 14:10:50 -0700878// From |rtc_options|, fill parts of |session_options| shared by all generated
879// m= sections (in other words, nothing that involves a map/array).
880void ExtractSharedMediaSessionOptions(
881 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
882 cricket::MediaSessionOptions* session_options) {
883 session_options->vad_enabled = rtc_options.voice_activity_detection;
884 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200885 session_options->raw_packetization_for_video =
886 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700887}
zhihuanga77e6bb2017-08-14 18:17:48 -0700888
zhihuang38ede132017-06-15 12:52:32 -0700889PeerConnection::PeerConnection(PeerConnectionFactory* factory,
890 std::unique_ptr<RtcEventLog> event_log,
891 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700893 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100894 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700895 datagram_transport_config_(
896 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700897 datagram_transport_data_channel_config_(
898 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700899 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700900 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700901 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100902 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200903 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -0700904 data_channel_transport_(nullptr),
Henrik Boström79b69802019-07-18 11:16:56 +0200905 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
907PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100908 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800909 RTC_DCHECK_RUN_ON(signaling_thread());
910
Steve Anton8af21862017-12-15 11:20:13 -0800911 // Need to stop transceivers before destroying the stats collector because
912 // AudioRtpSender has a reference to the StatsCollector it will update when
913 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100914 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800915 transceiver->Stop();
916 }
Steve Anton4171afb2017-11-20 10:20:22 -0800917
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700918 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800919 if (stats_collector_) {
920 stats_collector_->WaitForPendingRequest();
921 stats_collector_ = nullptr;
922 }
Steve Anton75737c02017-11-06 10:37:17 -0800923
Steve Anton8af21862017-12-15 11:20:13 -0800924 // Don't destroy BaseChannels until after stats has been cleaned up so that
925 // the last stats request can still read from the channels.
926 DestroyAllChannels();
927
Mirko Bonadei675513b2017-11-09 11:09:25 +0100928 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800929
930 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800931 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700932 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800933 transport_controller_.reset();
934
deadbeef91dd5672016-05-18 16:55:30 -0700935 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100936 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
937 RTC_DCHECK_RUN_ON(network_thread());
938 port_allocator_.reset();
939 });
eladalon248fd4f2017-09-06 05:18:15 -0700940 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700941 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100942 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700943 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800944 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700945 event_log_.reset();
946 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947}
948
Steve Anton8af21862017-12-15 11:20:13 -0800949void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800950 // Destroy video channels first since they may have a pointer to a voice
951 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100952 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800953 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800954 DestroyTransceiverChannel(transceiver);
955 }
956 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100957 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800958 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800959 DestroyTransceiverChannel(transceiver);
960 }
961 }
962 DestroyDataChannel();
963}
964
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000966 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700967 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100968 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100969 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100970 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700971
972 RTCError config_error = ValidateConfiguration(configuration);
973 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100974 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700975 return false;
976 }
977
Benjamin Wrightcab58882018-05-02 15:12:47 -0700978 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100979 RTC_LOG(LS_ERROR)
980 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100981 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800982 return false;
983 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200984
Benjamin Wrightcab58882018-05-02 15:12:47 -0700985 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800986 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100987 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100988 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800989 return false;
990 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700991
Benjamin Wrightcab58882018-05-02 15:12:47 -0700992 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700993 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700994 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700995 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800996
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200997 cricket::ServerAddresses stun_servers;
998 std::vector<cricket::RelayServerConfig> turn_servers;
999
1000 RTCErrorType parse_error =
1001 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1002 if (parse_error != RTCErrorType::NONE) {
1003 return false;
1004 }
1005
Jonas Oreland3c028422019-08-22 16:16:35 +02001006 // Add the turn logging id to all turn servers
1007 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1008 turn_server.turn_logging_id = configuration.turn_logging_id;
1009 }
1010
deadbeef91dd5672016-05-18 16:55:30 -07001011 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001012 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001013 const auto pa_result =
1014 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001015 RTC_FROM_HERE,
1016 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001017 stun_servers, turn_servers, configuration));
1018
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001019 // If initialization was successful, note if STUN or TURN servers
1020 // were supplied.
1021 if (!stun_servers.empty()) {
1022 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1023 }
1024 if (!turn_servers.empty()) {
1025 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001028 // Send information about IPv4/IPv6 status.
1029 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001030 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001031 address_family = kPeerConnection_IPv6;
1032 } else {
1033 address_family = kPeerConnection_IPv4;
1034 }
1035 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1036 kPeerConnectionAddressFamilyCounter_Max);
1037
Zhi Huange830e682018-03-30 10:48:35 -07001038 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1039
Steve Anton75737c02017-11-06 10:37:17 -08001040 // RFC 3264: The numeric value of the session id and version in the
1041 // o line MUST be representable with a "64 bit signed integer".
1042 // Due to this constraint session id |session_id_| is max limited to
1043 // LLONG_MAX.
1044 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001045 JsepTransportController::Config config;
1046 config.redetermine_role_on_ice_restart =
1047 configuration.redetermine_role_on_ice_restart;
1048 config.ssl_max_version = factory_->options().ssl_max_version;
1049 config.disable_encryption = options.disable_encryption;
1050 config.bundle_policy = configuration.bundle_policy;
1051 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001052 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1053 // stub.
1054 config.crypto_options = configuration.crypto_options.has_value()
1055 ? *configuration.crypto_options
1056 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001057 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001058 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1059 // since the JsepTransportController instance is owned by this PeerConnection
1060 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1061 // pointer.
1062 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1063 int64_t packet_time_us) {
1064 RTC_DCHECK_RUN_ON(network_thread());
1065 rtcp_invoker_.AsyncInvoke<void>(
1066 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1067 RTC_DCHECK_RUN_ON(worker_thread());
1068 // |call_| is reset on the worker thread in the PeerConnection
1069 // destructor, so we check that it's still valid before propagating
1070 // the packet.
1071 if (call_) {
1072 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1073 packet_time_us);
1074 }
1075 });
1076 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001077 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001078#if defined(ENABLE_EXTERNAL_AUTH)
1079 config.enable_external_auth = true;
1080#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001081 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001082
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001083 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001084 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001085 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001086 use_datagram_transport_for_data_channels_ =
1087 datagram_transport_data_channel_config_.enabled &&
1088 configuration.use_datagram_transport_for_data_channels.value_or(
1089 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001090 use_datagram_transport_for_data_channels_receive_only_ =
1091 configuration.use_datagram_transport_for_data_channels_receive_only
1092 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001093 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1094 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001095 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001096 if (!factory_->media_transport_factory()) {
1097 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001098 << "PeerConnecton is initialized with use_media_transport = true or "
1099 << "use_media_transport_for_data_channels = true "
1100 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001101 return false;
1102 }
1103
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001104 if (configuration.use_media_transport ||
1105 configuration.use_media_transport_for_data_channels) {
1106 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1107 // RTP media transport is introduced. But until then, we require SDES to
1108 // be enabled.
1109 if (configuration.enable_dtls_srtp.has_value() &&
1110 configuration.enable_dtls_srtp.value()) {
1111 RTC_LOG(LS_WARNING)
1112 << "When media transport is used, SDES must be enabled. Set "
1113 "configuration.enable_dtls_srtp to false. use_media_transport="
1114 << configuration.use_media_transport
1115 << ", use_media_transport_for_data_channels="
1116 << configuration.use_media_transport_for_data_channels;
1117 return false;
1118 }
1119 }
1120
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001121 config.use_media_transport_for_media = configuration.use_media_transport;
1122 config.use_media_transport_for_data_channels =
1123 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001124 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001125 config.use_datagram_transport_for_data_channels =
1126 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001127 config.use_datagram_transport_for_data_channels_receive_only =
1128 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001129 config.media_transport_factory = factory_->media_transport_factory();
1130 }
1131
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001132 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1133 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1134 if (!configuration.certificates.empty()) {
1135 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1136 // just picking the first one. The decision should be made based on the DTLS
1137 // handshake. The DTLS negotiations need to know about all certificates.
1138 certificate = configuration.certificates[0];
1139 }
1140
1141 if (options.disable_encryption) {
1142 dtls_enabled_ = false;
1143 } else {
1144 // Enable DTLS by default if we have an identity store or a certificate.
1145 dtls_enabled_ = (dependencies.cert_generator || certificate);
1146 // |configuration| can override the default |dtls_enabled_| value.
1147 if (configuration.enable_dtls_srtp) {
1148 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1149 }
1150 }
1151
1152 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1153
1154 if (use_datagram_transport_for_data_channels_) {
1155 if (configuration.enable_rtp_data_channel) {
1156 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1157 "use_datagram_transport_for_data_channels are "
1158 "incompatible and cannot both be set to true";
1159 return false;
1160 }
1161 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1162 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1163 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1164 } else {
1165 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1166 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1167 config.sctp_factory = sctp_factory_.get();
1168 }
1169 } else if (configuration.use_media_transport_for_data_channels) {
1170 if (configuration.enable_rtp_data_channel) {
1171 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1172 "use_media_transport_for_data_channels are "
1173 "incompatible and cannot both be set to true";
1174 return false;
1175 }
1176 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1177 } else if (configuration.enable_rtp_data_channel) {
1178 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1179 // set. It takes precendence over the disable_sctp_data_channels
1180 // PeerConnectionFactoryInterface::Options.
1181 data_channel_type_ = cricket::DCT_RTP;
1182 } else {
1183 // DTLS has to be enabled to use SCTP.
1184 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1185 data_channel_type_ = cricket::DCT_SCTP;
1186 config.sctp_factory = sctp_factory_.get();
1187 }
1188 }
1189
Zhi Huange830e682018-03-30 10:48:35 -07001190 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001191 signaling_thread(), network_thread(), port_allocator_.get(),
1192 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001193 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001194 this, &PeerConnection::OnTransportControllerConnectionState);
1195 transport_controller_->SignalStandardizedIceConnectionState.connect(
1196 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001197 transport_controller_->SignalConnectionState.connect(
1198 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001199 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001200 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001201 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001202 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001203 transport_controller_->SignalIceCandidateError.connect(
1204 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001205 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001206 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1207 transport_controller_->SignalDtlsHandshakeError.connect(
1208 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001209 transport_controller_->SignalIceCandidatePairChanged.connect(
1210 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001211
deadbeefab9b2d12015-10-14 11:33:11 -07001212 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001213 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214
Steve Antonba818672017-11-06 10:21:57 -08001215 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001216 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001217
Steve Antond25da372017-11-06 14:50:29 -08001218 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001219
Steve Anton75737c02017-11-06 10:37:17 -08001220 video_options_.screencast_min_bitrate_kbps =
1221 configuration.screencast_min_bitrate;
1222 audio_options_.combined_audio_video_bwe =
1223 configuration.combined_audio_video_bwe;
1224
1225 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001226 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001227
1228 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001229 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001230
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001231 audio_options_.audio_jitter_buffer_min_delay_ms =
1232 configuration.audio_jitter_buffer_min_delay_ms;
1233
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001234 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1235 configuration.audio_jitter_buffer_enable_rtx_handling;
1236
Steve Anton75737c02017-11-06 10:37:17 -08001237 // Whether the certificate generator/certificate is null or not determines
1238 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1239 // the right instructions by clearing the variables if needed.
1240 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001241 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001242 certificate = nullptr;
1243 } else if (certificate) {
1244 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001245 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001246 }
1247
1248 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1249 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001250 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001251 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1252 this, &PeerConnection::OnCertificateReady);
1253
1254 if (options.disable_encryption) {
1255 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1256 }
1257
1258 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001259 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001260 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261
Steve Anton4171afb2017-11-20 10:20:22 -08001262 // Add default audio/video transceivers for Plan B SDP.
1263 if (!IsUnifiedPlan()) {
1264 transceivers_.push_back(
1265 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1266 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1267 transceivers_.push_back(
1268 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1269 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1270 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001271 int delay_ms =
1272 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001273 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1274 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001275
1276 if (dependencies.video_bitrate_allocator_factory) {
1277 video_bitrate_allocator_factory_ =
1278 std::move(dependencies.video_bitrate_allocator_factory);
1279 } else {
1280 video_bitrate_allocator_factory_ =
1281 CreateBuiltinVideoBitrateAllocatorFactory();
1282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 return true;
1284}
1285
Steve Anton038834f2017-07-14 15:59:59 -07001286RTCError PeerConnection::ValidateConfiguration(
1287 const RTCConfiguration& config) const {
1288 if (config.ice_regather_interval_range &&
1289 config.continual_gathering_policy == GATHER_ONCE) {
1290 return RTCError(RTCErrorType::INVALID_PARAMETER,
1291 "ice_regather_interval_range specified but continual "
1292 "gathering policy is GATHER_ONCE");
1293 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001294 auto result =
1295 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1296 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001297}
1298
Yves Gerey665174f2018-06-19 15:03:05 +02001299rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001300 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001301 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1302 "Plan SdpSemantics. Please use GetSenders "
1303 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001304 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305}
1306
Yves Gerey665174f2018-06-19 15:03:05 +02001307rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001308 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001309 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1310 "Plan SdpSemantics. Please use GetReceivers "
1311 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001312 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001315bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001316 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001317 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1318 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001319 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 if (IsClosed()) {
1321 return false;
1322 }
deadbeefab9b2d12015-10-14 11:33:11 -07001323 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 return false;
1325 }
deadbeefab9b2d12015-10-14 11:33:11 -07001326
1327 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001328 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1329 observer->SignalAudioTrackAdded.connect(this,
1330 &PeerConnection::OnAudioTrackAdded);
1331 observer->SignalAudioTrackRemoved.connect(
1332 this, &PeerConnection::OnAudioTrackRemoved);
1333 observer->SignalVideoTrackAdded.connect(this,
1334 &PeerConnection::OnVideoTrackAdded);
1335 observer->SignalVideoTrackRemoved.connect(
1336 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001337 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001338
deadbeefab9b2d12015-10-14 11:33:11 -07001339 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001340 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001341 }
1342 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001343 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001344 }
1345
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001346 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001347 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348 return true;
1349}
1350
1351void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001352 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001353 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1354 "Plan SdpSemantics. Please use RemoveTrack "
1355 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001356 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001357 if (!IsClosed()) {
1358 for (const auto& track : local_stream->GetAudioTracks()) {
1359 RemoveAudioTrack(track.get(), local_stream);
1360 }
1361 for (const auto& track : local_stream->GetVideoTracks()) {
1362 RemoveVideoTrack(track.get(), local_stream);
1363 }
deadbeefab9b2d12015-10-14 11:33:11 -07001364 }
deadbeefab9b2d12015-10-14 11:33:11 -07001365 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001366 stream_observers_.erase(
1367 std::remove_if(
1368 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001369 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001370 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001371 }),
1372 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001373
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 if (IsClosed()) {
1375 return;
1376 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001377 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378}
1379
Steve Anton2d6c76a2018-01-05 17:10:52 -08001380RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001382 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001383 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001384 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001385 if (!track) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1387 }
1388 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1389 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1391 "Track has invalid kind: " + track->kind());
1392 }
Steve Antonf9381f02017-12-14 10:23:57 -08001393 if (IsClosed()) {
1394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1395 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001396 }
Steve Anton4171afb2017-11-20 10:20:22 -08001397 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001398 LOG_AND_RETURN_ERROR(
1399 RTCErrorType::INVALID_PARAMETER,
1400 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001403 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1404 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001405 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001406 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001407 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001408 }
1409 return sender_or_error;
1410}
deadbeefe1f9d832016-01-14 15:35:42 -08001411
Steve Antonf9381f02017-12-14 10:23:57 -08001412RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1413PeerConnection::AddTrackPlanB(
1414 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001415 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001416 if (stream_ids.size() > 1u) {
1417 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1418 "AddTrack with more than one stream is not "
1419 "supported with Plan B semantics.");
1420 }
1421 std::vector<std::string> adjusted_stream_ids = stream_ids;
1422 if (adjusted_stream_ids.empty()) {
1423 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1424 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001425 cricket::MediaType media_type =
1426 (track->kind() == MediaStreamTrackInterface::kAudioKind
1427 ? cricket::MEDIA_TYPE_AUDIO
1428 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001429 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001430 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001431 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001432 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001433 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001434 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001435 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001436 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001437 if (sender_info) {
1438 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001439 }
Steve Antonf9381f02017-12-14 10:23:57 -08001440 } else {
1441 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001442 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001443 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001444 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001445 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001446 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001447 if (sender_info) {
1448 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001449 }
deadbeefe1f9d832016-01-14 15:35:42 -08001450 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001452}
deadbeefe1f9d832016-01-14 15:35:42 -08001453
Steve Antonf9381f02017-12-14 10:23:57 -08001454RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1455PeerConnection::AddTrackUnifiedPlan(
1456 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001457 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001458 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1459 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001460 RTC_LOG(LS_INFO) << "Reusing an existing "
1461 << cricket::MediaTypeToString(transceiver->media_type())
1462 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001463 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001464 transceiver->internal()->set_direction(
1465 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001466 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001467 transceiver->internal()->set_direction(
1468 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001469 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001470 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001471 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001472 } else {
1473 cricket::MediaType media_type =
1474 (track->kind() == MediaStreamTrackInterface::kAudioKind
1475 ? cricket::MEDIA_TYPE_AUDIO
1476 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001477 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1478 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001479 std::string sender_id = track->id();
1480 // Avoid creating a sender with an existing ID by generating a random ID.
1481 // This can happen if this is the second time AddTrack has created a sender
1482 // for this track.
1483 if (FindSenderById(sender_id)) {
1484 sender_id = rtc::CreateRandomUuid();
1485 }
Florent Castelli892acf02018-10-01 22:47:20 +02001486 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001487 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1488 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001489 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001490 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001491 }
Steve Antonf9381f02017-12-14 10:23:57 -08001492 return transceiver->sender();
1493}
1494
1495rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1496PeerConnection::FindFirstTransceiverForAddedTrack(
1497 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1498 RTC_DCHECK(track);
1499 for (auto transceiver : transceivers_) {
1500 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001501 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001502 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001503 !transceiver->internal()->has_ever_been_used_to_send() &&
1504 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001505 return transceiver;
1506 }
1507 }
1508 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001509}
1510
1511bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1512 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001513 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001514}
1515
Steve Anton24db5732018-07-23 10:27:33 -07001516RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001517 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001518 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001519 if (!sender) {
1520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1521 }
deadbeefe1f9d832016-01-14 15:35:42 -08001522 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001523 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1524 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001525 }
Steve Antonf9381f02017-12-14 10:23:57 -08001526 if (IsUnifiedPlan()) {
1527 auto transceiver = FindTransceiverBySender(sender);
1528 if (!transceiver || !sender->track()) {
1529 return RTCError::OK();
1530 }
1531 sender->SetTrack(nullptr);
1532 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001533 transceiver->internal()->set_direction(
1534 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001535 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001536 transceiver->internal()->set_direction(
1537 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001538 }
Steve Anton4171afb2017-11-20 10:20:22 -08001539 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001540 bool removed;
1541 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1542 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1543 } else {
1544 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1545 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1546 }
1547 if (!removed) {
1548 LOG_AND_RETURN_ERROR(
1549 RTCErrorType::INVALID_PARAMETER,
1550 "Couldn't find sender " + sender->id() + " to remove.");
1551 }
Steve Anton4171afb2017-11-20 10:20:22 -08001552 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001553 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001554 return RTCError::OK();
1555}
1556
1557rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1558PeerConnection::FindTransceiverBySender(
1559 rtc::scoped_refptr<RtpSenderInterface> sender) {
1560 for (auto transceiver : transceivers_) {
1561 if (transceiver->sender() == sender) {
1562 return transceiver;
1563 }
1564 }
1565 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001566}
1567
Steve Anton9158ef62017-11-27 13:01:52 -08001568RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1569PeerConnection::AddTransceiver(
1570 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1571 return AddTransceiver(track, RtpTransceiverInit());
1572}
1573
1574RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1575PeerConnection::AddTransceiver(
1576 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1577 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001578 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001579 RTC_CHECK(IsUnifiedPlan())
1580 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001581 if (!track) {
1582 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1583 }
1584 cricket::MediaType media_type;
1585 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1586 media_type = cricket::MEDIA_TYPE_AUDIO;
1587 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1588 media_type = cricket::MEDIA_TYPE_VIDEO;
1589 } else {
1590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1591 "Track kind is not audio or video");
1592 }
1593 return AddTransceiver(media_type, track, init);
1594}
1595
1596RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1597PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1598 return AddTransceiver(media_type, RtpTransceiverInit());
1599}
1600
1601RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1602PeerConnection::AddTransceiver(cricket::MediaType media_type,
1603 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001604 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001605 RTC_CHECK(IsUnifiedPlan())
1606 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001607 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1608 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1609 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1610 "media type is not audio or video");
1611 }
1612 return AddTransceiver(media_type, nullptr, init);
1613}
1614
1615RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1616PeerConnection::AddTransceiver(
1617 cricket::MediaType media_type,
1618 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001619 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001620 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001621 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1622 media_type == cricket::MEDIA_TYPE_VIDEO));
1623 if (track) {
1624 RTC_DCHECK_EQ(media_type,
1625 (track->kind() == MediaStreamTrackInterface::kAudioKind
1626 ? cricket::MEDIA_TYPE_AUDIO
1627 : cricket::MEDIA_TYPE_VIDEO));
1628 }
1629
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001630 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1631 init.send_encodings.size(), 0, 7, 8);
1632
Amit Hilbuchaa584152019-02-06 17:09:52 -08001633 size_t num_rids = absl::c_count_if(init.send_encodings,
1634 [](const RtpEncodingParameters& encoding) {
1635 return !encoding.rid.empty();
1636 });
1637 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001638 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001639 RTCErrorType::INVALID_PARAMETER,
1640 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001641 }
1642
Amit Hilbuchf4770402019-04-08 14:11:57 -07001643 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1644 [](const RtpEncodingParameters& encoding) {
1645 return !IsLegalRsidName(encoding.rid);
1646 })) {
1647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1648 "Invalid RID value provided.");
1649 }
1650
Amit Hilbuchaa584152019-02-06 17:09:52 -08001651 if (absl::c_any_of(init.send_encodings,
1652 [](const RtpEncodingParameters& encoding) {
1653 return encoding.ssrc.has_value();
1654 })) {
1655 LOG_AND_RETURN_ERROR(
1656 RTCErrorType::UNSUPPORTED_PARAMETER,
1657 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001658 }
1659
1660 RtpParameters parameters;
1661 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001662
1663 // Encodings are dropped from the tail if too many are provided.
1664 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1665 parameters.encodings.erase(
1666 parameters.encodings.begin() + kMaxSimulcastStreams,
1667 parameters.encodings.end());
1668 }
1669
1670 // Single RID should be removed.
1671 if (parameters.encodings.size() == 1 &&
1672 !parameters.encodings[0].rid.empty()) {
1673 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1674 parameters.encodings[0].rid.clear();
1675 }
1676
1677 // If RIDs were not provided, they are generated for simulcast scenario.
1678 if (parameters.encodings.size() > 1 && num_rids == 0) {
1679 rtc::UniqueStringGenerator rid_generator;
1680 for (RtpEncodingParameters& encoding : parameters.encodings) {
1681 encoding.rid = rid_generator();
1682 }
1683 }
1684
Florent Castelli892acf02018-10-01 22:47:20 +02001685 if (UnimplementedRtpParameterHasValue(parameters)) {
1686 LOG_AND_RETURN_ERROR(
1687 RTCErrorType::UNSUPPORTED_PARAMETER,
1688 "Attempted to set an unimplemented parameter of RtpParameters.");
1689 }
Steve Anton9158ef62017-11-27 13:01:52 -08001690
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001691 auto result = cricket::CheckRtpParametersValues(parameters);
1692 if (!result.ok()) {
1693 LOG_AND_RETURN_ERROR(result.type(), result.message());
1694 }
1695
Steve Anton3d954a62018-04-02 11:27:23 -07001696 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1697 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001698 // Set the sender ID equal to the track ID if the track is specified unless
1699 // that sender ID is already in use.
1700 std::string sender_id =
1701 (track && !FindSenderById(track->id()) ? track->id()
1702 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001703 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001704 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001705 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1706 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1707 transceiver->internal()->set_direction(init.direction);
1708
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001709 if (update_negotiation_needed) {
1710 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001711 }
Steve Antonf9381f02017-12-14 10:23:57 -08001712
1713 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1714}
1715
Steve Anton02ee47c2018-01-10 16:26:06 -08001716rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1717PeerConnection::CreateSender(
1718 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001719 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001720 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001721 const std::vector<std::string>& stream_ids,
1722 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001723 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001724 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001725 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1726 RTC_DCHECK(!track ||
1727 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1728 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1729 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001730 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001731 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001732 } else {
1733 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1734 RTC_DCHECK(!track ||
1735 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1736 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001737 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001738 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001740 bool set_track_succeeded = sender->SetTrack(track);
1741 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001742 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001743 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001744 return sender;
1745}
1746
1747rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1748PeerConnection::CreateReceiver(cricket::MediaType media_type,
1749 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001750 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1751 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001752 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001753 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001754 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1755 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001756 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001757 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001758 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001759 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001760 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1761 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001762 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001763 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001764 return receiver;
1765}
1766
1767rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1768PeerConnection::CreateAndAddTransceiver(
1769 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1770 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1771 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001772 // Ensure that the new sender does not have an ID that is already in use by
1773 // another sender.
1774 // Allow receiver IDs to conflict since those come from remote SDP (which
1775 // could be invalid, but should not cause a crash).
1776 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001777 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001778 signaling_thread(),
1779 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001780 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001781 transceiver->internal()->SignalNegotiationNeeded.connect(
1782 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001783 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001784}
1785
Steve Anton52d86772018-02-20 15:48:12 -08001786void PeerConnection::OnNegotiationNeeded() {
1787 RTC_DCHECK_RUN_ON(signaling_thread());
1788 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001789 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001790}
1791
deadbeeffac06552015-11-25 11:26:01 -08001792rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001793 const std::string& kind,
1794 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001795 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001796 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1797 "Plan SdpSemantics. Please use AddTransceiver "
1798 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001799 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001800 if (IsClosed()) {
1801 return nullptr;
1802 }
Steve Anton4171afb2017-11-20 10:20:22 -08001803
Seth Hampson5b4f0752018-04-02 16:31:36 -07001804 // Internally we need to have one stream with Plan B semantics, so we
1805 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001806 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001807 if (stream_id.empty()) {
1808 stream_ids.push_back(rtc::CreateRandomUuid());
1809 RTC_LOG(LS_INFO)
1810 << "No stream_id specified for sender. Generated stream ID: "
1811 << stream_ids[0];
1812 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001813 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001814 }
1815
Steve Anton4171afb2017-11-20 10:20:22 -08001816 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001817 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001818 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001819 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001820 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001821 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001822 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001823 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001824 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001825 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001826 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001827 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001828 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001829 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001830 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001831 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001832 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001833 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001834 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001835 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001836 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001837
deadbeefe1f9d832016-01-14 15:35:42 -08001838 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001839}
1840
deadbeef70ab1a12015-09-28 16:53:55 -07001841std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1842 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001843 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001844 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001845 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001846 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001847 }
1848 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001849}
1850
Steve Anton4171afb2017-11-20 10:20:22 -08001851std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1852PeerConnection::GetSendersInternal() const {
1853 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1854 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001855 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001856 auto senders = transceiver->internal()->senders();
1857 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1858 }
1859 return all_senders;
1860}
1861
deadbeef70ab1a12015-09-28 16:53:55 -07001862std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1863PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001864 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001865 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001866 for (const auto& receiver : GetReceiversInternal()) {
1867 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001868 }
1869 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001870}
1871
Steve Anton4171afb2017-11-20 10:20:22 -08001872std::vector<
1873 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1874PeerConnection::GetReceiversInternal() const {
1875 std::vector<
1876 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1877 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001878 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001879 auto receivers = transceiver->internal()->receivers();
1880 all_receivers.insert(all_receivers.end(), receivers.begin(),
1881 receivers.end());
1882 }
1883 return all_receivers;
1884}
1885
Steve Anton9158ef62017-11-27 13:01:52 -08001886std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1887PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001888 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001889 RTC_CHECK(IsUnifiedPlan())
1890 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001891 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001892 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001893 all_transceivers.push_back(transceiver);
1894 }
1895 return all_transceivers;
1896}
1897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001899 MediaStreamTrackInterface* track,
1900 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001901 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001902 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001903 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001904 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 return false;
1906 }
1907
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001908 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001909 // The StatsCollector is used to tell if a track is valid because it may
1910 // remember tracks that the PeerConnection previously removed.
1911 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001912 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1913 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001914 return false;
1915 }
Steve Antonad182762018-09-05 20:22:40 +00001916 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1917 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return true;
1919}
1920
hbos74e1a4f2016-09-15 23:33:01 -07001921void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001922 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001923 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001924 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001925 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001926 stats_collector_->GetStatsReport(callback);
1927}
1928
Henrik Boström1df1bf82018-03-20 13:24:20 +01001929void PeerConnection::GetStats(
1930 rtc::scoped_refptr<RtpSenderInterface> selector,
1931 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1932 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001933 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001934 RTC_DCHECK(callback);
1935 RTC_DCHECK(stats_collector_);
1936 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1937 if (selector) {
1938 for (const auto& proxy_transceiver : transceivers_) {
1939 for (const auto& proxy_sender :
1940 proxy_transceiver->internal()->senders()) {
1941 if (proxy_sender == selector) {
1942 internal_sender = proxy_sender->internal();
1943 break;
1944 }
1945 }
1946 if (internal_sender)
1947 break;
1948 }
1949 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001950 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001951 // belong to the PeerConnection (in Plan B, senders can be removed from the
1952 // PeerConnection). This means that "all the stats objects representing the
1953 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1954 // produces an empty stats report.
1955 stats_collector_->GetStatsReport(internal_sender, callback);
1956}
1957
1958void PeerConnection::GetStats(
1959 rtc::scoped_refptr<RtpReceiverInterface> selector,
1960 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1961 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001962 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001963 RTC_DCHECK(callback);
1964 RTC_DCHECK(stats_collector_);
1965 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1966 if (selector) {
1967 for (const auto& proxy_transceiver : transceivers_) {
1968 for (const auto& proxy_receiver :
1969 proxy_transceiver->internal()->receivers()) {
1970 if (proxy_receiver == selector) {
1971 internal_receiver = proxy_receiver->internal();
1972 break;
1973 }
1974 }
1975 if (internal_receiver)
1976 break;
1977 }
1978 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001979 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001980 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1981 // the PeerConnection). This means that "all the stats objects representing
1982 // the selector" is an empty set. Invoking GetStatsReport() with a null
1983 // selector produces an empty stats report.
1984 stats_collector_->GetStatsReport(internal_receiver, callback);
1985}
1986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001988 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989 return signaling_state_;
1990}
1991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992PeerConnectionInterface::IceConnectionState
1993PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001994 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 return ice_connection_state_;
1996}
1997
Alex Loiko9289eda2018-11-23 16:18:59 +00001998PeerConnectionInterface::IceConnectionState
1999PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002000 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002001 return standardized_ice_connection_state_;
2002}
2003
Jonas Olsson635474e2018-10-18 15:58:17 +02002004PeerConnectionInterface::PeerConnectionState
2005PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002006 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002007 return connection_state_;
2008}
2009
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010PeerConnectionInterface::IceGatheringState
2011PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002012 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 return ice_gathering_state_;
2014}
2015
Yves Gerey665174f2018-06-19 15:03:05 +02002016rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017 const std::string& label,
2018 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002019 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002020 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002021
deadbeefab9b2d12015-10-14 11:33:11 -07002022 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002023
kwibergd1fe2812016-04-27 06:47:29 -07002024 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002025 if (config) {
2026 internal_config.reset(new InternalDataChannelInit(*config));
2027 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002028 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002029 InternalCreateDataChannel(label, internal_config.get()));
2030 if (!channel.get()) {
2031 return nullptr;
2032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002034 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2035 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002036 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002037 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002038 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002039 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040 return DataChannelProxy::Create(signaling_thread(), channel.get());
2041}
2042
Henrik Boström79b69802019-07-18 11:16:56 +02002043void PeerConnection::RestartIce() {
2044 RTC_DCHECK_RUN_ON(signaling_thread());
2045 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2046 current_local_description_.get(), pending_local_description_.get());
2047 UpdateNegotiationNeeded();
2048}
2049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002051 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002052 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002053 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002054
nisse7ce109a2017-01-31 00:57:56 -08002055 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002056 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002057 return;
2058 }
deadbeefab9b2d12015-10-14 11:33:11 -07002059
Steve Anton8d3444d2017-10-20 15:30:51 -07002060 if (IsClosed()) {
2061 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002062 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002063 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002064 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002065 return;
2066 }
2067
Steve Anton25ca0ac2019-06-25 10:40:48 -07002068 // If a session error has occurred the PeerConnection is in a possibly
2069 // inconsistent state so fail right away.
2070 if (session_error() != SessionError::kNone) {
2071 std::string error_message = GetSessionErrorMsg();
2072 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2073 PostCreateSessionDescriptionFailure(
2074 observer,
2075 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2076 return;
2077 }
2078
zhihuang1c378ed2017-08-17 14:10:50 -07002079 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002080 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002081 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002082 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002083 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002084 return;
2085 }
2086
Steve Anton22da89f2018-01-25 13:58:07 -08002087 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2088 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2089 if (IsUnifiedPlan()) {
2090 RTCError error = HandleLegacyOfferOptions(options);
2091 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002092 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002093 return;
2094 }
2095 }
2096
zhihuang1c378ed2017-08-17 14:10:50 -07002097 cricket::MediaSessionOptions session_options;
2098 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002099 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100}
2101
Steve Anton22da89f2018-01-25 13:58:07 -08002102RTCError PeerConnection::HandleLegacyOfferOptions(
2103 const RTCOfferAnswerOptions& options) {
2104 RTC_DCHECK(IsUnifiedPlan());
2105
2106 if (options.offer_to_receive_audio == 0) {
2107 RemoveRecvDirectionFromReceivingTransceiversOfType(
2108 cricket::MEDIA_TYPE_AUDIO);
2109 } else if (options.offer_to_receive_audio == 1) {
2110 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2111 } else if (options.offer_to_receive_audio > 1) {
2112 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2113 "offer_to_receive_audio > 1 is not supported.");
2114 }
2115
2116 if (options.offer_to_receive_video == 0) {
2117 RemoveRecvDirectionFromReceivingTransceiversOfType(
2118 cricket::MEDIA_TYPE_VIDEO);
2119 } else if (options.offer_to_receive_video == 1) {
2120 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2121 } else if (options.offer_to_receive_video > 1) {
2122 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2123 "offer_to_receive_video > 1 is not supported.");
2124 }
2125
2126 return RTCError::OK();
2127}
2128
2129void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2130 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002131 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002132 RtpTransceiverDirection new_direction =
2133 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2134 if (new_direction != transceiver->direction()) {
2135 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2136 << " transceiver (MID="
2137 << transceiver->mid().value_or("<not set>") << ") from "
2138 << RtpTransceiverDirectionToString(
2139 transceiver->direction())
2140 << " to "
2141 << RtpTransceiverDirectionToString(new_direction)
2142 << " since CreateOffer specified offer_to_receive=0";
2143 transceiver->internal()->set_direction(new_direction);
2144 }
Steve Anton22da89f2018-01-25 13:58:07 -08002145 }
2146}
2147
2148void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2149 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002150 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002151 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002152 RTC_LOG(LS_INFO)
2153 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2154 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002155 RtpTransceiverInit init;
2156 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002157 AddTransceiver(media_type, nullptr, init,
2158 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002159 }
2160}
2161
2162std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2163PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2164 std::vector<
2165 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2166 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002167 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002168 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002169 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2170 receiving_transceivers.push_back(transceiver);
2171 }
2172 }
2173 return receiving_transceivers;
2174}
2175
htaa2a49d92016-03-04 02:51:39 -08002176void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2177 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002178 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002179 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002180 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002181 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002182 return;
2183 }
2184
Steve Anton25ca0ac2019-06-25 10:40:48 -07002185 // If a session error has occurred the PeerConnection is in a possibly
2186 // inconsistent state so fail right away.
2187 if (session_error() != SessionError::kNone) {
2188 std::string error_message = GetSessionErrorMsg();
2189 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2190 PostCreateSessionDescriptionFailure(
2191 observer,
2192 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2193 return;
2194 }
2195
Steve Antondffead82018-02-06 10:31:29 -08002196 if (!(signaling_state_ == kHaveRemoteOffer ||
2197 signaling_state_ == kHaveLocalPrAnswer)) {
2198 std::string error =
2199 "PeerConnection cannot create an answer in a state other than "
2200 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002201 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002202 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002203 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002204 return;
2205 }
2206
Steve Antondffead82018-02-06 10:31:29 -08002207 // The remote description should be set if we're in the right state.
2208 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002209
Steve Anton22da89f2018-01-25 13:58:07 -08002210 if (IsUnifiedPlan()) {
2211 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2212 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2213 "supported with Unified Plan semantics. Use the "
2214 "RtpTransceiver API instead.";
2215 }
2216 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2217 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2218 "supported with Unified Plan semantics. Use the "
2219 "RtpTransceiver API instead.";
2220 }
2221 }
2222
htaa2a49d92016-03-04 02:51:39 -08002223 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002224 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002225
Steve Antond25da372017-11-06 14:50:29 -08002226 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227}
2228
2229void PeerConnection::SetLocalDescription(
2230 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002231 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002232 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002233 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002234
Steve Anton80dd7b52018-02-16 17:08:42 -08002235 // The SetLocalDescription contract is that we take ownership of the session
2236 // description regardless of the outcome, so wrap it in a unique_ptr right
2237 // away. Ideally, SetLocalDescription's signature will be changed to take the
2238 // description as a unique_ptr argument to formalize this agreement.
2239 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2240
nisse7ce109a2017-01-31 00:57:56 -08002241 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002242 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 return;
2244 }
Steve Anton8a006912017-12-04 15:25:56 -08002245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002247 PostSetSessionDescriptionFailure(
2248 observer,
2249 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 return;
2251 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002252
Steve Anton80dd7b52018-02-16 17:08:42 -08002253 // If a session error has occurred the PeerConnection is in a possibly
2254 // inconsistent state so fail right away.
2255 if (session_error() != SessionError::kNone) {
2256 std::string error_message = GetSessionErrorMsg();
2257 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002258 PostSetSessionDescriptionFailure(
2259 observer,
2260 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002261 return;
2262 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002263
Eldar Rello5ab79e62019-10-09 18:29:44 +03002264 // For SLD we support only explicit rollback.
2265 if (desc->GetType() == SdpType::kRollback) {
2266 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002267 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002268 if (error.ok()) {
2269 PostSetSessionDescriptionSuccess(observer);
2270 } else {
2271 PostSetSessionDescriptionFailure(observer, std::move(error));
2272 }
2273 } else {
2274 PostSetSessionDescriptionFailure(
2275 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2276 "Rollback not supported in Plan B"));
2277 }
2278 return;
2279 }
2280
Steve Anton80dd7b52018-02-16 17:08:42 -08002281 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2282 if (!error.ok()) {
2283 std::string error_message = GetSetDescriptionErrorMessage(
2284 cricket::CS_LOCAL, desc->GetType(), error);
2285 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002286 PostSetSessionDescriptionFailure(
2287 observer,
2288 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002289 return;
2290 }
2291
2292 // Grab the description type before moving ownership to ApplyLocalDescription,
2293 // which may destroy it before returning.
2294 const SdpType type = desc->GetType();
2295
2296 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002297 // |desc| may be destroyed at this point.
2298
2299 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002300 // If ApplyLocalDescription fails, the PeerConnection could be in an
2301 // inconsistent state, so act conservatively here and set the session error
2302 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2303 SetSessionError(SessionError::kContent, error.message());
2304 std::string error_message =
2305 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2306 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002307 PostSetSessionDescriptionFailure(
2308 observer,
2309 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002310 return;
2311 }
Steve Anton8a006912017-12-04 15:25:56 -08002312 RTC_DCHECK(local_description());
2313
2314 PostSetSessionDescriptionSuccess(observer);
2315
Steve Antonad182762018-09-05 20:22:40 +00002316 // MaybeStartGathering needs to be called after posting
2317 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2318 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002319 transport_controller_->MaybeStartGathering();
2320
Steve Antona3a92c22017-12-07 10:27:41 -08002321 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002322 // TODO(deadbeef): We already had to hop to the network thread for
2323 // MaybeStartGathering...
2324 network_thread()->Invoke<void>(
2325 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2326 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002327 // Make UMA notes about what was agreed to.
2328 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002329 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002330
2331 if (IsUnifiedPlan()) {
2332 bool was_negotiation_needed = is_negotiation_needed_;
2333 UpdateNegotiationNeeded();
2334 if (signaling_state() == kStable && was_negotiation_needed &&
2335 is_negotiation_needed_) {
2336 Observer()->OnRenegotiationNeeded();
2337 }
2338 }
2339
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002340 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002341}
2342
2343RTCError PeerConnection::ApplyLocalDescription(
2344 std::unique_ptr<SessionDescriptionInterface> desc) {
2345 RTC_DCHECK_RUN_ON(signaling_thread());
2346 RTC_DCHECK(desc);
2347
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002348 // Update stats here so that we have the most recent stats for tracks and
2349 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002350 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002351
Steve Antondcc3c022017-12-22 16:02:54 -08002352 // Take a reference to the old local description since it's used below to
2353 // compare against the new local description. When setting the new local
2354 // description, grab ownership of the replaced session description in case it
2355 // is the same as |old_local_description|, to keep it alive for the duration
2356 // of the method.
2357 const SessionDescriptionInterface* old_local_description =
2358 local_description();
2359 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002360 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002361 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002362 replaced_local_description = pending_local_description_
2363 ? std::move(pending_local_description_)
2364 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002365 current_local_description_ = std::move(desc);
2366 pending_local_description_ = nullptr;
2367 current_remote_description_ = std::move(pending_remote_description_);
2368 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002369 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002370 pending_local_description_ = std::move(desc);
2371 }
2372 // The session description to apply now must be accessed by
2373 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002374 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002375
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002376 // Report statistics about any use of simulcast.
2377 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2378 *local_description()->description());
2379
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002380 if (!is_caller_) {
2381 if (remote_description()) {
2382 // Remote description was applied first, so this PC is the callee.
2383 is_caller_ = false;
2384 } else {
2385 // Local description is applied first, so this PC is the caller.
2386 is_caller_ = true;
2387 }
2388 }
2389
Zhi Huange830e682018-03-30 10:48:35 -07002390 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2391 if (!error.ok()) {
2392 return error;
2393 }
2394
Steve Antondcc3c022017-12-22 16:02:54 -08002395 if (IsUnifiedPlan()) {
2396 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002397 cricket::CS_LOCAL, *local_description(), old_local_description,
2398 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002399 if (!error.ok()) {
2400 return error;
2401 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002402 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2403 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002404 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002405 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2406 // Note that code paths that don't set MID won't be able to use
2407 // information about DTLS transports.
2408 if (transceiver->mid()) {
2409 auto dtls_transport =
2410 LookupDtlsTransportByMidInternal(*transceiver->mid());
2411 transceiver->internal()->sender_internal()->set_transport(
2412 dtls_transport);
2413 transceiver->internal()->receiver_internal()->set_transport(
2414 dtls_transport);
2415 }
2416
Steve Antondcc3c022017-12-22 16:02:54 -08002417 const ContentInfo* content =
2418 FindMediaSectionForTransceiver(transceiver, local_description());
2419 if (!content) {
2420 continue;
2421 }
2422 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002423 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2424 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002425 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002426 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2427 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2428 // "recvonly", process the removal of a remote track for the media
2429 // description, given transceiver, removeList, and muteTracks.
2430 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2431 (transceiver->internal()->fired_direction() &&
2432 RtpTransceiverDirectionHasRecv(
2433 *transceiver->internal()->fired_direction()))) {
2434 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2435 &removed_streams);
2436 }
2437 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2438 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002439 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002440 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002441 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002442 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002443 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002444 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002445 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002446 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002447 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002448 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002449 }
2450 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002451 // Media channels will be created only when offer is set. These may use new
2452 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002453 if (type == SdpType::kOffer) {
2454 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2455 // description is applied. Restore back to old description.
2456 RTCError error = CreateChannels(*local_description()->description());
2457 if (!error.ok()) {
2458 return error;
2459 }
2460 }
Steve Antondcc3c022017-12-22 16:02:54 -08002461 // Remove unused channels if MediaContentDescription is rejected.
2462 RemoveUnusedChannels(local_description()->description());
2463 }
Steve Anton8a006912017-12-04 15:25:56 -08002464
Zhi Huange830e682018-03-30 10:48:35 -07002465 error = UpdateSessionState(type, cricket::CS_LOCAL,
2466 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002467 if (!error.ok()) {
2468 return error;
2469 }
Steve Antondcc3c022017-12-22 16:02:54 -08002470
Steve Anton8a006912017-12-04 15:25:56 -08002471 if (remote_description()) {
2472 // Now that we have a local description, we can push down remote candidates.
2473 UseCandidatesInSessionDescription(remote_description());
2474 }
2475
2476 pending_ice_restarts_.clear();
2477 if (session_error() != SessionError::kNone) {
2478 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2479 }
2480
deadbeefab9b2d12015-10-14 11:33:11 -07002481 // If setting the description decided our SSL role, allocate any necessary
2482 // SCTP sids.
2483 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002484 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002485 AllocateSctpSids(role);
2486 }
2487
Steve Antond3679212018-01-17 17:41:02 -08002488 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002489 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002490 const ContentInfo* content =
2491 FindMediaSectionForTransceiver(transceiver, local_description());
2492 if (!content) {
2493 continue;
2494 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002495 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2496 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002497 // 0 is a special value meaning "this sender has no associated send
2498 // stream". Need to call this so the sender won't attempt to configure
2499 // a no longer existing stream and run into DCHECKs in the lower
2500 // layers.
2501 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002502 } else {
2503 // Get the StreamParams from the channel which could generate SSRCs.
2504 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002505 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002506 streams[0].stream_ids());
2507 transceiver->internal()->sender_internal()->SetSsrc(
2508 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002509 }
2510 }
2511 } else {
2512 // Plan B semantics.
2513
Steve Antondcc3c022017-12-22 16:02:54 -08002514 // Update state and SSRC of local MediaStreams and DataChannels based on the
2515 // local session description.
2516 const cricket::ContentInfo* audio_content =
2517 GetFirstAudioContent(local_description()->description());
2518 if (audio_content) {
2519 if (audio_content->rejected) {
2520 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2521 } else {
2522 const cricket::AudioContentDescription* audio_desc =
2523 audio_content->media_description()->as_audio();
2524 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2525 }
deadbeeffaac4972015-11-12 15:33:07 -08002526 }
deadbeefab9b2d12015-10-14 11:33:11 -07002527
Steve Antondcc3c022017-12-22 16:02:54 -08002528 const cricket::ContentInfo* video_content =
2529 GetFirstVideoContent(local_description()->description());
2530 if (video_content) {
2531 if (video_content->rejected) {
2532 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2533 } else {
2534 const cricket::VideoContentDescription* video_desc =
2535 video_content->media_description()->as_video();
2536 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2537 }
deadbeeffaac4972015-11-12 15:33:07 -08002538 }
deadbeefab9b2d12015-10-14 11:33:11 -07002539 }
2540
2541 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002542 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002543 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002544 const cricket::RtpDataContentDescription* rtp_data_desc =
2545 data_content->media_description()->as_rtp_data();
2546 // rtp_data_desc will be null if this is an SCTP description.
2547 if (rtp_data_desc) {
2548 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002549 }
2550 }
2551
Henrik Boström79b69802019-07-18 11:16:56 +02002552 if (type == SdpType::kAnswer &&
2553 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2554 *current_local_description_)) {
2555 local_ice_credentials_to_replace_->ClearIceCredentials();
2556 }
2557
Steve Anton8a006912017-12-04 15:25:56 -08002558 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559}
2560
Steve Anton06817cd2018-12-18 15:55:30 -08002561// The SDP parser used to populate these values by default for the 'content
2562// name' if an a=mid line was absent.
2563static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2564 switch (media_type) {
2565 case cricket::MEDIA_TYPE_AUDIO:
2566 return cricket::CN_AUDIO;
2567 case cricket::MEDIA_TYPE_VIDEO:
2568 return cricket::CN_VIDEO;
2569 case cricket::MEDIA_TYPE_DATA:
2570 return cricket::CN_DATA;
2571 }
2572 RTC_NOTREACHED();
2573 return "";
2574}
2575
2576void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002577 cricket::SessionDescription* new_remote_description) {
2578 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002579 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002580 const cricket::ContentInfos& local_contents =
2581 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002582 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002583 const cricket::ContentInfos& remote_contents =
2584 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002585 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002586 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2587 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002588 if (!content.name.empty()) {
2589 continue;
2590 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002591 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002592 absl::string_view source_explanation;
2593 if (IsUnifiedPlan()) {
2594 if (i < local_contents.size()) {
2595 new_mid = local_contents[i].name;
2596 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002597 } else if (i < remote_contents.size()) {
2598 new_mid = remote_contents[i].name;
2599 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002600 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002601 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002602 source_explanation = "generated just now";
2603 }
2604 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002605 new_mid = std::string(
2606 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002607 source_explanation = "to match pre-existing behavior";
2608 }
Steve Antond7180cc2019-02-07 10:44:53 -08002609 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002610 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002611 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002612 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2613 << " is missing an a=mid line. Filling in the value '"
2614 << new_mid << "' " << source_explanation << ".";
2615 }
2616}
2617
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002619 SetSessionDescriptionObserver* observer,
2620 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002621 SetRemoteDescription(
2622 std::unique_ptr<SessionDescriptionInterface>(desc),
2623 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2624 new SetRemoteDescriptionObserverAdapter(this, observer)));
2625}
2626
2627void PeerConnection::SetRemoteDescription(
2628 std::unique_ptr<SessionDescriptionInterface> desc,
2629 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002630 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002631 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002632
nisse7ce109a2017-01-31 00:57:56 -08002633 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002635 return;
2636 }
Steve Anton8a006912017-12-04 15:25:56 -08002637
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002639 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002640 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641 return;
2642 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002643
Steve Anton80dd7b52018-02-16 17:08:42 -08002644 // If a session error has occurred the PeerConnection is in a possibly
2645 // inconsistent state so fail right away.
2646 if (session_error() != SessionError::kNone) {
2647 std::string error_message = GetSessionErrorMsg();
2648 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2649 observer->OnSetRemoteDescriptionComplete(
2650 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2651 return;
2652 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03002653 if (IsUnifiedPlan()) {
2654 if (configuration_.enable_implicit_rollback) {
2655 if (desc->GetType() == SdpType::kOffer &&
2656 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002657 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002658 }
2659 }
2660 // Explicit rollback.
2661 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002662 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03002663 return;
2664 }
2665 } else if (desc->GetType() == SdpType::kRollback) {
2666 observer->OnSetRemoteDescriptionComplete(
2667 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2668 "Rollback not supported in Plan B"));
2669 return;
2670 }
Steve Antonba42e992018-04-09 14:10:01 -07002671 if (desc->GetType() == SdpType::kOffer) {
2672 // Report to UMA the format of the received offer.
2673 ReportSdpFormatReceived(*desc);
2674 }
2675
Steve Anton06817cd2018-12-18 15:55:30 -08002676 // Handle remote descriptions missing a=mid lines for interop with legacy end
2677 // points.
2678 FillInMissingRemoteMids(desc->description());
2679
Steve Anton80dd7b52018-02-16 17:08:42 -08002680 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002681 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002682 std::string error_message = GetSetDescriptionErrorMessage(
2683 cricket::CS_REMOTE, desc->GetType(), error);
2684 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002685 observer->OnSetRemoteDescriptionComplete(
2686 RTCError(error.type(), std::move(error_message)));
2687 return;
2688 }
Steve Anton71439a62018-02-15 11:53:06 -08002689
Steve Anton80dd7b52018-02-16 17:08:42 -08002690 // Grab the description type before moving ownership to
2691 // ApplyRemoteDescription, which may destroy it before returning.
2692 const SdpType type = desc->GetType();
2693
2694 error = ApplyRemoteDescription(std::move(desc));
2695 // |desc| may be destroyed at this point.
2696
2697 if (!error.ok()) {
2698 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2699 // inconsistent state, so act conservatively here and set the session error
2700 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2701 SetSessionError(SessionError::kContent, error.message());
2702 std::string error_message =
2703 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2704 RTC_LOG(LS_ERROR) << error_message;
2705 observer->OnSetRemoteDescriptionComplete(
2706 RTCError(error.type(), std::move(error_message)));
2707 return;
2708 }
2709 RTC_DCHECK(remote_description());
2710
2711 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002712 // TODO(deadbeef): We already had to hop to the network thread for
2713 // MaybeStartGathering...
2714 network_thread()->Invoke<void>(
2715 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2716 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002717 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002718 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002719 }
2720
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002721 if (IsUnifiedPlan()) {
2722 bool was_negotiation_needed = is_negotiation_needed_;
2723 UpdateNegotiationNeeded();
2724 if (signaling_state() == kStable && was_negotiation_needed &&
2725 is_negotiation_needed_) {
2726 Observer()->OnRenegotiationNeeded();
2727 }
2728 }
2729
Steve Anton8a006912017-12-04 15:25:56 -08002730 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002731 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002732}
2733
2734RTCError PeerConnection::ApplyRemoteDescription(
2735 std::unique_ptr<SessionDescriptionInterface> desc) {
2736 RTC_DCHECK_RUN_ON(signaling_thread());
2737 RTC_DCHECK(desc);
2738
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739 // Update stats here so that we have the most recent stats for tracks and
2740 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002741 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002742
Steve Antondcc3c022017-12-22 16:02:54 -08002743 // Take a reference to the old remote description since it's used below to
2744 // compare against the new remote description. When setting the new remote
2745 // description, grab ownership of the replaced session description in case it
2746 // is the same as |old_remote_description|, to keep it alive for the duration
2747 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002748 const SessionDescriptionInterface* old_remote_description =
2749 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002750 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002751 SdpType type = desc->GetType();
2752 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002753 replaced_remote_description = pending_remote_description_
2754 ? std::move(pending_remote_description_)
2755 : std::move(current_remote_description_);
2756 current_remote_description_ = std::move(desc);
2757 pending_remote_description_ = nullptr;
2758 current_local_description_ = std::move(pending_local_description_);
2759 } else {
2760 replaced_remote_description = std::move(pending_remote_description_);
2761 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 }
Steve Anton8a006912017-12-04 15:25:56 -08002763 // The session description to apply now must be accessed by
2764 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002765 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002767 // Report statistics about any use of simulcast.
2768 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2769 *remote_description()->description());
2770
Zhi Huange830e682018-03-30 10:48:35 -07002771 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2772 if (!error.ok()) {
2773 return error;
2774 }
Steve Anton8a006912017-12-04 15:25:56 -08002775 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002776 if (IsUnifiedPlan()) {
2777 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002778 cricket::CS_REMOTE, *remote_description(), local_description(),
2779 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002780 if (!error.ok()) {
2781 return error;
2782 }
Steve Antondcc3c022017-12-22 16:02:54 -08002783 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002784 // Media channels will be created only when offer is set. These may use new
2785 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002786 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002787 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002788 // description is applied. Restore back to old description.
2789 RTCError error = CreateChannels(*remote_description()->description());
2790 if (!error.ok()) {
2791 return error;
2792 }
2793 }
Steve Antondcc3c022017-12-22 16:02:54 -08002794 // Remove unused channels if MediaContentDescription is rejected.
2795 RemoveUnusedChannels(remote_description()->description());
2796 }
Steve Anton8a006912017-12-04 15:25:56 -08002797
Zhi Huange830e682018-03-30 10:48:35 -07002798 // NOTE: Candidates allocation will be initiated only when
2799 // SetLocalDescription is called.
2800 error = UpdateSessionState(type, cricket::CS_REMOTE,
2801 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002802 if (!error.ok()) {
2803 return error;
2804 }
2805
2806 if (local_description() &&
2807 !UseCandidatesInSessionDescription(remote_description())) {
2808 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2809 }
2810
2811 if (old_remote_description) {
2812 for (const cricket::ContentInfo& content :
2813 old_remote_description->description()->contents()) {
2814 // Check if this new SessionDescription contains new ICE ufrag and
2815 // password that indicates the remote peer requests an ICE restart.
2816 // TODO(deadbeef): When we start storing both the current and pending
2817 // remote description, this should reset pending_ice_restarts and compare
2818 // against the current description.
2819 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2820 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002821 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002822 pending_ice_restarts_.insert(content.name);
2823 }
2824 } else {
2825 // We retain all received candidates only if ICE is not restarted.
2826 // When ICE is restarted, all previous candidates belong to an old
2827 // generation and should not be kept.
2828 // TODO(deadbeef): This goes against the W3C spec which says the remote
2829 // description should only contain candidates from the last set remote
2830 // description plus any candidates added since then. We should remove
2831 // this once we're sure it won't break anything.
2832 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2833 old_remote_description, content.name, mutable_remote_description());
2834 }
2835 }
2836 }
2837
2838 if (session_error() != SessionError::kNone) {
2839 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2840 }
2841
2842 // Set the the ICE connection state to connecting since the connection may
2843 // become writable with peer reflexive candidates before any remote candidate
2844 // is signaled.
2845 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2846 // is to have a new signal the indicates a change in checking state from the
2847 // transport and expose a new checking() member from transport that can be
2848 // read to determine the current checking state. The existing SignalConnecting
2849 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002850 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002851 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002852 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2853 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2854 }
2855
deadbeefab9b2d12015-10-14 11:33:11 -07002856 // If setting the description decided our SSL role, allocate any necessary
2857 // SCTP sids.
2858 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002859 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002860 AllocateSctpSids(role);
2861 }
2862
Steve Antondcc3c022017-12-22 16:02:54 -08002863 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002864 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002865 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002866 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002867 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002868 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002869 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002870 const ContentInfo* content =
2871 FindMediaSectionForTransceiver(transceiver, remote_description());
2872 if (!content) {
2873 continue;
2874 }
2875 const MediaContentDescription* media_desc = content->media_description();
2876 RtpTransceiverDirection local_direction =
2877 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002878 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2879 // RTCSessionDescription: Set the associated remote streams given
2880 // transceiver.[[Receiver]], msids, addList, and removeList".
2881 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2882 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2883 std::vector<std::string> stream_ids;
2884 if (!media_desc->streams().empty()) {
2885 // The remote description has signaled the stream IDs.
2886 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002887 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002888 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2889 << " (" << GetStreamIdsString(stream_ids) << ").";
2890 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2891 stream_ids, &added_streams,
2892 &removed_streams);
2893 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2894 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2895 // and transceiver's current direction is neither sendrecv nor recvonly,
2896 // process the addition of a remote track for the media description.
2897 if (!transceiver->fired_direction() ||
2898 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2899 RTC_LOG(LS_INFO)
2900 << "Processing the addition of a remote track for MID="
2901 << content->name << ".";
2902 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002903 }
Steve Antondcc3c022017-12-22 16:02:54 -08002904 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002905 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002906 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2907 // removal of a remote track for the media description, given transceiver,
2908 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002909 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002910 (transceiver->fired_direction() &&
2911 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2912 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2913 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002914 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002915 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002916 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002917 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002918 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002919 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002920 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002921 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002922 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002923 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2924 if (transceiver->mid()) {
2925 auto dtls_transport =
2926 LookupDtlsTransportByMidInternal(*transceiver->mid());
2927 transceiver->internal()->sender_internal()->set_transport(
2928 dtls_transport);
2929 transceiver->internal()->receiver_internal()->set_transport(
2930 dtls_transport);
2931 }
Steve Antondcc3c022017-12-22 16:02:54 -08002932 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002933 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002934 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002935 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002936 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2937 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002938 transceiver->Stop();
2939 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002940 if (!content->rejected &&
2941 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002942 if (!media_desc->streams().empty() &&
2943 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07002944 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
2945 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
2946 } else {
2947 transceiver->internal()
2948 ->receiver_internal()
2949 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002950 }
Steve Antond3679212018-01-17 17:41:02 -08002951 }
Steve Antondcc3c022017-12-22 16:02:54 -08002952 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002953 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002954 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002955 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002956 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002957 observer->OnTrack(transceiver);
2958 observer->OnAddTrack(transceiver->receiver(),
2959 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002960 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002961 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002962 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002963 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002964 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002965 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002966 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002967 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002968 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002969 }
Steve Antondcc3c022017-12-22 16:02:54 -08002970 }
2971
Henrik Boströmfdb92012017-11-09 19:55:44 +01002972 const cricket::ContentInfo* audio_content =
2973 GetFirstAudioContent(remote_description()->description());
2974 const cricket::ContentInfo* video_content =
2975 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002976 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002977 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002978 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002979 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002980 const cricket::RtpDataContentDescription* rtp_data_desc =
2981 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002982
2983 // Check if the descriptions include streams, just in case the peer supports
2984 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002985 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002986 (audio_desc && !audio_desc->streams().empty()) ||
2987 (video_desc && !video_desc->streams().empty())) {
2988 remote_peer_supports_msid_ = true;
2989 }
deadbeefab9b2d12015-10-14 11:33:11 -07002990
2991 // We wait to signal new streams until we finish processing the description,
2992 // since only at that point will new streams have all their tracks.
2993 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2994
Steve Antondcc3c022017-12-22 16:02:54 -08002995 if (!IsUnifiedPlan()) {
2996 // TODO(steveanton): When removing RTP senders/receivers in response to a
2997 // rejected media section, there is some cleanup logic that expects the
2998 // voice/ video channel to still be set. But in this method the voice/video
2999 // channel would have been destroyed by the SetRemoteDescription caller
3000 // above so the cleanup that relies on them fails to run. The RemoveSenders
3001 // calls should be moved to right before the DestroyChannel calls to fix
3002 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003003
Steve Antondcc3c022017-12-22 16:02:54 -08003004 // Find all audio rtp streams and create corresponding remote AudioTracks
3005 // and MediaStreams.
3006 if (audio_content) {
3007 if (audio_content->rejected) {
3008 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3009 } else {
3010 bool default_audio_track_needed =
3011 !remote_peer_supports_msid_ &&
3012 RtpTransceiverDirectionHasSend(audio_desc->direction());
3013 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3014 default_audio_track_needed, audio_desc->type(),
3015 new_streams);
3016 }
deadbeeffaac4972015-11-12 15:33:07 -08003017 }
deadbeefab9b2d12015-10-14 11:33:11 -07003018
Steve Antondcc3c022017-12-22 16:02:54 -08003019 // Find all video rtp streams and create corresponding remote VideoTracks
3020 // and MediaStreams.
3021 if (video_content) {
3022 if (video_content->rejected) {
3023 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3024 } else {
3025 bool default_video_track_needed =
3026 !remote_peer_supports_msid_ &&
3027 RtpTransceiverDirectionHasSend(video_desc->direction());
3028 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3029 default_video_track_needed, video_desc->type(),
3030 new_streams);
3031 }
deadbeeffaac4972015-11-12 15:33:07 -08003032 }
deadbeefab9b2d12015-10-14 11:33:11 -07003033
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003034 // If this is an RTP data transport, update the DataChannels with the
3035 // information from the remote peer.
3036 if (rtp_data_desc) {
3037 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003038 }
deadbeefab9b2d12015-10-14 11:33:11 -07003039
Steve Antondcc3c022017-12-22 16:02:54 -08003040 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003041 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003042 for (size_t i = 0; i < new_streams->count(); ++i) {
3043 MediaStreamInterface* new_stream = new_streams->at(i);
3044 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003045 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003046 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3047 }
deadbeefab9b2d12015-10-14 11:33:11 -07003048
Steve Antondcc3c022017-12-22 16:02:54 -08003049 UpdateEndedRemoteMediaStreams();
3050 }
deadbeefab9b2d12015-10-14 11:33:11 -07003051
Henrik Boström79b69802019-07-18 11:16:56 +02003052 if (type == SdpType::kAnswer &&
3053 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3054 *current_local_description_)) {
3055 local_ice_credentials_to_replace_->ClearIceCredentials();
3056 }
3057
Steve Anton8a006912017-12-04 15:25:56 -08003058 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003059}
3060
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003061void PeerConnection::SetAssociatedRemoteStreams(
3062 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3063 const std::vector<std::string>& stream_ids,
3064 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3065 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3066 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3067 for (const std::string& stream_id : stream_ids) {
3068 rtc::scoped_refptr<MediaStreamInterface> stream =
3069 remote_streams_->find(stream_id);
3070 if (!stream) {
3071 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3072 MediaStream::Create(stream_id));
3073 remote_streams_->AddStream(stream);
3074 added_streams->push_back(stream);
3075 }
3076 media_streams.push_back(stream);
3077 }
3078 // Special case: "a=msid" missing, use random stream ID.
3079 if (media_streams.empty() &&
3080 !(remote_description()->description()->msid_signaling() &
3081 cricket::kMsidSignalingMediaSection)) {
3082 if (!missing_msid_default_stream_) {
3083 missing_msid_default_stream_ = MediaStreamProxy::Create(
3084 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3085 added_streams->push_back(missing_msid_default_stream_);
3086 }
3087 media_streams.push_back(missing_msid_default_stream_);
3088 }
3089 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3090 receiver->streams();
3091 // SetStreams() will add/remove the receiver's track to/from the streams. This
3092 // differs from the spec - the spec uses an "addList" and "removeList" to
3093 // update the stream-track relationships in a later step. We do this earlier,
3094 // changing the order of things, but the end-result is the same.
3095 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3096 // instead. https://crbug.com/webrtc/9480
3097 receiver->SetStreams(media_streams);
3098 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3099}
3100
Steve Anton0f5400a2018-07-17 14:25:36 -07003101void PeerConnection::ProcessRemovalOfRemoteTrack(
3102 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3103 transceiver,
3104 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3105 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3106 RTC_DCHECK(transceiver->mid());
3107 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3108 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003109 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003110 transceiver->internal()->receiver_internal()->streams();
3111 // This will remove the remote track from the streams.
3112 transceiver->internal()->receiver_internal()->set_stream_ids({});
3113 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003114 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3115}
3116
3117void PeerConnection::RemoveRemoteStreamsIfEmpty(
3118 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3119 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3120 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3121 // streams, see if the stream was removed by checking if this was the last
3122 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003123 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003124 if (remote_stream->GetAudioTracks().empty() &&
3125 remote_stream->GetVideoTracks().empty()) {
3126 remote_streams_->RemoveStream(remote_stream);
3127 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003128 }
3129 }
3130}
3131
Steve Antondcc3c022017-12-22 16:02:54 -08003132RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3133 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003134 const SessionDescriptionInterface& new_session,
3135 const SessionDescriptionInterface* old_local_description,
3136 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003137 RTC_DCHECK(IsUnifiedPlan());
3138
Steve Anton7464fca2018-01-19 11:10:37 -08003139 const cricket::ContentGroup* bundle_group = nullptr;
3140 if (new_session.GetType() == SdpType::kOffer) {
3141 auto bundle_group_or_error =
3142 GetEarlyBundleGroup(*new_session.description());
3143 if (!bundle_group_or_error.ok()) {
3144 return bundle_group_or_error.MoveError();
3145 }
3146 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003147 }
Steve Antondcc3c022017-12-22 16:02:54 -08003148
Steve Antondcc3c022017-12-22 16:02:54 -08003149 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003150 for (size_t i = 0; i < new_contents.size(); ++i) {
3151 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003152 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003153 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003154 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3155 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003156 const cricket::ContentInfo* old_local_content = nullptr;
3157 if (old_local_description &&
3158 i < old_local_description->description()->contents().size()) {
3159 old_local_content =
3160 &old_local_description->description()->contents()[i];
3161 }
3162 const cricket::ContentInfo* old_remote_content = nullptr;
3163 if (old_remote_description &&
3164 i < old_remote_description->description()->contents().size()) {
3165 old_remote_content =
3166 &old_remote_description->description()->contents()[i];
3167 }
Steve Antondcc3c022017-12-22 16:02:54 -08003168 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003169 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3170 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003171 if (!transceiver_or_error.ok()) {
3172 return transceiver_or_error.MoveError();
3173 }
3174 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003175 RTCError error =
3176 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3177 if (!error.ok()) {
3178 return error;
3179 }
3180 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003181 if (GetDataMid() && new_content.name != *GetDataMid()) {
3182 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003183 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3184 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003185 continue;
3186 }
3187 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3188 if (!error.ok()) {
3189 return error;
3190 }
Steve Antondcc3c022017-12-22 16:02:54 -08003191 } else {
3192 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3193 "Unknown section type.");
3194 }
3195 }
3196
3197 return RTCError::OK();
3198}
3199
3200RTCError PeerConnection::UpdateTransceiverChannel(
3201 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3202 transceiver,
3203 const cricket::ContentInfo& content,
3204 const cricket::ContentGroup* bundle_group) {
3205 RTC_DCHECK(IsUnifiedPlan());
3206 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003207 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003208 if (content.rejected) {
3209 if (channel) {
3210 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003211 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003212 }
3213 } else {
3214 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003215 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003216 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003217 } else {
Steve Anton69470252018-02-09 11:43:08 -08003218 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003219 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003220 }
3221 if (!channel) {
3222 LOG_AND_RETURN_ERROR(
3223 RTCErrorType::INTERNAL_ERROR,
3224 "Failed to create channel for mid=" + content.name);
3225 }
3226 transceiver->internal()->SetChannel(channel);
3227 }
3228 }
3229 return RTCError::OK();
3230}
3231
Steve Antonfa2260d2017-12-28 16:38:23 -08003232RTCError PeerConnection::UpdateDataChannel(
3233 cricket::ContentSource source,
3234 const cricket::ContentInfo& content,
3235 const cricket::ContentGroup* bundle_group) {
3236 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003237 // If data channels are disabled, ignore this media section. CreateAnswer
3238 // will take care of rejecting it.
3239 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003240 }
3241 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003242 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003243 DestroyDataChannel();
3244 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003245 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003246 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003247 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003248 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3249 "Failed to create data channel.");
3250 }
3251 }
3252 if (source == cricket::CS_REMOTE) {
3253 const MediaContentDescription* data_desc = content.media_description();
3254 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3255 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3256 }
3257 }
3258 }
3259 return RTCError::OK();
3260}
3261
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003262// This method will extract any send encodings that were sent by the remote
3263// connection. This is currently only relevant for Simulcast scenario (where
3264// the number of layers may be communicated by the server).
3265static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3266 const MediaContentDescription& desc) {
3267 if (!desc.HasSimulcast()) {
3268 return {};
3269 }
3270 std::vector<RtpEncodingParameters> result;
3271 const SimulcastDescription& simulcast = desc.simulcast_description();
3272
3273 // This is a remote description, the parameters we are after should appear
3274 // as receive streams.
3275 for (const auto& alternatives : simulcast.receive_layers()) {
3276 RTC_DCHECK(!alternatives.empty());
3277 // There is currently no way to specify or choose from alternatives.
3278 // We will always use the first alternative, which is the most preferred.
3279 const SimulcastLayer& layer = alternatives[0];
3280 RtpEncodingParameters parameters;
3281 parameters.rid = layer.rid;
3282 parameters.active = !layer.is_paused;
3283 result.push_back(parameters);
3284 }
3285
3286 return result;
3287}
3288
3289static RTCError UpdateSimulcastLayerStatusInSender(
3290 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003291 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003292 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003293 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003294 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003295
3296 // The simulcast envelope cannot be changed, only the status of the streams.
3297 // So we will iterate over the send encodings rather than the layers.
3298 for (RtpEncodingParameters& encoding : parameters.encodings) {
3299 auto iter = std::find_if(layers.begin(), layers.end(),
3300 [&encoding](const SimulcastLayer& layer) {
3301 return layer.rid == encoding.rid;
3302 });
3303 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003304 if (iter == layers.end()) {
3305 disabled_layers.push_back(encoding.rid);
3306 continue;
3307 }
3308
3309 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003310 }
3311
Amit Hilbuch619b2942019-02-26 15:55:19 -08003312 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003313 if (result.ok()) {
3314 result = sender->DisableEncodingLayers(disabled_layers);
3315 }
3316
3317 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003318}
3319
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003320static bool SimulcastIsRejected(
3321 const ContentInfo* local_content,
3322 const MediaContentDescription& answer_media_desc) {
3323 bool simulcast_offered = local_content &&
3324 local_content->media_description() &&
3325 local_content->media_description()->HasSimulcast();
3326 bool simulcast_answered = answer_media_desc.HasSimulcast();
3327 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3328 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3329 return simulcast_offered && (!simulcast_answered || !rids_supported);
3330}
3331
Amit Hilbuch2297d332019-02-19 12:49:22 -08003332static RTCError DisableSimulcastInSender(
3333 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003334 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003335 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003336 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003337 return RTCError::OK();
3338 }
3339
Amit Hilbuch2297d332019-02-19 12:49:22 -08003340 std::vector<std::string> disabled_layers;
3341 std::transform(
3342 parameters.encodings.begin() + 1, parameters.encodings.end(),
3343 std::back_inserter(disabled_layers),
3344 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3345 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003346}
3347
Steve Antondcc3c022017-12-22 16:02:54 -08003348RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3349PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003350 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003351 size_t mline_index,
3352 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003353 const ContentInfo* old_local_content,
3354 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003355 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003356 // If this is an offer then the m= section might be recycled. If the m=
3357 // section is being recycled (defined as: rejected in the current local or
3358 // remote description and not rejected in new description), dissociate the
3359 // currently associated RtpTransceiver by setting its mid property to null,
3360 // and discard the mapping between the transceiver and its m= section index.
3361 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3362 old_remote_content)) {
3363 // We want to dissociate the transceiver that has the rejected mid.
3364 const std::string& old_mid =
3365 (old_local_content && old_local_content->rejected)
3366 ? old_local_content->name
3367 : old_remote_content->name;
3368 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003369 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003370 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3371 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003372 old_transceiver->internal()->set_mid(absl::nullopt);
3373 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003374 }
3375 }
3376 const MediaContentDescription* media_desc = content.media_description();
3377 auto transceiver = GetAssociatedTransceiver(content.name);
3378 if (source == cricket::CS_LOCAL) {
3379 // Find the RtpTransceiver that corresponds to this m= section, using the
3380 // mapping between transceivers and m= section indices established when
3381 // creating the offer.
3382 if (!transceiver) {
3383 transceiver = GetTransceiverByMLineIndex(mline_index);
3384 }
3385 if (!transceiver) {
3386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3387 "Unknown transceiver");
3388 }
3389 } else {
3390 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3391 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3392 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003393 // When simulcast is requested, a transceiver cannot be associated because
3394 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003395 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003396 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3397 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003398 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3399 }
3400 // If no RtpTransceiver was found in the previous step, create one with a
3401 // recvonly direction.
3402 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003403 RTC_LOG(LS_INFO) << "Adding "
3404 << cricket::MediaTypeToString(media_desc->type())
3405 << " transceiver for MID=" << content.name
3406 << " at i=" << mline_index
3407 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003408 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003409 std::vector<RtpEncodingParameters> send_encodings =
3410 GetSendEncodingsFromRemoteDescription(*media_desc);
3411 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3412 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003413 std::string receiver_id;
3414 if (!media_desc->streams().empty()) {
3415 receiver_id = media_desc->streams()[0].id;
3416 } else {
3417 receiver_id = rtc::CreateRandomUuid();
3418 }
3419 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003420 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003421 transceiver->internal()->set_direction(
3422 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003423 if (type == SdpType::kOffer) {
3424 transceiver_stable_states_by_transceivers_[transceiver] =
3425 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3426 absl::nullopt, absl::nullopt, true);
3427 }
Steve Antondcc3c022017-12-22 16:02:54 -08003428 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003429 // Check if the offer indicated simulcast but the answer rejected it.
3430 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003431 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003432 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003433 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003434 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003435 if (!error.ok()) {
3436 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3437 return std::move(error);
3438 }
3439 }
Steve Antondcc3c022017-12-22 16:02:54 -08003440 }
3441 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003442 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003443 LOG_AND_RETURN_ERROR(
3444 RTCErrorType::INVALID_PARAMETER,
3445 "Transceiver type does not match media description type.");
3446 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003447 if (media_desc->HasSimulcast()) {
3448 std::vector<SimulcastLayer> layers =
3449 source == cricket::CS_LOCAL
3450 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3451 : media_desc->simulcast_description()
3452 .receive_layers()
3453 .GetAllLayers();
3454 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003455 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003456 if (!error.ok()) {
3457 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3458 return std::move(error);
3459 }
3460 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003461 if (type == SdpType::kOffer) {
3462 // Make sure we don't overwrite existing stable states and that the
3463 // state is really going to change when adding new record to the map.
3464 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3465 if (it == transceiver_stable_states_by_transceivers_.end() &&
3466 (transceiver->internal()->mid() != content.name ||
3467 transceiver->internal()->mline_index() != mline_index)) {
3468 transceiver_stable_states_by_transceivers_[transceiver] =
3469 TransceiverStableState(transceiver->internal()->direction(),
3470 transceiver->internal()->mid(),
3471 transceiver->internal()->mline_index(), false);
3472 }
3473 }
3474
Steve Antondcc3c022017-12-22 16:02:54 -08003475 // Associate the found or created RtpTransceiver with the m= section by
3476 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3477 // section, and establish a mapping between the transceiver and the index of
3478 // the m= section.
3479 transceiver->internal()->set_mid(content.name);
3480 transceiver->internal()->set_mline_index(mline_index);
3481 return std::move(transceiver);
3482}
3483
3484rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3485PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3486 RTC_DCHECK(IsUnifiedPlan());
3487 for (auto transceiver : transceivers_) {
3488 if (transceiver->mid() == mid) {
3489 return transceiver;
3490 }
3491 }
3492 return nullptr;
3493}
3494
3495rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3496PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3497 RTC_DCHECK(IsUnifiedPlan());
3498 for (auto transceiver : transceivers_) {
3499 if (transceiver->internal()->mline_index() == mline_index) {
3500 return transceiver;
3501 }
3502 }
3503 return nullptr;
3504}
3505
3506rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3507PeerConnection::FindAvailableTransceiverToReceive(
3508 cricket::MediaType media_type) const {
3509 RTC_DCHECK(IsUnifiedPlan());
3510 // From JSEP section 5.10 (Applying a Remote Description):
3511 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3512 // the same type that were added to the PeerConnection by addTrack and are not
3513 // associated with any m= section and are not stopped, find the first such
3514 // RtpTransceiver.
3515 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003516 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003517 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3518 !transceiver->stopped()) {
3519 return transceiver;
3520 }
3521 }
3522 return nullptr;
3523}
3524
Steve Antoned10bd92017-12-05 10:52:59 -08003525const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3526 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3527 transceiver,
3528 const SessionDescriptionInterface* sdesc) const {
3529 RTC_DCHECK(transceiver);
3530 RTC_DCHECK(sdesc);
3531 if (IsUnifiedPlan()) {
3532 if (!transceiver->internal()->mid()) {
3533 // This transceiver is not associated with a media section yet.
3534 return nullptr;
3535 }
3536 return sdesc->description()->GetContentByName(
3537 *transceiver->internal()->mid());
3538 } else {
3539 // Plan B only allows at most one audio and one video section, so use the
3540 // first media section of that type.
3541 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003542 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003543 }
3544}
3545
deadbeef46c73892016-11-16 19:42:04 -08003546PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003547 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003548 return configuration_;
3549}
3550
Niels Möller2579f0c2019-08-19 09:58:17 +02003551RTCError PeerConnection::SetConfiguration(
3552 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003553 RTC_DCHECK_RUN_ON(signaling_thread());
3554 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003555 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003556 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3558 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003559 }
3560
Qingsi Wanga2d60672018-04-11 16:57:45 -07003561 // According to JSEP, after setLocalDescription, changing the candidate pool
3562 // size is not allowed, and changing the set of ICE servers will not result
3563 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003564 if (local_description() && configuration.ice_candidate_pool_size !=
3565 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003566 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3567 "Can't change candidate pool size after calling "
3568 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003569 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003570
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003571 if (local_description() &&
3572 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003573 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3574 "Can't change media_transport after calling "
3575 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003576 }
3577
3578 if (remote_description() &&
3579 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003580 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3581 "Can't change media_transport after calling "
3582 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003583 }
3584
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003585 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003586 configuration.use_media_transport_for_data_channels !=
3587 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3589 "Can't change media_transport_for_data_channels "
3590 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003591 }
3592
3593 if (remote_description() &&
3594 configuration.use_media_transport_for_data_channels !=
3595 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003596 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3597 "Can't change media_transport_for_data_channels "
3598 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003599 }
3600
3601 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003602 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3604 "Can't change crypto_options after calling "
3605 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003606 }
3607
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003608 if (local_description() && configuration.use_datagram_transport !=
3609 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003610 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3611 "Can't change use_datagram_transport "
3612 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003613 }
3614
3615 if (remote_description() && configuration.use_datagram_transport !=
3616 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3618 "Can't change use_datagram_transport "
3619 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003620 }
3621
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003622 if (local_description() &&
3623 configuration.use_datagram_transport_for_data_channels !=
3624 configuration_.use_datagram_transport_for_data_channels) {
3625 LOG_AND_RETURN_ERROR(
3626 RTCErrorType::INVALID_MODIFICATION,
3627 "Can't change use_datagram_transport_for_data_channels "
3628 "after calling SetLocalDescription.");
3629 }
3630
3631 if (remote_description() &&
3632 configuration.use_datagram_transport_for_data_channels !=
3633 configuration_.use_datagram_transport_for_data_channels) {
3634 LOG_AND_RETURN_ERROR(
3635 RTCErrorType::INVALID_MODIFICATION,
3636 "Can't change use_datagram_transport_for_data_channels "
3637 "after calling SetRemoteDescription.");
3638 }
3639
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003640 if (local_description() &&
3641 configuration.use_datagram_transport_for_data_channels_receive_only !=
3642 configuration_
3643 .use_datagram_transport_for_data_channels_receive_only) {
3644 LOG_AND_RETURN_ERROR(
3645 RTCErrorType::INVALID_MODIFICATION,
3646 "Can't change use_datagram_transport_for_data_channels_receive_only "
3647 "after calling SetLocalDescription.");
3648 }
3649
3650 if (remote_description() &&
3651 configuration.use_datagram_transport_for_data_channels_receive_only !=
3652 configuration_
3653 .use_datagram_transport_for_data_channels_receive_only) {
3654 LOG_AND_RETURN_ERROR(
3655 RTCErrorType::INVALID_MODIFICATION,
3656 "Can't change use_datagram_transport_for_data_channels_receive_only "
3657 "after calling SetRemoteDescription.");
3658 }
3659
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003660 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003661 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003662 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003663 *configuration.use_datagram_transport) ||
3664 (configuration.use_datagram_transport_for_data_channels &&
3665 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003666 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3667 << "Media transport requires MaxBundle policy.";
3668 }
3669
deadbeef293e9262017-01-11 12:28:30 -08003670 // The simplest (and most future-compatible) way to tell if the config was
3671 // modified in an invalid way is to copy each property we do support
3672 // modifying, then use operator==. There are far more properties we don't
3673 // support modifying than those we do, and more could be added.
3674 RTCConfiguration modified_config = configuration_;
3675 modified_config.servers = configuration.servers;
3676 modified_config.type = configuration.type;
3677 modified_config.ice_candidate_pool_size =
3678 configuration.ice_candidate_pool_size;
3679 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003680 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07003681 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3682 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003683 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003684 modified_config.ice_check_interval_strong_connectivity =
3685 configuration.ice_check_interval_strong_connectivity;
3686 modified_config.ice_check_interval_weak_connectivity =
3687 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003688 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3689 modified_config.ice_unwritable_min_checks =
3690 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003691 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003692 modified_config.stun_candidate_keepalive_interval =
3693 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003694 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003695 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003696 modified_config.active_reset_srtp_params =
3697 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003698 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003699 modified_config.use_media_transport_for_data_channels =
3700 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003701 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003702 modified_config.use_datagram_transport_for_data_channels =
3703 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003704 modified_config.use_datagram_transport_for_data_channels_receive_only =
3705 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02003706 modified_config.turn_logging_id = configuration.turn_logging_id;
deadbeef293e9262017-01-11 12:28:30 -08003707 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003708 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3709 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003710 }
3711
Steve Anton038834f2017-07-14 15:59:59 -07003712 // Validate the modified configuration.
3713 RTCError validate_error = ValidateConfiguration(modified_config);
3714 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003715 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003716 }
3717
deadbeef293e9262017-01-11 12:28:30 -08003718 // Note that this isn't possible through chromium, since it's an unsigned
3719 // short in WebIDL.
3720 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003721 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003722 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003723 }
3724
3725 // Parse ICE servers before hopping to network thread.
3726 cricket::ServerAddresses stun_servers;
3727 std::vector<cricket::RelayServerConfig> turn_servers;
3728 RTCErrorType parse_error =
3729 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3730 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003731 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003732 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003733 // Add the turn logging id to all turn servers
3734 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3735 turn_server.turn_logging_id = configuration.turn_logging_id;
3736 }
3737
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003738 // Note if STUN or TURN servers were supplied.
3739 if (!stun_servers.empty()) {
3740 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3741 }
3742 if (!turn_servers.empty()) {
3743 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3744 }
deadbeef293e9262017-01-11 12:28:30 -08003745
3746 // In theory this shouldn't fail.
3747 if (!network_thread()->Invoke<bool>(
3748 RTC_FROM_HERE,
3749 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3750 stun_servers, turn_servers, modified_config.type,
3751 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003752 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003753 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003754 modified_config.stun_candidate_keepalive_interval,
3755 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003756 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3757 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003758 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003759
deadbeefd1a38b52016-12-10 13:15:33 -08003760 // As described in JSEP, calling setConfiguration with new ICE servers or
3761 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3762 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003763 if (modified_config.servers != configuration_.servers ||
3764 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003765 modified_config.GetTurnPortPrunePolicy() !=
3766 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08003767 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003768 }
skvladd1f5fda2017-02-03 16:54:05 -08003769
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003770 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003771
3772 use_datagram_transport_ = datagram_transport_config_.enabled &&
3773 modified_config.use_datagram_transport.value_or(
3774 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003775 use_datagram_transport_for_data_channels_ =
3776 datagram_transport_data_channel_config_.enabled &&
3777 modified_config.use_datagram_transport_for_data_channels.value_or(
3778 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003779 use_datagram_transport_for_data_channels_receive_only_ =
3780 modified_config.use_datagram_transport_for_data_channels_receive_only
3781 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003782 transport_controller_->SetMediaTransportSettings(
3783 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003784 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003785 use_datagram_transport_, use_datagram_transport_for_data_channels_,
3786 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08003787
Zhi Huangb57e1692018-06-12 11:41:11 -07003788 if (configuration_.active_reset_srtp_params !=
3789 modified_config.active_reset_srtp_params) {
3790 transport_controller_->SetActiveResetSrtpParams(
3791 modified_config.active_reset_srtp_params);
3792 }
3793
deadbeef293e9262017-01-11 12:28:30 -08003794 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003795 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02003796 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003797}
3798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003799bool PeerConnection::AddIceCandidate(
3800 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003801 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003802 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003803 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003804 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003805 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003806 return false;
3807 }
Steve Antond25da372017-11-06 14:50:29 -08003808
3809 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003810 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003811 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003812 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003813 return false;
3814 }
3815
3816 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003817 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003818 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003819 return false;
3820 }
3821
3822 bool valid = false;
3823 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3824 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003825 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003826 return false;
3827 }
3828
3829 // Add this candidate to the remote session description.
3830 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003831 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003832 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003833 return false;
3834 }
3835
3836 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003837 bool result = UseCandidate(ice_candidate);
3838 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003839 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003840 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3841 } else {
3842 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3843 }
3844 return result;
Steve Antond25da372017-11-06 14:50:29 -08003845 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003846 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003847 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003848 return true;
3849 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003850}
3851
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003852bool PeerConnection::RemoveIceCandidates(
3853 const std::vector<cricket::Candidate>& candidates) {
3854 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003855 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003856 if (IsClosed()) {
3857 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3858 return false;
3859 }
3860
Steve Antond25da372017-11-06 14:50:29 -08003861 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003862 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3863 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003864 return false;
3865 }
3866
3867 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003868 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003869 return false;
3870 }
3871
3872 size_t number_removed =
3873 mutable_remote_description()->RemoveCandidates(candidates);
3874 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003875 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003876 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003877 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003878 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003879 }
3880
3881 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003882 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3883 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003884 RTC_LOG(LS_ERROR)
3885 << "RemoveIceCandidates: Error when removing remote candidates: "
3886 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003887 }
3888 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003889}
3890
Niels Möller0c4f7be2018-05-07 14:01:37 +02003891RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003892 if (!worker_thread()->IsCurrent()) {
3893 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003894 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003895 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003896 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003897
Niels Möller0c4f7be2018-05-07 14:01:37 +02003898 const bool has_min = bitrate.min_bitrate_bps.has_value();
3899 const bool has_start = bitrate.start_bitrate_bps.has_value();
3900 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003901 if (has_min && *bitrate.min_bitrate_bps < 0) {
3902 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3903 "min_bitrate_bps <= 0");
3904 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003905 if (has_start) {
3906 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003907 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003908 "start_bitrate_bps < min_bitrate_bps");
3909 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003910 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3911 "curent_bitrate_bps < 0");
3912 }
3913 }
3914 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003915 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003916 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003917 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003918 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3919 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3920 "max_bitrate_bps < min_bitrate_bps");
3921 } else if (*bitrate.max_bitrate_bps < 0) {
3922 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3923 "max_bitrate_bps < 0");
3924 }
3925 }
3926
zstein4b979802017-06-02 14:37:37 -07003927 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003928 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003929
3930 return RTCError::OK();
3931}
3932
henrika5f6bf242017-11-01 11:06:56 +01003933void PeerConnection::SetAudioPlayout(bool playout) {
3934 if (!worker_thread()->IsCurrent()) {
3935 worker_thread()->Invoke<void>(
3936 RTC_FROM_HERE,
3937 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3938 return;
3939 }
3940 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003941 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003942 audio_state->SetPlayout(playout);
3943}
3944
3945void PeerConnection::SetAudioRecording(bool recording) {
3946 if (!worker_thread()->IsCurrent()) {
3947 worker_thread()->Invoke<void>(
3948 RTC_FROM_HERE,
3949 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3950 return;
3951 }
3952 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003953 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003954 audio_state->SetRecording(recording);
3955}
3956
Steve Anton8c0f7a72017-10-03 10:03:10 -07003957std::unique_ptr<rtc::SSLCertificate>
3958PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003959 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3960 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003961 return nullptr;
3962 }
Steve Antonf25303e2018-10-16 15:23:31 -07003963 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003964}
3965
Zhi Huang70b820f2018-01-27 14:16:15 -08003966std::unique_ptr<rtc::SSLCertChain>
3967PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003968 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003969 auto audio_transceiver = GetFirstAudioTransceiver();
3970 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003971 return nullptr;
3972 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003973 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003974 audio_transceiver->internal()->channel()->transport_name());
3975}
3976
3977rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3978PeerConnection::GetFirstAudioTransceiver() const {
3979 for (auto transceiver : transceivers_) {
3980 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3981 return transceiver;
3982 }
3983 }
3984 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003985}
3986
Bjorn Tereliusde939432017-11-20 17:38:14 +01003987bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3988 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003989 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02003990 RTC_FROM_HERE,
3991 [this, output = std::move(output), output_period_ms]() mutable {
3992 return StartRtcEventLog_w(std::move(output), output_period_ms);
3993 });
ivoc14d5dbe2016-07-04 07:06:55 -07003994}
3995
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003996bool PeerConnection::StartRtcEventLog(
3997 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003998 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3999 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4000 output_period_ms = 5000;
4001 }
4002 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004003}
4004
ivoc14d5dbe2016-07-04 07:06:55 -07004005void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004006 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004007 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4008}
4009
Harald Alvestrandad88c882018-11-28 16:47:46 +01004010rtc::scoped_refptr<DtlsTransportInterface>
4011PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004012 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004013 return transport_controller_->LookupDtlsTransportByMid(mid);
4014}
4015
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004016rtc::scoped_refptr<DtlsTransport>
4017PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004018 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004019 return transport_controller_->LookupDtlsTransportByMid(mid);
4020}
4021
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004022rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4023 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004024 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004025 if (!sctp_mid_) {
4026 return nullptr;
4027 }
4028 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004029}
4030
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004031const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004032 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004033 return pending_local_description_ ? pending_local_description_.get()
4034 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004035}
4036
4037const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004038 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004039 return pending_remote_description_ ? pending_remote_description_.get()
4040 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004041}
4042
deadbeeffe4a8a42016-12-20 17:56:17 -08004043const SessionDescriptionInterface* PeerConnection::current_local_description()
4044 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004045 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004046 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004047}
4048
4049const SessionDescriptionInterface* PeerConnection::current_remote_description()
4050 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004051 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004052 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004053}
4054
4055const SessionDescriptionInterface* PeerConnection::pending_local_description()
4056 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004057 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004058 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004059}
4060
4061const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4062 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004063 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004064 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004065}
4066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004067void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004068 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004069 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004070 // Update stats here so that we have the most recent stats for tracks and
4071 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004072 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004073
Steve Anton75737c02017-11-06 10:37:17 -08004074 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004075 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004076
Mirko Bonadei739baf02019-01-27 17:29:42 +01004077 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004078 transceiver->Stop();
4079 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004080
4081 // Ensure that all asynchronous stats requests are completed before destroying
4082 // the transport controller below.
4083 if (stats_collector_) {
4084 stats_collector_->WaitForPendingRequest();
4085 }
4086
4087 // Don't destroy BaseChannels until after stats has been cleaned up so that
4088 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004089 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004090
Qingsi Wang93a84392018-01-30 17:13:09 -08004091 // The event log is used in the transport controller, which must be outlived
4092 // by the former. CreateOffer by the peer connection is implemented
4093 // asynchronously and if the peer connection is closed without resetting the
4094 // WebRTC session description factory, the session description factory would
4095 // call the transport controller.
4096 webrtc_session_desc_factory_.reset();
4097 transport_controller_.reset();
4098
deadbeef42a42632017-03-10 15:18:00 -08004099 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004100 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4101 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004102
Steve Anton978b8762017-09-29 12:15:02 -07004103 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004104 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004105 call_.reset();
4106 // The event log must outlive call (and any other object that uses it).
4107 event_log_.reset();
4108 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004109 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004110 // The .h file says that observer can be discarded after close() returns.
4111 // Make sure this is true.
4112 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004113}
4114
Steve Antonad182762018-09-05 20:22:40 +00004115void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004116 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004117 switch (msg->message_id) {
4118 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4119 SetSessionDescriptionMsg* param =
4120 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4121 param->observer->OnSuccess();
4122 delete param;
4123 break;
4124 }
4125 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4126 SetSessionDescriptionMsg* param =
4127 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4128 param->observer->OnFailure(std::move(param->error));
4129 delete param;
4130 break;
4131 }
4132 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4133 CreateSessionDescriptionMsg* param =
4134 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4135 param->observer->OnFailure(std::move(param->error));
4136 delete param;
4137 break;
4138 }
4139 case MSG_GETSTATS: {
4140 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4141 StatsReports reports;
4142 stats_->GetStats(param->track, &reports);
4143 param->observer->OnComplete(reports);
4144 delete param;
4145 break;
4146 }
4147 case MSG_FREE_DATACHANNELS: {
4148 sctp_data_channels_to_free_.clear();
4149 break;
4150 }
4151 case MSG_REPORT_USAGE_PATTERN: {
4152 ReportUsagePattern();
4153 break;
4154 }
4155 default:
4156 RTC_NOTREACHED() << "Not implemented";
4157 break;
4158 }
4159}
4160
Steve Antonafb0bb72018-02-20 11:35:37 -08004161cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4162 RTC_DCHECK(!IsUnifiedPlan());
4163 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4164 GetAudioTransceiver()->internal()->channel());
4165 if (voice_channel) {
4166 return voice_channel->media_channel();
4167 } else {
4168 return nullptr;
4169 }
4170}
4171
4172cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4173 RTC_DCHECK(!IsUnifiedPlan());
4174 auto* video_channel = static_cast<cricket::VideoChannel*>(
4175 GetVideoTransceiver()->internal()->channel());
4176 if (video_channel) {
4177 return video_channel->media_channel();
4178 } else {
4179 return nullptr;
4180 }
4181}
4182
Steve Anton4171afb2017-11-20 10:20:22 -08004183void PeerConnection::CreateAudioReceiver(
4184 MediaStreamInterface* stream,
4185 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004186 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4187 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004188 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4189 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004190 auto* audio_receiver = new AudioRtpReceiver(
4191 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004192 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004193 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4194 audio_receiver->SetupUnsignaledMediaChannel();
4195 } else {
4196 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4197 }
Steve Antond3679212018-01-17 17:41:02 -08004198 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4199 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004200 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004201 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004202 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004203}
4204
Steve Anton4171afb2017-11-20 10:20:22 -08004205void PeerConnection::CreateVideoReceiver(
4206 MediaStreamInterface* stream,
4207 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004208 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4209 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004210 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4211 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004212 auto* video_receiver = new VideoRtpReceiver(
4213 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004214 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004215 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4216 video_receiver->SetupUnsignaledMediaChannel();
4217 } else {
4218 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4219 }
Steve Antond3679212018-01-17 17:41:02 -08004220 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4221 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004222 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004223 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004224 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004225}
4226
deadbeef70ab1a12015-09-28 16:53:55 -07004227// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4228// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004229rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004230 const RtpSenderInfo& remote_sender_info) {
4231 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4232 if (!receiver) {
4233 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4234 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004235 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004236 }
Steve Anton4171afb2017-11-20 10:20:22 -08004237 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4238 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4239 } else {
4240 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4241 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004242 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004243}
4244
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004245void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4246 MediaStreamInterface* stream) {
4247 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004248 RTC_DCHECK(track);
4249 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004250 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004251 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004252 // We already have a sender for this track, so just change the stream_id
4253 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004254 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004255 return;
4256 }
4257
4258 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004259 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004260 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004261 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004262 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004263 // If the sender has already been configured in SDP, we call SetSsrc,
4264 // which will connect the sender to the underlying transport. This can
4265 // occur if a local session description that contains the ID of the sender
4266 // is set before AddStream is called. It can also occur if the local
4267 // session description is not changed and RemoveStream is called, and
4268 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004269 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004270 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004271 if (sender_info) {
4272 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004273 }
4274}
4275
4276// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4277// indefinitely, when we have unified plan SDP.
4278void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4279 MediaStreamInterface* stream) {
4280 RTC_DCHECK(!IsClosed());
4281 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004282 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004283 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4284 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004285 return;
4286 }
Steve Anton4171afb2017-11-20 10:20:22 -08004287 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004288}
4289
4290void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4291 MediaStreamInterface* stream) {
4292 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004293 RTC_DCHECK(track);
4294 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004295 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004296 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004297 // We already have a sender for this track, so just change the stream_id
4298 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004299 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004300 return;
4301 }
4302
4303 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004304 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004305 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004306 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004307 GetVideoTransceiver()->internal()->AddSender(new_sender);
4308 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004309 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004310 if (sender_info) {
4311 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004312 }
4313}
4314
4315void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4316 MediaStreamInterface* stream) {
4317 RTC_DCHECK(!IsClosed());
4318 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004319 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004320 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4321 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004322 return;
4323 }
Steve Anton4171afb2017-11-20 10:20:22 -08004324 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004325}
4326
Steve Antonba818672017-11-06 10:21:57 -08004327void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004328 if (ice_connection_state_ == new_state) {
4329 return;
4330 }
4331
deadbeefcbecd352015-09-23 11:50:27 -07004332 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004333 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004334 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004335 return;
4336 }
Steve Antonba818672017-11-06 10:21:57 -08004337
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4339 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004340 RTC_DCHECK(ice_connection_state_ !=
4341 PeerConnectionInterface::kIceConnectionClosed);
4342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004343 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004344 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004345}
4346
Alex Loiko9289eda2018-11-23 16:18:59 +00004347void PeerConnection::SetStandardizedIceConnectionState(
4348 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004349 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004350 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004351 }
4352
4353 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004354 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004355 }
4356
4357 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4358 << standardized_ice_connection_state_ << " => " << new_state;
4359
Alex Loiko9289eda2018-11-23 16:18:59 +00004360 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004361 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004362}
4363
Jonas Olsson635474e2018-10-18 15:58:17 +02004364void PeerConnection::SetConnectionState(
4365 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004366 if (connection_state_ == new_state)
4367 return;
4368 if (IsClosed())
4369 return;
4370 connection_state_ = new_state;
4371 Observer()->OnConnectionChange(new_state);
4372}
4373
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004374void PeerConnection::OnIceGatheringChange(
4375 PeerConnectionInterface::IceGatheringState new_state) {
4376 if (IsClosed()) {
4377 return;
4378 }
4379 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004380 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004381}
4382
jbauch81bf7b02017-03-25 08:31:12 -07004383void PeerConnection::OnIceCandidate(
4384 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004385 if (IsClosed()) {
4386 return;
4387 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004388 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004389 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004390}
4391
Eldar Relloda13ea22019-06-01 12:23:43 +03004392void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4393 const std::string& url,
4394 int error_code,
4395 const std::string& error_text) {
4396 if (IsClosed()) {
4397 return;
4398 }
4399 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4400}
4401
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004402void PeerConnection::OnIceCandidatesRemoved(
4403 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004404 if (IsClosed()) {
4405 return;
4406 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004407 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004408}
4409
Alex Drake00c7ecf2019-08-06 10:54:47 -07004410void PeerConnection::OnSelectedCandidatePairChanged(
4411 const cricket::CandidatePairChangeEvent& event) {
4412 if (IsClosed()) {
4413 return;
4414 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004415
Qingsi Wangcc46b102019-09-12 11:19:01 -07004416 if (event.selected_candidate_pair.local_candidate().type() ==
4417 LOCAL_PORT_TYPE &&
4418 event.selected_candidate_pair.remote_candidate().type() ==
4419 LOCAL_PORT_TYPE) {
4420 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4421 }
4422
Alex Drake00c7ecf2019-08-06 10:54:47 -07004423 Observer()->OnIceSelectedCandidatePairChanged(event);
4424}
4425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004426void PeerConnection::ChangeSignalingState(
4427 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004428 if (signaling_state_ == signaling_state) {
4429 return;
4430 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004431 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4432 << GetSignalingStateString(signaling_state_)
4433 << " New state: "
4434 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004435 signaling_state_ = signaling_state;
4436 if (signaling_state == kClosed) {
4437 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004438 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004439 standardized_ice_connection_state_ =
4440 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004441 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4442 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004443 if (ice_gathering_state_ != kIceGatheringComplete) {
4444 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004445 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004446 }
4447 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004448 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004449}
4450
deadbeefeb459812015-12-15 19:24:43 -08004451void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4452 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004453 if (IsClosed()) {
4454 return;
4455 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004456 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004457 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004458}
4459
deadbeefeb459812015-12-15 19:24:43 -08004460void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4461 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004462 if (IsClosed()) {
4463 return;
4464 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004465 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004466 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004467}
4468
4469void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4470 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004471 if (IsClosed()) {
4472 return;
4473 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004474 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004475 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004476}
4477
4478void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4479 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004480 if (IsClosed()) {
4481 return;
4482 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004483 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004484 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004485}
4486
Henrik Boström31638672017-11-23 17:48:32 +01004487void PeerConnection::PostSetSessionDescriptionSuccess(
4488 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004489 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4490 signaling_thread()->Post(RTC_FROM_HERE, this,
4491 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004492}
4493
deadbeefab9b2d12015-10-14 11:33:11 -07004494void PeerConnection::PostSetSessionDescriptionFailure(
4495 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004496 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004497 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004498 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4499 msg->error = std::move(error);
4500 signaling_thread()->Post(RTC_FROM_HERE, this,
4501 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004502}
4503
4504void PeerConnection::PostCreateSessionDescriptionFailure(
4505 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004506 RTCError error) {
4507 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004508 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4509 msg->error = std::move(error);
4510 signaling_thread()->Post(RTC_FROM_HERE, this,
4511 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004512}
4513
zhihuang1c378ed2017-08-17 14:10:50 -07004514void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004515 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004516 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004517 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004518
Steve Antondcc3c022017-12-22 16:02:54 -08004519 if (IsUnifiedPlan()) {
4520 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4521 } else {
4522 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4523 }
4524
Steve Antonfa2260d2017-12-28 16:38:23 -08004525 // Intentionally unset the data channel type for RTP data channel with the
4526 // second condition. Otherwise the RTP data channels would be successfully
4527 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4528 // when building with chromium. We want to leave RTP data channels broken, so
4529 // people won't try to use them.
4530 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4531 session_options->data_channel_type = data_channel_type();
4532 }
4533
Steve Antondcc3c022017-12-22 16:02:54 -08004534 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004535 bool ice_restart = offer_answer_options.ice_restart ||
4536 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004537 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004538 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004539 options.transport_options.enable_ice_renomination =
4540 configuration_.enable_ice_renomination;
4541 }
4542
4543 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004544 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004545 session_options->pooled_ice_credentials =
4546 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4547 RTC_FROM_HERE,
4548 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4549 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004550 session_options->offer_extmap_allow_mixed =
4551 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004552
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004553 if (configuration_.use_media_transport ||
4554 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004555 session_options->media_transport_settings =
4556 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4557 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004558
4559 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004560 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004561 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004562 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004563 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004564 if (!params) {
4565 continue;
4566 }
4567 options.transport_options.opaque_parameters = params;
4568 if ((use_datagram_transport_ &&
4569 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4570 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4571 (use_datagram_transport_for_data_channels_ &&
4572 options.type == cricket::MEDIA_TYPE_DATA)) {
4573 options.alt_protocol = params->protocol;
4574 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004575 }
4576 }
4577
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004578 // Allow fallback for using obsolete SCTP syntax.
4579 // Note that the default in |session_options| is true, while
4580 // the default in |options| is false.
4581 session_options->use_obsolete_sctp_sdp =
4582 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004583}
4584
4585void PeerConnection::GetOptionsForPlanBOffer(
4586 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4587 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004588 // Figure out transceiver directional preferences.
4589 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4590 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4591
4592 // By default, generate sendrecv/recvonly m= sections.
4593 bool recv_audio = true;
4594 bool recv_video = true;
4595
4596 // By default, only offer a new m= section if we have media to send with it.
4597 bool offer_new_audio_description = send_audio;
4598 bool offer_new_video_description = send_video;
4599 bool offer_new_data_description = HasDataChannels();
4600
4601 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004602 if (offer_answer_options.offer_to_receive_audio !=
4603 RTCOfferAnswerOptions::kUndefined) {
4604 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004605 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004606 offer_new_audio_description ||
4607 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004608 }
Steve Antondcc3c022017-12-22 16:02:54 -08004609 if (offer_answer_options.offer_to_receive_video !=
4610 RTCOfferAnswerOptions::kUndefined) {
4611 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004612 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004613 offer_new_video_description ||
4614 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004615 }
4616
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004617 absl::optional<size_t> audio_index;
4618 absl::optional<size_t> video_index;
4619 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004620 // If a current description exists, generate m= sections in the same order,
4621 // using the first audio/video/data section that appears and rejecting
4622 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004623 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004624 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004625 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004626 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4627 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4628 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004629 }
4630
zhihuang1c378ed2017-08-17 14:10:50 -07004631 // Add audio/video/data m= sections to the end if needed.
4632 if (!audio_index && offer_new_audio_description) {
4633 session_options->media_description_options.push_back(
4634 cricket::MediaDescriptionOptions(
4635 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004636 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4637 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004638 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004639 }
zhihuang1c378ed2017-08-17 14:10:50 -07004640 if (!video_index && offer_new_video_description) {
4641 session_options->media_description_options.push_back(
4642 cricket::MediaDescriptionOptions(
4643 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004644 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4645 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004646 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004647 }
zhihuang1c378ed2017-08-17 14:10:50 -07004648 if (!data_index && offer_new_data_description) {
4649 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004650 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004651 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004652 }
4653
4654 cricket::MediaDescriptionOptions* audio_media_description_options =
4655 !audio_index ? nullptr
4656 : &session_options->media_description_options[*audio_index];
4657 cricket::MediaDescriptionOptions* video_media_description_options =
4658 !video_index ? nullptr
4659 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004660
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004661 AddPlanBRtpSenderOptions(GetSendersInternal(),
4662 audio_media_description_options,
4663 video_media_description_options,
4664 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004665}
4666
Steve Antondcc3c022017-12-22 16:02:54 -08004667static cricket::MediaDescriptionOptions
4668GetMediaDescriptionOptionsForTransceiver(
4669 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4670 transceiver,
4671 const std::string& mid) {
4672 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004673 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004674 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004675 media_description_options.codec_preferences =
4676 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004677 // This behavior is specified in JSEP. The gist is that:
4678 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4679 // sendrecv.
4680 // 2. If the MSID is included, then it must be included in any subsequent
4681 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004682 if (transceiver->stopped() ||
4683 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4684 !transceiver->internal()->has_ever_been_used_to_send())) {
4685 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004686 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004687
4688 cricket::SenderOptions sender_options;
4689 sender_options.track_id = transceiver->sender()->id();
4690 sender_options.stream_ids = transceiver->sender()->stream_ids();
4691
4692 // The following sets up RIDs and Simulcast.
4693 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004694 RtpParameters send_parameters =
4695 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004696 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4697 send_parameters.encodings.end(),
4698 [](const RtpEncodingParameters& encoding) {
4699 return !encoding.rid.empty();
4700 });
4701
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004702 std::vector<RidDescription> send_rids;
4703 SimulcastLayerList send_layers;
4704 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4705 if (encoding.rid.empty()) {
4706 continue;
4707 }
4708 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4709 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4710 }
4711
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004712 if (has_rids) {
4713 sender_options.rids = send_rids;
4714 }
4715
4716 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004717 // When RIDs are configured, we must set num_sim_layers to 0 to.
4718 // Otherwise, num_sim_layers must be 1 because either there is no
4719 // simulcast, or simulcast is acheived by munging the SDP.
4720 sender_options.num_sim_layers = has_rids ? 0 : 1;
4721 media_description_options.sender_options.push_back(sender_options);
4722
Steve Antondcc3c022017-12-22 16:02:54 -08004723 return media_description_options;
4724}
4725
Steve Anton5c72e712018-12-10 14:25:30 -08004726// Returns the ContentInfo at mline index |i|, or null if none exists.
4727static const ContentInfo* GetContentByIndex(
4728 const SessionDescriptionInterface* sdesc,
4729 size_t i) {
4730 if (!sdesc) {
4731 return nullptr;
4732 }
4733 const ContentInfos& contents = sdesc->description()->contents();
4734 return (i < contents.size() ? &contents[i] : nullptr);
4735}
4736
Steve Antondcc3c022017-12-22 16:02:54 -08004737void PeerConnection::GetOptionsForUnifiedPlanOffer(
4738 const RTCOfferAnswerOptions& offer_answer_options,
4739 cricket::MediaSessionOptions* session_options) {
4740 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4741 // Offers) and 5.2.2 (Subsequent Offers).
4742 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004743 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004744 const ContentInfos& local_contents =
4745 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004746 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004747 const ContentInfos& remote_contents =
4748 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004749 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004750 // The mline indices that can be recycled. New transceivers should reuse these
4751 // slots first.
4752 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004753 // First, go through each media section that exists in either the local or
4754 // remote description and generate a media section in this offer for the
4755 // associated transceiver. If a media section can be recycled, generate a
4756 // default, rejected media section here that can be later overwritten.
4757 for (size_t i = 0;
4758 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4759 // Either |local_content| or |remote_content| is non-null.
4760 const ContentInfo* local_content =
4761 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004762 const ContentInfo* current_local_content =
4763 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004764 const ContentInfo* remote_content =
4765 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004766 const ContentInfo* current_remote_content =
4767 GetContentByIndex(current_remote_description(), i);
4768 bool had_been_rejected =
4769 (current_local_content && current_local_content->rejected) ||
4770 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004771 const std::string& mid =
4772 (local_content ? local_content->name : remote_content->name);
4773 cricket::MediaType media_type =
4774 (local_content ? local_content->media_description()->type()
4775 : remote_content->media_description()->type());
4776 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4777 media_type == cricket::MEDIA_TYPE_VIDEO) {
4778 auto transceiver = GetAssociatedTransceiver(mid);
4779 RTC_CHECK(transceiver);
4780 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004781 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004782 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004783 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004784 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4785 RtpTransceiverDirection::kInactive,
4786 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004787 recycleable_mline_indices.push(i);
4788 } else {
4789 session_options->media_description_options.push_back(
4790 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4791 // CreateOffer shouldn't really cause any state changes in
4792 // PeerConnection, but we need a way to match new transceivers to new
4793 // media sections in SetLocalDescription and JSEP specifies this is done
4794 // by recording the index of the media section generated for the
4795 // transceiver in the offer.
4796 transceiver->internal()->set_mline_index(i);
4797 }
4798 } else {
4799 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004800 RTC_CHECK(GetDataMid());
4801 if (had_been_rejected || mid != *GetDataMid()) {
4802 session_options->media_description_options.push_back(
4803 GetMediaDescriptionOptionsForRejectedData(mid));
4804 } else {
4805 session_options->media_description_options.push_back(
4806 GetMediaDescriptionOptionsForActiveData(mid));
4807 }
Steve Antondcc3c022017-12-22 16:02:54 -08004808 }
4809 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004810
Steve Antondcc3c022017-12-22 16:02:54 -08004811 // Next, look for transceivers that are newly added (that is, are not stopped
4812 // and not associated). Reuse media sections marked as recyclable first,
4813 // otherwise append to the end of the offer. New media sections should be
4814 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004815 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004816 if (transceiver->mid() || transceiver->stopped()) {
4817 continue;
4818 }
4819 size_t mline_index;
4820 if (!recycleable_mline_indices.empty()) {
4821 mline_index = recycleable_mline_indices.front();
4822 recycleable_mline_indices.pop();
4823 session_options->media_description_options[mline_index] =
4824 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004825 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004826 } else {
4827 mline_index = session_options->media_description_options.size();
4828 session_options->media_description_options.push_back(
4829 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004830 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004831 }
4832 // See comment above for why CreateOffer changes the transceiver's state.
4833 transceiver->internal()->set_mline_index(mline_index);
4834 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004835 // Lastly, add a m-section if we have local data channels and an m section
4836 // does not already exist.
4837 if (!GetDataMid() && HasDataChannels()) {
4838 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004839 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004840 }
Steve Antondcc3c022017-12-22 16:02:54 -08004841}
4842
4843void PeerConnection::GetOptionsForAnswer(
4844 const RTCOfferAnswerOptions& offer_answer_options,
4845 cricket::MediaSessionOptions* session_options) {
4846 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4847
4848 if (IsUnifiedPlan()) {
4849 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4850 } else {
4851 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4852 }
4853
Steve Antonfa2260d2017-12-28 16:38:23 -08004854 // Intentionally unset the data channel type for RTP data channel. Otherwise
4855 // the RTP data channels would be successfully negotiated by default and the
4856 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4857 // We want to leave RTP data channels broken, so people won't try to use them.
4858 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4859 session_options->data_channel_type = data_channel_type();
4860 }
4861
Steve Antondcc3c022017-12-22 16:02:54 -08004862 // Apply ICE renomination flag.
4863 for (auto& options : session_options->media_description_options) {
4864 options.transport_options.enable_ice_renomination =
4865 configuration_.enable_ice_renomination;
4866 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004867
4868 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004869 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004870 session_options->pooled_ice_credentials =
4871 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4872 RTC_FROM_HERE,
4873 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4874 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004875
4876 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004877 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004878 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004879 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004880 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004881 if (!params) {
4882 continue;
4883 }
4884 options.transport_options.opaque_parameters = params;
4885 if ((use_datagram_transport_ &&
4886 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4887 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4888 (use_datagram_transport_for_data_channels_ &&
4889 options.type == cricket::MEDIA_TYPE_DATA)) {
4890 options.alt_protocol = params->protocol;
4891 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004892 }
4893 }
deadbeefab9b2d12015-10-14 11:33:11 -07004894}
4895
Steve Antondcc3c022017-12-22 16:02:54 -08004896void PeerConnection::GetOptionsForPlanBAnswer(
4897 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004898 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004899 // Figure out transceiver directional preferences.
4900 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4901 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4902
4903 // By default, generate sendrecv/recvonly m= sections. The direction is also
4904 // restricted by the direction in the offer.
4905 bool recv_audio = true;
4906 bool recv_video = true;
4907
4908 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004909 if (offer_answer_options.offer_to_receive_audio !=
4910 RTCOfferAnswerOptions::kUndefined) {
4911 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004912 }
Steve Antondcc3c022017-12-22 16:02:54 -08004913 if (offer_answer_options.offer_to_receive_video !=
4914 RTCOfferAnswerOptions::kUndefined) {
4915 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004916 }
4917
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004918 absl::optional<size_t> audio_index;
4919 absl::optional<size_t> video_index;
4920 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004921
4922 // Generate m= sections that match those in the offer.
4923 // Note that mediasession.cc will handle intersection our preferred
4924 // direction with the offered direction.
4925 GenerateMediaDescriptionOptions(
4926 remote_description(),
4927 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4928 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4929 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004930
4931 cricket::MediaDescriptionOptions* audio_media_description_options =
4932 !audio_index ? nullptr
4933 : &session_options->media_description_options[*audio_index];
4934 cricket::MediaDescriptionOptions* video_media_description_options =
4935 !video_index ? nullptr
4936 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004937
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004938 AddPlanBRtpSenderOptions(GetSendersInternal(),
4939 audio_media_description_options,
4940 video_media_description_options,
4941 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004942}
zhihuangaf388472016-11-02 16:49:48 -07004943
Steve Antondcc3c022017-12-22 16:02:54 -08004944void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4945 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4946 cricket::MediaSessionOptions* session_options) {
4947 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4948 // Answers) and 5.3.2 (Subsequent Answers).
4949 RTC_DCHECK(remote_description());
4950 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4951 for (const ContentInfo& content :
4952 remote_description()->description()->contents()) {
4953 cricket::MediaType media_type = content.media_description()->type();
4954 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4955 media_type == cricket::MEDIA_TYPE_VIDEO) {
4956 auto transceiver = GetAssociatedTransceiver(content.name);
4957 RTC_CHECK(transceiver);
4958 session_options->media_description_options.push_back(
4959 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4960 } else {
4961 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004962 // Reject all data sections if data channels are disabled.
4963 // Reject a data section if it has already been rejected.
4964 // Reject all data sections except for the first one.
4965 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4966 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004967 session_options->media_description_options.push_back(
4968 GetMediaDescriptionOptionsForRejectedData(content.name));
4969 } else {
4970 session_options->media_description_options.push_back(
4971 GetMediaDescriptionOptionsForActiveData(content.name));
4972 }
Steve Antondcc3c022017-12-22 16:02:54 -08004973 }
4974 }
htaa2a49d92016-03-04 02:51:39 -08004975}
4976
zhihuang1c378ed2017-08-17 14:10:50 -07004977void PeerConnection::GenerateMediaDescriptionOptions(
4978 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004979 RtpTransceiverDirection audio_direction,
4980 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004981 absl::optional<size_t>* audio_index,
4982 absl::optional<size_t>* video_index,
4983 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004984 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004985 for (const cricket::ContentInfo& content :
4986 session_desc->description()->contents()) {
4987 if (IsAudioContent(&content)) {
4988 // If we already have an audio m= section, reject this extra one.
4989 if (*audio_index) {
4990 session_options->media_description_options.push_back(
4991 cricket::MediaDescriptionOptions(
4992 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004993 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004994 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004995 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004996 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004997 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4998 content.name, audio_direction,
4999 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005000 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005001 }
5002 } else if (IsVideoContent(&content)) {
5003 // If we already have an video m= section, reject this extra one.
5004 if (*video_index) {
5005 session_options->media_description_options.push_back(
5006 cricket::MediaDescriptionOptions(
5007 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005008 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005009 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005010 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005011 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005012 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5013 content.name, video_direction,
5014 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005015 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005016 }
5017 } else {
5018 RTC_DCHECK(IsDataContent(&content));
5019 // If we already have an data m= section, reject this extra one.
5020 if (*data_index) {
5021 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005022 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005023 } else {
5024 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005025 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005026 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005027 }
5028 }
htaa2a49d92016-03-04 02:51:39 -08005029 }
deadbeefab9b2d12015-10-14 11:33:11 -07005030}
5031
Steve Antonfa2260d2017-12-28 16:38:23 -08005032cricket::MediaDescriptionOptions
5033PeerConnection::GetMediaDescriptionOptionsForActiveData(
5034 const std::string& mid) const {
5035 // Direction for data sections is meaningless, but legacy endpoints might
5036 // expect sendrecv.
5037 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5038 RtpTransceiverDirection::kSendRecv,
5039 /*stopped=*/false);
5040 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5041 return options;
5042}
5043
5044cricket::MediaDescriptionOptions
5045PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5046 const std::string& mid) const {
5047 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5048 RtpTransceiverDirection::kInactive,
5049 /*stopped=*/true);
5050 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5051 return options;
5052}
5053
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005054absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005055 switch (data_channel_type_) {
5056 case cricket::DCT_RTP:
5057 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005058 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005059 }
5060 return rtp_data_channel_->content_name();
5061 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005062 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005063 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5064 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5065 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005066 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005067 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005068 }
5069}
5070
Steve Anton4171afb2017-11-20 10:20:22 -08005071void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5072 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5073 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005074 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005075}
5076
Steve Anton4171afb2017-11-20 10:20:22 -08005077void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005078 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005079 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005080 cricket::MediaType media_type,
5081 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005082 RTC_DCHECK(!IsUnifiedPlan());
5083
Steve Anton4171afb2017-11-20 10:20:22 -08005084 std::vector<RtpSenderInfo>* current_senders =
5085 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005086
Steve Anton4171afb2017-11-20 10:20:22 -08005087 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005088 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005089 for (auto sender_it = current_senders->begin();
5090 sender_it != current_senders->end();
5091 /* incremented manually */) {
5092 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005093 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005094 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005095 std::string params_stream_id;
5096 if (params) {
5097 params_stream_id =
5098 (!params->first_stream_id().empty() ? params->first_stream_id()
5099 : kDefaultStreamId);
5100 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005101 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005102 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005103 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005104 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005105 sender_exists) {
5106 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005107 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005108 OnRemoteSenderRemoved(info, media_type);
5109 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005110 }
5111 }
5112
Steve Anton4171afb2017-11-20 10:20:22 -08005113 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005114 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005115 if (!params.has_ssrcs()) {
5116 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5117 // sender, this means it is coming from a Unified Plan endpoint,so we just
5118 // create a default.
5119 default_sender_needed = true;
5120 break;
5121 }
5122
Seth Hampson845e8782018-03-02 11:34:10 -08005123 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005124 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005125 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5126 // not supported in Plan B, we just take the first here and create the
5127 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005128 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005129 (!params.first_stream_id().empty() ? params.first_stream_id()
5130 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005131 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005132 uint32_t ssrc = params.first_ssrc();
5133
5134 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005135 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005136 if (!stream) {
5137 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005138 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005139 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005140 remote_streams_->AddStream(stream);
5141 new_streams->AddStream(stream);
5142 }
5143
Steve Anton4171afb2017-11-20 10:20:22 -08005144 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005145 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005146 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005147 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005148 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005149 }
5150 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005151
Steve Anton4171afb2017-11-20 10:20:22 -08005152 // Add default sender if necessary.
5153 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005154 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005155 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005156 if (!default_stream) {
5157 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005158 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005159 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005160 remote_streams_->AddStream(default_stream);
5161 new_streams->AddStream(default_stream);
5162 }
Steve Anton4171afb2017-11-20 10:20:22 -08005163 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5164 ? kDefaultAudioSenderId
5165 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005166 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005167 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005168 if (!default_sender_info) {
5169 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005170 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005171 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005172 }
5173 }
deadbeefab9b2d12015-10-14 11:33:11 -07005174}
5175
Steve Anton4171afb2017-11-20 10:20:22 -08005176void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5177 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005178 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5179 << " receiver for track_id=" << sender_info.sender_id
5180 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005181
Steve Anton3d954a62018-04-02 11:27:23 -07005182 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005183 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005184 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005185 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005186 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005187 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005188 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005189 }
5190}
5191
Steve Anton4171afb2017-11-20 10:20:22 -08005192void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5193 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005194 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5195 << " receiver for track_id=" << sender_info.sender_id
5196 << " and stream_id=" << sender_info.stream_id;
5197
Seth Hampson845e8782018-03-02 11:34:10 -08005198 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005199
Henrik Boström933d8b02017-10-10 10:05:16 -07005200 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005201 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005202 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5203 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005204 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005205 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005206 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005207 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005208 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005209 }
5210 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005211 // Stopping or destroying a VideoRtpReceiver will end the
5212 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005213 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005214 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005215 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005216 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005217 // There's no guarantee the track is still available, e.g. the track may
5218 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005219 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005220 }
5221 } else {
nisseede5da42017-01-12 05:15:36 -08005222 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005223 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005224 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005225 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005226 }
deadbeefab9b2d12015-10-14 11:33:11 -07005227}
5228
5229void PeerConnection::UpdateEndedRemoteMediaStreams() {
5230 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5231 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5232 MediaStreamInterface* stream = remote_streams_->at(i);
5233 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5234 streams_to_remove.push_back(stream);
5235 }
5236 }
5237
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005238 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005239 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005240 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005241 }
5242}
5243
Steve Anton4171afb2017-11-20 10:20:22 -08005244void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005245 const std::vector<cricket::StreamParams>& streams,
5246 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005247 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005248
Seth Hampson845e8782018-03-02 11:34:10 -08005249 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005250 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005251 for (auto sender_it = current_senders->begin();
5252 sender_it != current_senders->end();
5253 /* incremented manually */) {
5254 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005255 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005256 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5257 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005258 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005259 OnLocalSenderRemoved(info, media_type);
5260 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005261 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005262 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005263 }
5264 }
5265
Steve Anton4171afb2017-11-20 10:20:22 -08005266 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005267 for (const cricket::StreamParams& params : streams) {
5268 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005269 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005270 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005271 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005272 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005273 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005274 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005275 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005276 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005277 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005278 }
5279 }
5280}
5281
Steve Anton4171afb2017-11-20 10:20:22 -08005282void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5283 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005284 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005285 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005286 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005287 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5288 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005289 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005290 return;
5291 }
5292
deadbeeffac06552015-11-25 11:26:01 -08005293 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005294 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005295 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005296 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005297 }
deadbeeffac06552015-11-25 11:26:01 -08005298
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005299 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005300 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005301}
5302
Steve Anton4171afb2017-11-20 10:20:22 -08005303void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5304 cricket::MediaType media_type) {
5305 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005306 if (!sender) {
5307 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005308 // SessionDescriptions has been renegotiated.
5309 return;
5310 }
deadbeeffac06552015-11-25 11:26:01 -08005311
5312 // A sender has been removed from the SessionDescription but it's still
5313 // associated with the PeerConnection. This only occurs if the SDP doesn't
5314 // match with the calls to CreateSender, AddStream and RemoveStream.
5315 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005316 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005317 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005318 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005319 }
deadbeeffac06552015-11-25 11:26:01 -08005320
Steve Anton4171afb2017-11-20 10:20:22 -08005321 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005322}
5323
5324void PeerConnection::UpdateLocalRtpDataChannels(
5325 const cricket::StreamParamsVec& streams) {
5326 std::vector<std::string> existing_channels;
5327
5328 // Find new and active data channels.
5329 for (const cricket::StreamParams& params : streams) {
5330 // |it->sync_label| is actually the data channel label. The reason is that
5331 // we use the same naming of data channels as we do for
5332 // MediaStreams and Tracks.
5333 // For MediaStreams, the sync_label is the MediaStream label and the
5334 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005335 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005336 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005337 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005338 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005339 continue;
5340 }
5341 // Set the SSRC the data channel should use for sending.
5342 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5343 existing_channels.push_back(data_channel_it->first);
5344 }
5345
5346 UpdateClosingRtpDataChannels(existing_channels, true);
5347}
5348
5349void PeerConnection::UpdateRemoteRtpDataChannels(
5350 const cricket::StreamParamsVec& streams) {
5351 std::vector<std::string> existing_channels;
5352
5353 // Find new and active data channels.
5354 for (const cricket::StreamParams& params : streams) {
5355 // The data channel label is either the mslabel or the SSRC if the mslabel
5356 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005357 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005358 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005359 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005360 auto data_channel_it = rtp_data_channels_.find(label);
5361 if (data_channel_it == rtp_data_channels_.end()) {
5362 // This is a new data channel.
5363 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5364 } else {
5365 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5366 }
5367 existing_channels.push_back(label);
5368 }
5369
5370 UpdateClosingRtpDataChannels(existing_channels, false);
5371}
5372
5373void PeerConnection::UpdateClosingRtpDataChannels(
5374 const std::vector<std::string>& active_channels,
5375 bool is_local_update) {
5376 auto it = rtp_data_channels_.begin();
5377 while (it != rtp_data_channels_.end()) {
5378 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005379 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005380 ++it;
5381 continue;
5382 }
5383
5384 if (is_local_update) {
5385 data_channel->SetSendSsrc(0);
5386 } else {
5387 data_channel->RemotePeerRequestClose();
5388 }
5389
5390 if (data_channel->state() == DataChannel::kClosed) {
5391 rtp_data_channels_.erase(it);
5392 it = rtp_data_channels_.begin();
5393 } else {
5394 ++it;
5395 }
5396 }
5397}
5398
5399void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5400 uint32_t remote_ssrc) {
5401 rtc::scoped_refptr<DataChannel> channel(
5402 InternalCreateDataChannel(label, nullptr));
5403 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005404 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005405 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005406 return;
5407 }
5408 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005409 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5410 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005411 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005412}
5413
5414rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5415 const std::string& label,
5416 const InternalDataChannelInit* config) {
5417 if (IsClosed()) {
5418 return nullptr;
5419 }
Steve Anton75737c02017-11-06 10:37:17 -08005420 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005421 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005422 << "InternalCreateDataChannel: Data is not supported in this call.";
5423 return nullptr;
5424 }
5425 InternalDataChannelInit new_config =
5426 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005427 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005428 if (new_config.id < 0) {
5429 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005430 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005431 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005432 RTC_LOG(LS_ERROR)
5433 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005434 return nullptr;
5435 }
5436 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005437 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005438 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005439 return nullptr;
5440 }
5441 }
5442
Steve Anton75737c02017-11-06 10:37:17 -08005443 rtc::scoped_refptr<DataChannel> channel(
5444 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005445 if (!channel) {
5446 sid_allocator_.ReleaseSid(new_config.id);
5447 return nullptr;
5448 }
5449
5450 if (channel->data_channel_type() == cricket::DCT_RTP) {
5451 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005452 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5453 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005454 return nullptr;
5455 }
5456 rtp_data_channels_[channel->label()] = channel;
5457 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005458 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005459 sctp_data_channels_.push_back(channel);
5460 channel->SignalClosed.connect(this,
5461 &PeerConnection::OnSctpDataChannelClosed);
5462 }
5463
Steve Anton2d8609c2018-01-23 16:38:46 -08005464 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005465 return channel;
5466}
5467
5468bool PeerConnection::HasDataChannels() const {
5469 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5470}
5471
5472void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005473 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005474 for (const auto& channel : sctp_data_channels_) {
5475 if (channel->id() < 0) {
5476 int sid;
5477 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005478 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5479 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005480 continue;
5481 }
5482 channel->SetSctpSid(sid);
5483 }
5484 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005485 // Since closing modifies the list of channels, we have to do the actual
5486 // closing outside the loop.
5487 for (const auto& channel : channels_to_close) {
5488 channel->CloseAbruptly();
5489 }
deadbeefab9b2d12015-10-14 11:33:11 -07005490}
5491
5492void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005493 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005494 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5495 ++it) {
5496 if (it->get() == channel) {
5497 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005498 // After the closing procedure is done, it's safe to use this ID for
5499 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005500 sid_allocator_.ReleaseSid(channel->id());
5501 }
deadbeefbd292462015-12-14 18:15:29 -08005502 // Since this method is triggered by a signal from the DataChannel,
5503 // we can't free it directly here; we need to free it asynchronously.
5504 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005505 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005506 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5507 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005508 return;
5509 }
5510 }
5511}
5512
deadbeefab9b2d12015-10-14 11:33:11 -07005513void PeerConnection::OnDataChannelDestroyed() {
5514 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5515 // DataChannel may callback to us and try to modify the list.
5516 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5517 temp_rtp_dcs.swap(rtp_data_channels_);
5518 for (const auto& kv : temp_rtp_dcs) {
5519 kv.second->OnTransportChannelDestroyed();
5520 }
5521
5522 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5523 temp_sctp_dcs.swap(sctp_data_channels_);
5524 for (const auto& channel : temp_sctp_dcs) {
5525 channel->OnTransportChannelDestroyed();
5526 }
5527}
5528
5529void PeerConnection::OnDataChannelOpenMessage(
5530 const std::string& label,
5531 const InternalDataChannelInit& config) {
5532 rtc::scoped_refptr<DataChannel> channel(
5533 InternalCreateDataChannel(label, &config));
5534 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005535 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005536 return;
5537 }
5538
deadbeefa601f5c2016-06-06 14:27:39 -07005539 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5540 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005541 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005542 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005543}
5544
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005545bool PeerConnection::HandleOpenMessage_s(
5546 const cricket::ReceiveDataParams& params,
5547 const rtc::CopyOnWriteBuffer& buffer) {
5548 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5549 // Received OPEN message; parse and signal that a new data channel should
5550 // be created.
5551 std::string label;
5552 InternalDataChannelInit config;
5553 config.id = params.ssrc;
5554 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5555 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5556 << params.ssrc;
5557 return true;
5558 }
5559 config.open_handshake_role = InternalDataChannelInit::kAcker;
5560 OnDataChannelOpenMessage(label, config);
5561 return true;
5562 }
5563 return false;
5564}
5565
Steve Anton4171afb2017-11-20 10:20:22 -08005566rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5567PeerConnection::GetAudioTransceiver() const {
5568 // This method only works with Plan B SDP, where there is a single
5569 // audio/video transceiver.
5570 RTC_DCHECK(!IsUnifiedPlan());
5571 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005572 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005573 return transceiver;
5574 }
5575 }
5576 RTC_NOTREACHED();
5577 return nullptr;
5578}
5579
5580rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5581PeerConnection::GetVideoTransceiver() const {
5582 // This method only works with Plan B SDP, where there is a single
5583 // audio/video transceiver.
5584 RTC_DCHECK(!IsUnifiedPlan());
5585 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005586 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005587 return transceiver;
5588 }
5589 }
5590 RTC_NOTREACHED();
5591 return nullptr;
5592}
5593
5594// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5595// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005596bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005597 switch (type) {
5598 case cricket::MEDIA_TYPE_AUDIO:
5599 return !GetAudioTransceiver()->internal()->senders().empty();
5600 case cricket::MEDIA_TYPE_VIDEO:
5601 return !GetVideoTransceiver()->internal()->senders().empty();
5602 case cricket::MEDIA_TYPE_DATA:
5603 return false;
5604 }
5605 RTC_NOTREACHED();
5606 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005607}
5608
Steve Anton4171afb2017-11-20 10:20:22 -08005609rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5610PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005611 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005612 for (auto sender : transceiver->internal()->senders()) {
5613 if (sender->track() == track) {
5614 return sender;
5615 }
5616 }
5617 }
5618 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005619}
5620
Steve Anton4171afb2017-11-20 10:20:22 -08005621rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5622PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005623 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005624 for (auto sender : transceiver->internal()->senders()) {
5625 if (sender->id() == sender_id) {
5626 return sender;
5627 }
5628 }
5629 }
5630 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005631}
5632
Steve Anton4171afb2017-11-20 10:20:22 -08005633rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5634PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005635 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005636 for (auto receiver : transceiver->internal()->receivers()) {
5637 if (receiver->id() == receiver_id) {
5638 return receiver;
5639 }
5640 }
5641 }
5642 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005643}
5644
Steve Anton4171afb2017-11-20 10:20:22 -08005645std::vector<PeerConnection::RtpSenderInfo>*
5646PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5647 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5648 media_type == cricket::MEDIA_TYPE_VIDEO);
5649 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5650 ? &remote_audio_sender_infos_
5651 : &remote_video_sender_infos_;
5652}
5653
5654std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005655 cricket::MediaType media_type) {
5656 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5657 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005658 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5659 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005660}
5661
Steve Anton4171afb2017-11-20 10:20:22 -08005662const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5663 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005664 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005665 const std::string sender_id) const {
5666 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005667 if (sender_info.stream_id == stream_id &&
5668 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005669 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005670 }
5671 }
5672 return nullptr;
5673}
5674
5675DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5676 for (const auto& channel : sctp_data_channels_) {
5677 if (channel->id() == sid) {
5678 return channel;
5679 }
5680 }
5681 return nullptr;
5682}
5683
Karl Wibergfb3be392019-03-22 14:13:22 +01005684PeerConnection::InitializePortAllocatorResult
5685PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005686 const cricket::ServerAddresses& stun_servers,
5687 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005688 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005689 RTC_DCHECK_RUN_ON(network_thread());
5690
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005691 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005692 // To handle both internal and externally created port allocator, we will
5693 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005694 int port_allocator_flags = port_allocator_->flags();
5695 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5696 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5697 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005698 // If the disable-IPv6 flag was specified, we'll not override it
5699 // by experiment.
5700 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005701 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005702 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5703 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005704 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005705 }
5706
zhihuangb09b3f92017-03-07 14:40:51 -08005707 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005708 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005709 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005710 }
5711
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005712 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005713 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005714 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005715 }
5716
honghaiz60347052016-05-31 18:29:12 -07005717 if (configuration.candidate_network_policy ==
5718 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005719 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005720 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005721 }
5722
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005723 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005724 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005725 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5726 }
5727
Karl Wibergfb3be392019-03-22 14:13:22 +01005728 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005729 // No step delay is used while allocating ports.
5730 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005731 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005732 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005733 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005734
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005735 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005736 for (auto& turn_server : turn_servers_copy) {
5737 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005738 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005739 // Call this last since it may create pooled allocator sessions using the
5740 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005741 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005742 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005743 configuration.ice_candidate_pool_size,
5744 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005745 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005746
5747 InitializePortAllocatorResult res;
5748 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5749 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005750}
5751
deadbeef91dd5672016-05-18 16:55:30 -07005752bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005753 const cricket::ServerAddresses& stun_servers,
5754 const std::vector<cricket::RelayServerConfig>& turn_servers,
5755 IceTransportsType type,
5756 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005757 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005758 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005759 absl::optional<int> stun_candidate_keepalive_interval,
5760 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005761 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005762 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005763 // According to JSEP, after setLocalDescription, changing the candidate pool
5764 // size is not allowed, and changing the set of ICE servers will not result
5765 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005766 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005767 port_allocator_->FreezeCandidatePool();
5768 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005769 // Add the custom tls turn servers if they exist.
5770 auto turn_servers_copy = turn_servers;
5771 for (auto& turn_server : turn_servers_copy) {
5772 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5773 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005774 // Call this last since it may create pooled allocator sessions using the
5775 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005776 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005777 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005778 turn_port_prune_policy, turn_customizer,
5779 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005780}
5781
Steve Antonba818672017-11-06 10:21:57 -08005782cricket::ChannelManager* PeerConnection::channel_manager() const {
5783 return factory_->channel_manager();
5784}
5785
Elad Alon99c3fe52017-10-13 16:29:40 +02005786bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005787 std::unique_ptr<RtcEventLogOutput> output,
5788 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005789 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005790 if (!event_log_) {
5791 return false;
5792 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005793 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005794}
5795
5796void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005797 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005798 if (event_log_) {
5799 event_log_->StopLogging();
5800 }
ivoc14d5dbe2016-07-04 07:06:55 -07005801}
nisseeaabdf62017-05-05 02:23:02 -07005802
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005803cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005804 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005805 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005806 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005807 if (channel && channel->content_name() == content_name) {
5808 return channel;
5809 }
Steve Anton75737c02017-11-06 10:37:17 -08005810 }
5811 if (rtp_data_channel() &&
5812 rtp_data_channel()->content_name() == content_name) {
5813 return rtp_data_channel();
5814 }
5815 return nullptr;
5816}
5817
5818bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005819 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005820 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005821 RTC_LOG(LS_INFO)
5822 << "Local and Remote descriptions must be applied 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 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005826 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005827 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005828 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005829 return false;
5830 }
5831
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005832 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005833 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005834 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005835 if (!dtls_role && is_caller_.has_value()) {
5836 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5837 }
Zhi Huange830e682018-03-30 10:48:35 -07005838 *role = *dtls_role;
5839 return true;
5840 }
5841 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005842}
5843
5844bool PeerConnection::GetSslRole(const std::string& content_name,
5845 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005846 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005847 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005848 RTC_LOG(LS_INFO)
5849 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005850 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005851 return false;
5852 }
5853
Zhi Huange830e682018-03-30 10:48:35 -07005854 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5855 if (dtls_role) {
5856 *role = *dtls_role;
5857 return true;
5858 }
5859 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005860}
5861
Steve Antonf8470812017-12-04 10:46:21 -08005862void PeerConnection::SetSessionError(SessionError error,
5863 const std::string& error_desc) {
5864 RTC_DCHECK_RUN_ON(signaling_thread());
5865 if (error != session_error_) {
5866 session_error_ = error;
5867 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005868 }
5869}
5870
Zhi Huange830e682018-03-30 10:48:35 -07005871RTCError PeerConnection::UpdateSessionState(
5872 SdpType type,
5873 cricket::ContentSource source,
5874 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005875 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005876
5877 // If there's already a pending error then no state transition should happen.
5878 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005879 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005880
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005881 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005882 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005883 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005884 }
5885
5886 // Update the signaling state according to the specified state machine (see
5887 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005888 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005889 ChangeSignalingState(source == cricket::CS_LOCAL
5890 ? PeerConnectionInterface::kHaveLocalOffer
5891 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005892 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005893 ChangeSignalingState(source == cricket::CS_LOCAL
5894 ? PeerConnectionInterface::kHaveLocalPrAnswer
5895 : PeerConnectionInterface::kHaveRemotePrAnswer);
5896 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005897 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005898 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03005899 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005900 }
5901
5902 // Update internal objects according to the session description's media
5903 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005904 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005905 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005906 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005907 }
5908
Steve Anton8a006912017-12-04 15:25:56 -08005909 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005910}
5911
Steve Anton8a006912017-12-04 15:25:56 -08005912RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005913 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005914 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005915 const SessionDescriptionInterface* sdesc =
5916 (source == cricket::CS_LOCAL ? local_description()
5917 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005918 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005919
5920 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005921 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005922 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005923 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005924 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005925 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005926 continue;
5927 }
5928 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005929 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005930 if (!content_desc) {
5931 continue;
5932 }
5933 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005934 bool success = (source == cricket::CS_LOCAL)
5935 ? channel->SetLocalContent(content_desc, type, &error)
5936 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005937 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005938 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005939 }
5940 }
5941
5942 // If using the RtpDataChannel, push down the new SDP section for it too.
5943 if (rtp_data_channel_) {
5944 const ContentInfo* data_content =
5945 cricket::GetFirstDataContent(sdesc->description());
5946 if (data_content && !data_content->rejected) {
5947 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005948 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005949 if (data_desc) {
5950 std::string error;
5951 bool success =
5952 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005953 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005954 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005955 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005956 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005957 }
Steve Anton75737c02017-11-06 10:37:17 -08005958 }
5959 }
5960 }
Steve Antoned10bd92017-12-05 10:52:59 -08005961
Steve Anton75737c02017-11-06 10:37:17 -08005962 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5963 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005964 if (sctp_mid_ && local_description() && remote_description()) {
5965 rtc::scoped_refptr<SctpTransport> sctp_transport =
5966 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005967 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5968 local_description()->description());
5969 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5970 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005971 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005972 int max_message_size;
5973 // A remote max message size of zero means "any size supported".
5974 // We configure the connection with our own max message size.
5975 if (remote_sctp_description->max_message_size() == 0) {
5976 max_message_size = local_sctp_description->max_message_size();
5977 } else {
5978 max_message_size =
5979 std::min(local_sctp_description->max_message_size(),
5980 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005981 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005982 sctp_transport->Start(local_sctp_description->port(),
5983 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005984 }
Steve Anton75737c02017-11-06 10:37:17 -08005985 }
Steve Antoned10bd92017-12-05 10:52:59 -08005986
Steve Anton8a006912017-12-04 15:25:56 -08005987 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005988}
5989
Steve Anton8a006912017-12-04 15:25:56 -08005990RTCError PeerConnection::PushdownTransportDescription(
5991 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005992 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005993 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005994
Zhi Huange830e682018-03-30 10:48:35 -07005995 if (source == cricket::CS_LOCAL) {
5996 const SessionDescriptionInterface* sdesc = local_description();
5997 RTC_DCHECK(sdesc);
5998 return transport_controller_->SetLocalDescription(type,
5999 sdesc->description());
6000 } else {
6001 const SessionDescriptionInterface* sdesc = remote_description();
6002 RTC_DCHECK(sdesc);
6003 return transport_controller_->SetRemoteDescription(type,
6004 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006005 }
Steve Anton75737c02017-11-06 10:37:17 -08006006}
6007
6008bool PeerConnection::GetTransportDescription(
6009 const SessionDescription* description,
6010 const std::string& content_name,
6011 cricket::TransportDescription* tdesc) {
6012 if (!description || !tdesc) {
6013 return false;
6014 }
6015 const TransportInfo* transport_info =
6016 description->GetTransportInfoByName(content_name);
6017 if (!transport_info) {
6018 return false;
6019 }
6020 *tdesc = transport_info->description;
6021 return true;
6022}
6023
Steve Anton75737c02017-11-06 10:37:17 -08006024cricket::IceConfig PeerConnection::ParseIceConfig(
6025 const PeerConnectionInterface::RTCConfiguration& config) const {
6026 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006027 switch (config.continual_gathering_policy) {
6028 case PeerConnectionInterface::GATHER_ONCE:
6029 gathering_policy = cricket::GATHER_ONCE;
6030 break;
6031 case PeerConnectionInterface::GATHER_CONTINUALLY:
6032 gathering_policy = cricket::GATHER_CONTINUALLY;
6033 break;
6034 default:
6035 RTC_NOTREACHED();
6036 gathering_policy = cricket::GATHER_ONCE;
6037 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006038
Steve Anton75737c02017-11-06 10:37:17 -08006039 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006040 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6041 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006042 ice_config.prioritize_most_likely_candidate_pairs =
6043 config.prioritize_most_likely_ice_candidate_pairs;
6044 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006045 RTCConfigurationToIceConfigOptionalInt(
6046 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006047 ice_config.continual_gathering_policy = gathering_policy;
6048 ice_config.presume_writable_when_fully_relayed =
6049 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006050 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6051 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006052 ice_config.ice_check_interval_strong_connectivity =
6053 config.ice_check_interval_strong_connectivity;
6054 ice_config.ice_check_interval_weak_connectivity =
6055 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006056 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006057 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6058 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006059 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006060 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006061 ice_config.regather_all_networks_interval_range =
6062 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006063 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006064 return ice_config;
6065}
6066
Steve Anton75737c02017-11-06 10:37:17 -08006067bool PeerConnection::SendData(const cricket::SendDataParams& params,
6068 const rtc::CopyOnWriteBuffer& payload,
6069 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006070 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006071 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006072 SendDataParams send_params;
6073 send_params.type = ToWebrtcDataMessageType(params.type);
6074 send_params.ordered = params.ordered;
6075 if (params.max_rtx_count >= 0) {
6076 send_params.max_rtx_count = params.max_rtx_count;
6077 } else if (params.max_rtx_ms >= 0) {
6078 send_params.max_rtx_ms = params.max_rtx_ms;
6079 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006080
6081 RTCError error = network_thread()->Invoke<RTCError>(
6082 RTC_FROM_HERE, [this, params, send_params, payload] {
6083 return data_channel_transport_->SendData(params.sid, send_params,
6084 payload);
6085 });
6086
6087 if (error.ok()) {
6088 *result = cricket::SendDataResult::SDR_SUCCESS;
6089 return true;
6090 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6091 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6092 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6093 *result = cricket::SendDataResult::SDR_BLOCK;
6094 return false;
6095 }
6096 *result = cricket::SendDataResult::SDR_ERROR;
6097 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006098 } else if (rtp_data_channel_) {
6099 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006100 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006101 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6102 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006103}
6104
6105bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006106 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006107 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006108 // Don't log an error here, because DataChannels are expected to call
6109 // ConnectDataChannel in this state. It's the only way to initially tell
6110 // whether or not the underlying transport is ready.
6111 return false;
6112 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006113 if (data_channel_transport_) {
6114 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6115 &DataChannel::OnChannelReady);
6116 SignalDataChannelTransportReceivedData_s.connect(
6117 webrtc_data_channel, &DataChannel::OnDataReceived);
6118 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006119 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006120 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006121 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006122 }
6123 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006124 rtp_data_channel_->SignalReadyToSendData.connect(
6125 webrtc_data_channel, &DataChannel::OnChannelReady);
6126 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6127 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006128 }
Steve Anton75737c02017-11-06 10:37:17 -08006129 return true;
6130}
6131
6132void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006133 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006134 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006135 RTC_LOG(LS_ERROR)
6136 << "DisconnectDataChannel called when rtp_data_channel_ and "
6137 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006138 return;
6139 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006140 if (data_channel_transport_) {
6141 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6142 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6143 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6144 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6145 }
6146 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006147 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6148 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006149 }
Steve Anton75737c02017-11-06 10:37:17 -08006150}
6151
6152void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006153 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006154 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6155 if (data_channel_transport_) {
6156 data_channel_transport_->OpenChannel(sid);
6157 }
6158 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006159 }
Steve Anton75737c02017-11-06 10:37:17 -08006160}
6161
6162void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006163 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006164 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6165 if (data_channel_transport_) {
6166 data_channel_transport_->CloseChannel(sid);
6167 }
6168 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006169 }
Steve Anton75737c02017-11-06 10:37:17 -08006170}
6171
6172bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006173 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006174 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006175 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006176}
6177
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006178void PeerConnection::OnDataReceived(int channel_id,
6179 DataMessageType type,
6180 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006181 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006182 cricket::ReceiveDataParams params;
6183 params.sid = channel_id;
6184 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006185 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006186 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6187 RTC_DCHECK_RUN_ON(signaling_thread());
6188 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006189 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006190 }
6191 });
6192}
6193
6194void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006195 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006196 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006197 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6198 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006199 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006200 });
6201}
6202
6203void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006204 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006205 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006206 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6207 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006208 SignalDataChannelTransportChannelClosed_s(channel_id);
6209 });
6210}
6211
6212void PeerConnection::OnReadyToSend() {
6213 RTC_DCHECK_RUN_ON(network_thread());
6214 data_channel_transport_invoker_->AsyncInvoke<void>(
6215 RTC_FROM_HERE, signaling_thread(), [this] {
6216 RTC_DCHECK_RUN_ON(signaling_thread());
6217 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006218 SignalDataChannelTransportWritable_s(
6219 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006220 });
6221}
6222
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006223absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006224 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006225 if (sctp_mid_ && transport_controller_) {
6226 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6227 if (dtls_transport) {
6228 return dtls_transport->transport_name();
6229 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006230 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006231 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006232 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006233}
6234
Qingsi Wang72a43a12018-02-20 16:03:18 -08006235cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6236 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006237 network_thread()->Invoke<void>(
6238 RTC_FROM_HERE,
6239 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6240 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006241 return candidate_states_list;
6242}
6243
Steve Anton5dfde182018-02-06 10:34:40 -08006244std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6245 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006246 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006247 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006248 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006249 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006250 if (channel) {
6251 transport_names_by_mid[channel->content_name()] =
6252 channel->transport_name();
6253 }
Steve Anton75737c02017-11-06 10:37:17 -08006254 }
Steve Anton5dfde182018-02-06 10:34:40 -08006255 if (rtp_data_channel_) {
6256 transport_names_by_mid[rtp_data_channel_->content_name()] =
6257 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006259 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006260 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006261 RTC_DCHECK(transport_name);
6262 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006263 }
Steve Anton5dfde182018-02-06 10:34:40 -08006264 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006265}
6266
Steve Anton5dfde182018-02-06 10:34:40 -08006267std::map<std::string, cricket::TransportStats>
6268PeerConnection::GetTransportStatsByNames(
6269 const std::set<std::string>& transport_names) {
6270 if (!network_thread()->IsCurrent()) {
6271 return network_thread()
6272 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6273 RTC_FROM_HERE,
6274 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006276 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006277 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6278 for (const std::string& transport_name : transport_names) {
6279 cricket::TransportStats transport_stats;
6280 bool success =
6281 transport_controller_->GetStats(transport_name, &transport_stats);
6282 if (success) {
6283 transport_stats_by_name[transport_name] = std::move(transport_stats);
6284 } else {
6285 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6286 << transport_name;
6287 }
6288 }
6289 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006290}
6291
6292bool PeerConnection::GetLocalCertificate(
6293 const std::string& transport_name,
6294 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006295 if (!certificate) {
6296 return false;
6297 }
6298 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6299 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006300}
6301
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006302std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006303 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006304 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006305}
6306
6307cricket::DataChannelType PeerConnection::data_channel_type() const {
6308 return data_channel_type_;
6309}
6310
6311bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006312 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006313 return pending_ice_restarts_.find(content_name) !=
6314 pending_ice_restarts_.end();
6315}
6316
Steve Anton75737c02017-11-06 10:37:17 -08006317bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6318 return transport_controller_->NeedsIceRestart(content_name);
6319}
6320
6321void PeerConnection::OnCertificateReady(
6322 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6323 transport_controller_->SetLocalCertificate(certificate);
6324}
6325
6326void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006327 SetSessionError(SessionError::kTransport,
6328 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006329}
6330
Alex Loiko9289eda2018-11-23 16:18:59 +00006331void PeerConnection::OnTransportControllerConnectionState(
6332 cricket::IceConnectionState state) {
6333 switch (state) {
6334 case cricket::kIceConnectionConnecting:
6335 // If the current state is Connected or Completed, then there were
6336 // writable channels but now there are not, so the next state must
6337 // be Disconnected.
6338 // kIceConnectionConnecting is currently used as the default,
6339 // un-connected state by the TransportController, so its only use is
6340 // detecting disconnections.
6341 if (ice_connection_state_ ==
6342 PeerConnectionInterface::kIceConnectionConnected ||
6343 ice_connection_state_ ==
6344 PeerConnectionInterface::kIceConnectionCompleted) {
6345 SetIceConnectionState(
6346 PeerConnectionInterface::kIceConnectionDisconnected);
6347 }
6348 break;
6349 case cricket::kIceConnectionFailed:
6350 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6351 break;
6352 case cricket::kIceConnectionConnected:
6353 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6354 "all transports are writable.";
6355 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6356 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6357 break;
6358 case cricket::kIceConnectionCompleted:
6359 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6360 "all transports are complete.";
6361 if (ice_connection_state_ !=
6362 PeerConnectionInterface::kIceConnectionConnected) {
6363 // If jumping directly from "checking" to "connected",
6364 // signal "connected" first.
6365 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6366 }
6367 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6368 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6369 ReportTransportStats();
6370 break;
6371 default:
6372 RTC_NOTREACHED();
6373 }
6374}
6375
Steve Anton75737c02017-11-06 10:37:17 -08006376void PeerConnection::OnTransportControllerCandidatesGathered(
6377 const std::string& transport_name,
6378 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006379 int sdp_mline_index;
6380 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006381 RTC_LOG(LS_ERROR)
6382 << "OnTransportControllerCandidatesGathered: content name "
6383 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006384 return;
6385 }
6386
6387 for (cricket::Candidates::const_iterator citer = candidates.begin();
6388 citer != candidates.end(); ++citer) {
6389 // Use transport_name as the candidate media id.
6390 std::unique_ptr<JsepIceCandidate> candidate(
6391 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6392 if (local_description()) {
6393 mutable_local_description()->AddCandidate(candidate.get());
6394 }
6395 OnIceCandidate(std::move(candidate));
6396 }
6397}
6398
Eldar Relloda13ea22019-06-01 12:23:43 +03006399void PeerConnection::OnTransportControllerCandidateError(
6400 const cricket::IceCandidateErrorEvent& event) {
6401 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6402 event.error_text);
6403}
6404
Steve Anton75737c02017-11-06 10:37:17 -08006405void PeerConnection::OnTransportControllerCandidatesRemoved(
6406 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006407 // Sanity check.
6408 for (const cricket::Candidate& candidate : candidates) {
6409 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006410 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006411 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006412 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006413 return;
6414 }
6415 }
6416
6417 if (local_description()) {
6418 mutable_local_description()->RemoveCandidates(candidates);
6419 }
6420 OnIceCandidatesRemoved(candidates);
6421}
6422
Alex Drake00c7ecf2019-08-06 10:54:47 -07006423void PeerConnection::OnTransportControllerCandidateChanged(
6424 const cricket::CandidatePairChangeEvent& event) {
6425 OnSelectedCandidatePairChanged(event);
6426}
6427
Steve Anton75737c02017-11-06 10:37:17 -08006428void PeerConnection::OnTransportControllerDtlsHandshakeError(
6429 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006430 RTC_HISTOGRAM_ENUMERATION(
6431 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6432 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006433}
6434
Steve Antoned10bd92017-12-05 10:52:59 -08006435void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006436 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006437 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006438 if (channel && !channel->enabled()) {
6439 channel->Enable(true);
6440 }
Steve Anton75737c02017-11-06 10:37:17 -08006441 }
6442
Steve Anton4171afb2017-11-20 10:20:22 -08006443 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006444 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006445 }
Steve Anton75737c02017-11-06 10:37:17 -08006446}
6447
6448// Returns the media index for a local ice candidate given the content name.
6449bool PeerConnection::GetLocalCandidateMediaIndex(
6450 const std::string& content_name,
6451 int* sdp_mline_index) {
6452 if (!local_description() || !sdp_mline_index) {
6453 return false;
6454 }
6455
6456 bool content_found = false;
6457 const ContentInfos& contents = local_description()->description()->contents();
6458 for (size_t index = 0; index < contents.size(); ++index) {
6459 if (contents[index].name == content_name) {
6460 *sdp_mline_index = static_cast<int>(index);
6461 content_found = true;
6462 break;
6463 }
6464 }
6465 return content_found;
6466}
6467
6468bool PeerConnection::UseCandidatesInSessionDescription(
6469 const SessionDescriptionInterface* remote_desc) {
6470 if (!remote_desc) {
6471 return true;
6472 }
6473 bool ret = true;
6474
6475 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6476 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6477 for (size_t n = 0; n < candidates->count(); ++n) {
6478 const IceCandidateInterface* candidate = candidates->at(n);
6479 bool valid = false;
6480 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6481 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006482 RTC_LOG(LS_INFO)
6483 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006484 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006485 }
6486 continue;
6487 }
6488 ret = UseCandidate(candidate);
6489 if (!ret) {
6490 break;
6491 }
6492 }
6493 }
6494 return ret;
6495}
6496
6497bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006498 RTCErrorOr<const cricket::ContentInfo*> result =
6499 FindContentInfo(remote_description(), candidate);
6500 if (!result.ok()) {
6501 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6502 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006503 return false;
6504 }
Steve Anton75737c02017-11-06 10:37:17 -08006505 std::vector<cricket::Candidate> candidates;
6506 candidates.push_back(candidate->candidate());
6507 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006508 RTCError error = transport_controller_->AddRemoteCandidates(
6509 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006510 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006511 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006512 // Candidates successfully submitted for checking.
6513 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6514 ice_connection_state_ ==
6515 PeerConnectionInterface::kIceConnectionDisconnected) {
6516 // If state is New, then the session has just gotten its first remote ICE
6517 // candidates, so go to Checking.
6518 // If state is Disconnected, the session is re-using old candidates or
6519 // receiving additional ones, so go to Checking.
6520 // If state is Connected, stay Connected.
6521 // TODO(bemasc): If state is Connected, and the new candidates are for a
6522 // newly added transport, then the state actually _should_ move to
6523 // checking. Add a way to distinguish that case.
6524 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6525 }
6526 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006527 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006528 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006529 }
6530 return true;
6531}
6532
Guido Urdaneta41633172019-05-23 20:12:29 +02006533RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6534 const SessionDescriptionInterface* description,
6535 const IceCandidateInterface* candidate) {
6536 if (candidate->sdp_mline_index() >= 0) {
6537 size_t mediacontent_index =
6538 static_cast<size_t>(candidate->sdp_mline_index());
6539 size_t content_size = description->description()->contents().size();
6540 if (mediacontent_index < content_size) {
6541 return &description->description()->contents()[mediacontent_index];
6542 } else {
6543 return RTCError(RTCErrorType::INVALID_RANGE,
6544 "Media line index (" +
6545 rtc::ToString(candidate->sdp_mline_index()) +
6546 ") out of range (number of mlines: " +
6547 rtc::ToString(content_size) + ").");
6548 }
6549 } else if (!candidate->sdp_mid().empty()) {
6550 auto& contents = description->description()->contents();
6551 auto it = absl::c_find_if(
6552 contents, [candidate](const cricket::ContentInfo& content_info) {
6553 return content_info.mid() == candidate->sdp_mid();
6554 });
6555 if (it == contents.end()) {
6556 return RTCError(
6557 RTCErrorType::INVALID_PARAMETER,
6558 "Mid " + candidate->sdp_mid() +
6559 " specified but no media section with that mid found.");
6560 } else {
6561 return &*it;
6562 }
6563 }
6564
6565 return RTCError(RTCErrorType::INVALID_PARAMETER,
6566 "Neither sdp_mline_index nor sdp_mid specified.");
6567}
6568
Steve Anton75737c02017-11-06 10:37:17 -08006569void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006570 // Destroy video channel first since it may have a pointer to the
6571 // voice channel.
6572 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006573 if (!video_info || video_info->rejected) {
6574 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006575 }
6576
Steve Anton6fec8802017-12-04 10:37:29 -08006577 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6578 if (!audio_info || audio_info->rejected) {
6579 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006580 }
6581
6582 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6583 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006584 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006585 }
6586}
6587
Steve Antondcc3c022017-12-22 16:02:54 -08006588RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6589 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006590 const cricket::ContentGroup* bundle_group = nullptr;
6591 if (configuration_.bundle_policy ==
6592 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006593 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006594 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006595 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6596 "max-bundle configured but session description "
6597 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006598 }
6599 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006600 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006601}
6602
6603RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006604 // Creating the media channels. Transports should already have been created
6605 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006606 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006607 if (voice && !voice->rejected &&
6608 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006609 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006610 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006611 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6612 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006613 }
6614 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6615 }
6616
Steve Antondcc3c022017-12-22 16:02:54 -08006617 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006618 if (video && !video->rejected &&
6619 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006620 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006621 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006622 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6623 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006624 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006625 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006626 }
6627
Steve Antondcc3c022017-12-22 16:02:54 -08006628 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006629 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006630 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006631 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006632 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6633 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006634 }
6635 }
6636
Steve Anton8a006912017-12-04 15:25:56 -08006637 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006638}
6639
Steve Anton4171afb2017-11-20 10:20:22 -08006640// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006641cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006642 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006643 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006644 MediaTransportConfig media_transport_config =
6645 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006646
Steve Anton75737c02017-11-06 10:37:17 -08006647 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006648 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006649 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6650 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006651 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006652 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006653 }
Steve Anton75737c02017-11-06 10:37:17 -08006654 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6655 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006656 voice_channel->SignalSentPacket.connect(this,
6657 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006658 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006659
Steve Antoneda6ccd2017-12-04 10:21:55 -08006660 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006661}
6662
Steve Anton4171afb2017-11-20 10:20:22 -08006663// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006664cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006665 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006666 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006667 MediaTransportConfig media_transport_config =
6668 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006669
Steve Anton75737c02017-11-06 10:37:17 -08006670 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006671 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006672 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6673 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006674 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006675 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006676 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006677 }
Steve Anton75737c02017-11-06 10:37:17 -08006678 video_channel->SignalDtlsSrtpSetupFailure.connect(
6679 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006680 video_channel->SignalSentPacket.connect(this,
6681 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006682 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006683
Steve Antoneda6ccd2017-12-04 10:21:55 -08006684 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006685}
6686
Zhi Huange830e682018-03-30 10:48:35 -07006687bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006688 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006689 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006690 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006691 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6692 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006693 if (!network_thread()->Invoke<bool>(
6694 RTC_FROM_HERE,
6695 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6696 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006697 return false;
6698 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006699
6700 // All non-RTP data channels must initialize |sctp_data_channels_|.
6701 for (const auto& channel : sctp_data_channels_) {
6702 channel->OnTransportChannelCreated();
6703 }
6704 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006705 case cricket::DCT_RTP:
6706 default:
6707 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6708 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6709 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006710 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006711 if (!rtp_data_channel_) {
6712 return false;
6713 }
6714 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6715 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6716 rtp_data_channel_->SignalSentPacket.connect(
6717 this, &PeerConnection::OnSentPacket_w);
6718 rtp_data_channel_->SetRtpTransport(rtp_transport);
6719 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006721 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006722}
6723
6724Call::Stats PeerConnection::GetCallStats() {
6725 if (!worker_thread()->IsCurrent()) {
6726 return worker_thread()->Invoke<Call::Stats>(
6727 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6728 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006729 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006730 if (call_) {
6731 return call_->GetStats();
6732 } else {
6733 return Call::Stats();
6734 }
6735}
6736
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006737bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006738 DataChannelTransportInterface* transport =
6739 transport_controller_->GetDataChannelTransport(mid);
6740 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006741 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006742 << "Data channel transport is not available for data channels, mid="
6743 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006744 return false;
6745 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006746 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006747
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006748 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02006749 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006750 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006751
6752 // Note: setting the data sink and checking initial state must be done last,
6753 // after setting up the data channel. Setting the data sink may trigger
6754 // callbacks to PeerConnection which require the transport to be completely
6755 // set up (eg. OnReadyToSend()).
6756 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006757 return true;
6758}
6759
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006760void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006761 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006762 return;
6763 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006764 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6765 << *sctp_mid_;
6766
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006767 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6768 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006769 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00006770 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006771 if (data_channel_transport_) {
6772 data_channel_transport_->SetDataSink(nullptr);
6773 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006774 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006775}
6776
Steve Anton75737c02017-11-06 10:37:17 -08006777// Returns false if bundle is enabled and rtcp_mux is disabled.
6778bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6779 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6780 if (!bundle_enabled)
6781 return true;
6782
6783 const cricket::ContentGroup* bundle_group =
6784 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6785 RTC_DCHECK(bundle_group != NULL);
6786
6787 const cricket::ContentInfos& contents = desc->contents();
6788 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6789 citer != contents.end(); ++citer) {
6790 const cricket::ContentInfo* content = (&*citer);
6791 RTC_DCHECK(content != NULL);
6792 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006793 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006794 if (!HasRtcpMuxEnabled(content))
6795 return false;
6796 }
6797 }
6798 // RTCP-MUX is enabled in all the contents.
6799 return true;
6800}
6801
6802bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006803 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006804}
6805
Steve Anton06817cd2018-12-18 15:55:30 -08006806static RTCError ValidateMids(const cricket::SessionDescription& description) {
6807 std::set<std::string> mids;
6808 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006809 if (content.name.empty()) {
6810 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6811 "A media section is missing a MID attribute.");
6812 }
Steve Anton06817cd2018-12-18 15:55:30 -08006813 if (!mids.insert(content.name).second) {
6814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6815 "Duplicate a=mid value '" + content.name + "'.");
6816 }
6817 }
6818 return RTCError::OK();
6819}
6820
Steve Anton8a006912017-12-04 15:25:56 -08006821RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006822 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006823 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006824 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006825 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006826 }
6827
6828 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006829 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006830 }
6831
Steve Anton3828c062017-12-06 10:34:51 -08006832 SdpType type = sdesc->GetType();
6833 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6834 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006835 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006836 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006837 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006838 }
6839
Steve Anton06817cd2018-12-18 15:55:30 -08006840 RTCError error = ValidateMids(*sdesc->description());
6841 if (!error.ok()) {
6842 return error;
6843 }
6844
Steve Anton75737c02017-11-06 10:37:17 -08006845 // Verify crypto settings.
6846 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006847 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6848 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006849 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006850 if (!crypto_error.ok()) {
6851 return crypto_error;
6852 }
Steve Anton75737c02017-11-06 10:37:17 -08006853 }
6854
6855 // Verify ice-ufrag and ice-pwd.
6856 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6858 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006859 }
6860
6861 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6863 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006864 }
6865
6866 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6867 // m-lines that do not rtcp-mux enabled.
6868
6869 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006870 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006871 // With an answer we want to compare the new answer session description with
6872 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006873 const cricket::SessionDescription* offer_desc =
6874 (source == cricket::CS_LOCAL) ? remote_description()->description()
6875 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006876 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6877 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6878 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006879 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6880 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006881 }
6882 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006883 // The re-offers should respect the order of m= sections in current
6884 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006885 // With a re-offer, either the current local or current remote descriptions
6886 // could be the most up to date, so we would like to check against both of
6887 // them if they exist. It could be the case that one of them has a 0 port
6888 // for a media section, but the other does not. This is important to check
6889 // against in the case that we are recycling an m= section.
6890 const cricket::SessionDescription* current_desc = nullptr;
6891 const cricket::SessionDescription* secondary_current_desc = nullptr;
6892 if (local_description()) {
6893 current_desc = local_description()->description();
6894 if (remote_description()) {
6895 secondary_current_desc = remote_description()->description();
6896 }
6897 } else if (remote_description()) {
6898 current_desc = remote_description()->description();
6899 }
Steve Anton75737c02017-11-06 10:37:17 -08006900 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006901 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6902 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006903 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6904 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006905 }
6906 }
6907
Steve Antonba42e992018-04-09 14:10:01 -07006908 if (IsUnifiedPlan()) {
6909 // Ensure that each audio and video media section has at most one
6910 // "StreamParams". This will return an error if receiving a session
6911 // description from a "Plan B" endpoint which adds multiple tracks of the
6912 // same type. With Unified Plan, there can only be at most one track per
6913 // media section.
6914 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006915 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006916 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6917 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6918 desc.streams().size() > 1u) {
6919 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6920 "Media section has more than one track specified "
6921 "with a=ssrc lines which is not supported with "
6922 "Unified Plan.");
6923 }
6924 }
6925 }
6926
Steve Anton8a006912017-12-04 15:25:56 -08006927 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006928}
6929
Steve Anton3828c062017-12-06 10:34:51 -08006930bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006931 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006932 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006933 return (state == PeerConnectionInterface::kStable) ||
6934 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006935 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006936 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006937 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6938 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6939 }
6940}
6941
Steve Anton3828c062017-12-06 10:34:51 -08006942bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006943 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006944 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006945 return (state == PeerConnectionInterface::kStable) ||
6946 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006947 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006948 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006949 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6950 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6951 }
6952}
6953
Steve Antonf8470812017-12-04 10:46:21 -08006954const char* PeerConnection::SessionErrorToString(SessionError error) const {
6955 switch (error) {
6956 case SessionError::kNone:
6957 return "ERROR_NONE";
6958 case SessionError::kContent:
6959 return "ERROR_CONTENT";
6960 case SessionError::kTransport:
6961 return "ERROR_TRANSPORT";
6962 }
6963 RTC_NOTREACHED();
6964 return "";
6965}
6966
Steve Anton75737c02017-11-06 10:37:17 -08006967std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006968 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006969 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6970 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006971 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006972}
6973
Steve Anton8e20f172018-03-06 10:55:04 -08006974void PeerConnection::ReportSdpFormatReceived(
6975 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006976 int num_audio_mlines = 0;
6977 int num_video_mlines = 0;
6978 int num_audio_tracks = 0;
6979 int num_video_tracks = 0;
6980 for (const ContentInfo& content : remote_offer.description()->contents()) {
6981 cricket::MediaType media_type = content.media_description()->type();
6982 int num_tracks = std::max(
6983 1, static_cast<int>(content.media_description()->streams().size()));
6984 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6985 num_audio_mlines += 1;
6986 num_audio_tracks += num_tracks;
6987 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6988 num_video_mlines += 1;
6989 num_video_tracks += num_tracks;
6990 }
6991 }
6992 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6993 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6994 format = kSdpFormatReceivedComplexUnifiedPlan;
6995 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6996 format = kSdpFormatReceivedComplexPlanB;
6997 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6998 format = kSdpFormatReceivedSimple;
6999 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007000 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7001 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007002}
7003
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007004void PeerConnection::ReportIceCandidateCollected(
7005 const cricket::Candidate& candidate) {
7006 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7007 if (candidate.address().IsPrivateIP()) {
7008 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7009 }
7010 if (candidate.address().IsUnresolvedIP()) {
7011 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7012 }
7013 if (candidate.address().family() == AF_INET6) {
7014 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7015 }
7016}
7017
7018void PeerConnection::ReportRemoteIceCandidateAdded(
7019 const cricket::Candidate& candidate) {
7020 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7021 if (candidate.address().IsPrivateIP()) {
7022 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7023 }
7024 if (candidate.address().IsUnresolvedIP()) {
7025 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7026 }
7027 if (candidate.address().family() == AF_INET6) {
7028 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7029 }
7030}
7031
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007032void PeerConnection::NoteUsageEvent(UsageEvent event) {
7033 RTC_DCHECK_RUN_ON(signaling_thread());
7034 usage_event_accumulator_ |= static_cast<int>(event);
7035}
7036
7037void PeerConnection::ReportUsagePattern() const {
7038 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007039 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7040 usage_event_accumulator_,
7041 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007042 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007043 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007044 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7045 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007046 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007047 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7048 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7049 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7050 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007051 // If called after close(), we can't report, because observer may have
7052 // been deallocated, and therefore pointer is null. Write to log instead.
7053 if (observer_) {
7054 Observer()->OnInterestingUsage(usage_event_accumulator_);
7055 } else {
7056 RTC_LOG(LS_INFO) << "Interesting usage signature "
7057 << usage_event_accumulator_
7058 << " observed after observer shutdown";
7059 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007060 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007061}
7062
Steve Anton0ffaaa22018-02-23 10:31:30 -08007063void PeerConnection::ReportNegotiatedSdpSemantics(
7064 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007065 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007066 switch (answer.description()->msid_signaling()) {
7067 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007068 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007069 break;
7070 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007071 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007072 break;
7073 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007074 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007075 break;
7076 case cricket::kMsidSignalingMediaSection |
7077 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007078 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007079 break;
7080 default:
7081 RTC_NOTREACHED();
7082 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007083 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7084 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007085}
7086
Steve Anton75737c02017-11-06 10:37:17 -08007087// We need to check the local/remote description for the Transport instead of
7088// the session, because a new Transport added during renegotiation may have
7089// them unset while the session has them set from the previous negotiation.
7090// Not doing so may trigger the auto generation of transport description and
7091// mess up DTLS identity information, ICE credential, etc.
7092bool PeerConnection::ReadyToUseRemoteCandidate(
7093 const IceCandidateInterface* candidate,
7094 const SessionDescriptionInterface* remote_desc,
7095 bool* valid) {
7096 *valid = true;
7097
7098 const SessionDescriptionInterface* current_remote_desc =
7099 remote_desc ? remote_desc : remote_description();
7100
7101 if (!current_remote_desc) {
7102 return false;
7103 }
7104
Guido Urdaneta41633172019-05-23 20:12:29 +02007105 RTCErrorOr<const cricket::ContentInfo*> result =
7106 FindContentInfo(current_remote_desc, candidate);
7107 if (!result.ok()) {
7108 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7109 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007110
7111 *valid = false;
7112 return false;
7113 }
7114
Guido Urdaneta41633172019-05-23 20:12:29 +02007115 std::string transport_name = GetTransportName(result.value()->name);
7116 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007117}
7118
7119bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007120 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007121 (dtls_enabled_ ||
7122 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007123}
7124
7125void PeerConnection::OnTransportControllerGatheringState(
7126 cricket::IceGatheringState state) {
7127 RTC_DCHECK(signaling_thread()->IsCurrent());
7128 if (state == cricket::kIceGatheringGathering) {
7129 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7130 } else if (state == cricket::kIceGatheringComplete) {
7131 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7132 }
7133}
7134
7135void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007136 std::map<std::string, std::set<cricket::MediaType>>
7137 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007138 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007139 if (transceiver->internal()->channel()) {
7140 const std::string& transport_name =
7141 transceiver->internal()->channel()->transport_name();
7142 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007143 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007144 }
Steve Anton75737c02017-11-06 10:37:17 -08007145 }
7146 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007147 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7148 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007149 }
Zhi Huange830e682018-03-30 10:48:35 -07007150
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007151 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007152 if (transport_name) {
7153 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007154 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007155 }
Zhi Huange830e682018-03-30 10:48:35 -07007156
Steve Antonc7b964c2018-02-01 14:39:45 -08007157 for (const auto& entry : media_types_by_transport_name) {
7158 const std::string& transport_name = entry.first;
7159 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007160 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007161 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007162 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007163 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007164 }
7165 }
7166}
7167// Walk through the ConnectionInfos to gather best connection usage
7168// for IPv4 and IPv6.
7169void PeerConnection::ReportBestConnectionState(
7170 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007171 for (const cricket::TransportChannelStats& channel_stats :
7172 stats.channel_stats) {
7173 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007174 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007175 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007176 continue;
7177 }
7178
Steve Antonc7b964c2018-02-01 14:39:45 -08007179 const cricket::Candidate& local = connection_info.local_candidate;
7180 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007181
7182 // Increment the counter for IceCandidatePairType.
7183 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7184 (local.type() == RELAY_PORT_TYPE &&
7185 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007186 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7187 GetIceCandidatePairCounter(local, remote),
7188 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007189 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007190 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7191 GetIceCandidatePairCounter(local, remote),
7192 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007193 } else {
7194 RTC_CHECK(0);
7195 }
Steve Anton75737c02017-11-06 10:37:17 -08007196
7197 // Increment the counter for IP type.
7198 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007199 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7200 kBestConnections_IPv4,
7201 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007202 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007203 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7204 kBestConnections_IPv6,
7205 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007206 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007207 RTC_CHECK(!local.address().hostname().empty() &&
7208 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007209 }
7210
7211 return;
7212 }
7213 }
7214}
7215
7216void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007217 const cricket::TransportStats& stats,
7218 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007219 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7220 return;
7221 }
7222
7223 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7224 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7225 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7226 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7227 return;
7228 }
7229
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007230 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7231 for (cricket::MediaType media_type : media_types) {
7232 switch (media_type) {
7233 case cricket::MEDIA_TYPE_AUDIO:
7234 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7235 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7236 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7237 break;
7238 case cricket::MEDIA_TYPE_VIDEO:
7239 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7240 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7241 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7242 break;
7243 case cricket::MEDIA_TYPE_DATA:
7244 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7245 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7246 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7247 break;
7248 default:
7249 RTC_NOTREACHED();
7250 continue;
7251 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007252 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007253 }
7254
7255 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7256 for (cricket::MediaType media_type : media_types) {
7257 switch (media_type) {
7258 case cricket::MEDIA_TYPE_AUDIO:
7259 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7260 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7261 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7262 break;
7263 case cricket::MEDIA_TYPE_VIDEO:
7264 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7265 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7266 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7267 break;
7268 case cricket::MEDIA_TYPE_DATA:
7269 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7270 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7271 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7272 break;
7273 default:
7274 RTC_NOTREACHED();
7275 continue;
7276 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007277 }
Steve Anton75737c02017-11-06 10:37:17 -08007278 }
7279}
7280
7281void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007282 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007283 RTC_DCHECK(call_);
7284 call_->OnSentPacket(sent_packet);
7285}
7286
7287const std::string PeerConnection::GetTransportName(
7288 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007289 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007290 if (channel) {
7291 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007292 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007293 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007294 RTC_DCHECK(sctp_mid_);
7295 if (content_name == *sctp_mid_) {
7296 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007297 }
7298 }
7299 // Return an empty string if failed to retrieve the transport name.
7300 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007301}
7302
Steve Anton6fec8802017-12-04 10:37:29 -08007303void PeerConnection::DestroyTransceiverChannel(
7304 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7305 transceiver) {
7306 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007307
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007308 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007309 if (channel) {
7310 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007311 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007312 }
7313}
7314
7315void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007316 if (rtp_data_channel_) {
7317 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007318 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007319 rtp_data_channel_ = nullptr;
7320 }
7321
7322 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7323 // grab a reference to this PeerConnection. If this is called from the
7324 // PeerConnection destructor, the RefCountedObject vtable will have already
7325 // been destroyed (since it is a subclass of PeerConnection) and using
7326 // rtc::Bind will cause "Pure virtual function called" error to appear.
7327
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007328 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007329 OnDataChannelDestroyed();
7330 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7331 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007332 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007333 });
7334 }
Steve Anton6fec8802017-12-04 10:37:29 -08007335}
7336
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007337void PeerConnection::DestroyChannelInterface(
7338 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007339 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007340 switch (channel->media_type()) {
7341 case cricket::MEDIA_TYPE_AUDIO:
7342 channel_manager()->DestroyVoiceChannel(
7343 static_cast<cricket::VoiceChannel*>(channel));
7344 break;
7345 case cricket::MEDIA_TYPE_VIDEO:
7346 channel_manager()->DestroyVideoChannel(
7347 static_cast<cricket::VideoChannel*>(channel));
7348 break;
7349 case cricket::MEDIA_TYPE_DATA:
7350 channel_manager()->DestroyRtpDataChannel(
7351 static_cast<cricket::RtpDataChannel*>(channel));
7352 break;
7353 default:
7354 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7355 break;
7356 }
Zhi Huange830e682018-03-30 10:48:35 -07007357}
Steve Anton6fec8802017-12-04 10:37:29 -08007358
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007359bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007360 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007361 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007362 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007363 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007364 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007365 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007366 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007367 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007368 auto base_channel = GetChannel(mid);
7369 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007370 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007371 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007372
Karl Wiberg5966c502019-02-21 23:55:09 +01007373 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007374 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007375 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007376
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007377 if (data_channel_transport_ && mid == sctp_mid_ &&
7378 data_channel_transport_ != data_channel_transport) {
7379 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7380 // it's bundled).
7381 data_channel_transport_->SetDataSink(nullptr);
7382 data_channel_transport_ = data_channel_transport;
7383 if (data_channel_transport) {
7384 data_channel_transport->SetDataSink(this);
7385
7386 // There's a new data channel transport. This needs to be signaled to the
7387 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7388 // necessary when bundling is applied.
7389 data_channel_transport_invoker_->AsyncInvoke<void>(
7390 RTC_FROM_HERE, signaling_thread(), [this] {
7391 RTC_DCHECK_RUN_ON(signaling_thread());
7392 for (auto channel : sctp_data_channels_) {
7393 channel->OnTransportChannelCreated();
7394 }
7395 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007396 }
7397 }
7398
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007399 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007400}
7401
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007402void PeerConnection::OnSetStreams() {
7403 RTC_DCHECK_RUN_ON(signaling_thread());
7404 if (IsUnifiedPlan())
7405 UpdateNegotiationNeeded();
7406}
7407
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007408PeerConnectionObserver* PeerConnection::Observer() const {
7409 // In earlier production code, the pointer was not cleared on close,
7410 // which might have led to undefined behavior if the observer was not
7411 // deallocated, or strange crashes if it was.
7412 // We use CHECK in order to catch such behavior if it exists.
7413 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7414 RTC_CHECK(observer_);
7415 return observer_;
7416}
7417
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007418CryptoOptions PeerConnection::GetCryptoOptions() {
7419 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7420 // after it has been removed.
7421 return configuration_.crypto_options.has_value()
7422 ? *configuration_.crypto_options
7423 : factory_->options().crypto_options;
7424}
7425
Harald Alvestrand89061872018-01-02 14:08:34 +01007426void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007427 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007428 if (stats_collector_) {
7429 stats_collector_->ClearCachedStatsReport();
7430 }
7431}
7432
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007433void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007434 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7435 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007436}
7437
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007438void PeerConnection::UpdateNegotiationNeeded() {
7439 RTC_DCHECK_RUN_ON(signaling_thread());
7440 if (!IsUnifiedPlan()) {
7441 Observer()->OnRenegotiationNeeded();
7442 return;
7443 }
7444
7445 // If connection's [[IsClosed]] slot is true, abort these steps.
7446 if (IsClosed())
7447 return;
7448
7449 // If connection's signaling state is not "stable", abort these steps.
7450 if (signaling_state() != kStable)
7451 return;
7452
7453 // NOTE
7454 // The negotiation-needed flag will be updated once the state transitions to
7455 // "stable", as part of the steps for setting an RTCSessionDescription.
7456
7457 // If the result of checking if negotiation is needed is false, clear the
7458 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7459 // to false, and abort these steps.
7460 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7461 if (!is_negotiation_needed) {
7462 is_negotiation_needed_ = false;
7463 return;
7464 }
7465
7466 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7467 // steps.
7468 if (is_negotiation_needed_)
7469 return;
7470
7471 // Set connection's [[NegotiationNeeded]] slot to true.
7472 is_negotiation_needed_ = true;
7473
7474 // Queue a task that runs the following steps:
7475 // If connection's [[IsClosed]] slot is true, abort these steps.
7476 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7477 // Fire an event named negotiationneeded at connection.
7478 Observer()->OnRenegotiationNeeded();
7479}
7480
7481bool PeerConnection::CheckIfNegotiationIsNeeded() {
7482 RTC_DCHECK_RUN_ON(signaling_thread());
7483 // 1. If any implementation-specific negotiation is required, as described at
7484 // the start of this section, return true.
7485
Henrik Boström79b69802019-07-18 11:16:56 +02007486 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7487 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7488 return true;
7489 }
7490
7491 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007492 const SessionDescriptionInterface* description = current_local_description();
7493 if (!description)
7494 return true;
7495
Henrik Boström79b69802019-07-18 11:16:56 +02007496 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007497 // description has been negotiated yet for data, return true.
7498 if (!sctp_data_channels_.empty()) {
7499 if (!cricket::GetFirstDataContent(description->description()->contents()))
7500 return true;
7501 }
7502
Henrik Boström79b69802019-07-18 11:16:56 +02007503 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007504 // following checks:
7505 for (const auto& transceiver : transceivers_) {
7506 const ContentInfo* current_local_msection =
7507 FindTransceiverMSection(transceiver.get(), description);
7508
7509 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7510 transceiver.get(), current_remote_description());
7511
Henrik Boström79b69802019-07-18 11:16:56 +02007512 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007513 // but the associated m= section is not yet rejected in
7514 // connection.[[CurrentLocalDescription]] or
7515 // connection.[[CurrentRemoteDescription]], return true.
7516 if (transceiver->stopped()) {
7517 if (current_local_msection && !current_local_msection->rejected &&
7518 ((current_remote_msection && !current_remote_msection->rejected) ||
7519 !current_remote_msection)) {
7520 return true;
7521 }
7522 continue;
7523 }
7524
Henrik Boström79b69802019-07-18 11:16:56 +02007525 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007526 // section in description, return true.
7527 if (!current_local_msection)
7528 return true;
7529
7530 const MediaContentDescription* current_local_media_description =
7531 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007532 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007533 // in description then perform the following checks:
7534
Henrik Boström79b69802019-07-18 11:16:56 +02007535 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007536 // associated m= section in description either doesn't contain a single
7537 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7538 // m= section, or the MSID values themselves, differ from what is in
7539 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7540 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7541 if (current_local_media_description->streams().size() == 0)
7542 return true;
7543
7544 std::vector<std::string> msection_msids;
7545 for (const auto& stream : current_local_media_description->streams()) {
7546 for (const std::string& msid : stream.stream_ids())
7547 msection_msids.push_back(msid);
7548 }
7549
7550 std::vector<std::string> transceiver_msids =
7551 transceiver->sender()->stream_ids();
7552 if (msection_msids.size() != transceiver_msids.size())
7553 return true;
7554
7555 absl::c_sort(transceiver_msids);
7556 absl::c_sort(msection_msids);
7557 if (transceiver_msids != msection_msids)
7558 return true;
7559 }
7560
Henrik Boström79b69802019-07-18 11:16:56 +02007561 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007562 // associated m= section in neither connection.[[CurrentLocalDescription]]
7563 // nor connection.[[CurrentRemoteDescription]] matches
7564 // transceiver.[[Direction]], return true.
7565 if (description->GetType() == SdpType::kOffer) {
7566 if (!current_remote_description())
7567 return true;
7568
7569 if (!current_remote_msection)
7570 return true;
7571
7572 RtpTransceiverDirection current_local_direction =
7573 current_local_media_description->direction();
7574 RtpTransceiverDirection current_remote_direction =
7575 current_remote_msection->media_description()->direction();
7576 if (transceiver->direction() != current_local_direction &&
7577 transceiver->direction() !=
7578 RtpTransceiverDirectionReversed(current_remote_direction)) {
7579 return true;
7580 }
7581 }
7582
Henrik Boström79b69802019-07-18 11:16:56 +02007583 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007584 // associated m= section in the description does not match
7585 // transceiver.[[Direction]] intersected with the offered direction (as
7586 // described in [JSEP] (section 5.3.1.)), return true.
7587 if (description->GetType() == SdpType::kAnswer) {
7588 if (!remote_description())
7589 return true;
7590
7591 const ContentInfo* offered_remote_msection =
7592 FindTransceiverMSection(transceiver.get(), remote_description());
7593
7594 RtpTransceiverDirection offered_direction =
7595 offered_remote_msection
7596 ? offered_remote_msection->media_description()->direction()
7597 : RtpTransceiverDirection::kInactive;
7598
7599 if (current_local_media_description->direction() !=
7600 (RtpTransceiverDirectionIntersection(
7601 transceiver->direction(),
7602 RtpTransceiverDirectionReversed(offered_direction)))) {
7603 return true;
7604 }
7605 }
7606 }
7607
7608 // If all the preceding checks were performed and true was not returned,
7609 // nothing remains to be negotiated; return false.
7610 return false;
7611}
7612
Eldar Relloead0ec92019-10-21 23:01:31 +03007613RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007614 auto state = signaling_state();
7615 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7616 state != PeerConnectionInterface::kHaveRemoteOffer) {
7617 return RTCError(RTCErrorType::INVALID_STATE,
7618 "Called in wrong signalingState: " +
7619 GetSignalingStateString(signaling_state()));
7620 }
7621 RTC_DCHECK_RUN_ON(signaling_thread());
7622 RTC_DCHECK(IsUnifiedPlan());
7623
7624 for (auto&& transceivers_stable_state_pair :
7625 transceiver_stable_states_by_transceivers_) {
7626 auto transceiver = transceivers_stable_state_pair.first;
7627 auto state = transceivers_stable_state_pair.second;
7628 RTC_DCHECK(transceiver->internal()->mid().has_value());
7629 std::string mid = transceiver->internal()->mid().value();
7630 transport_controller_->RollbackTransportForMid(mid);
7631 DestroyTransceiverChannel(transceiver);
7632
Eldar Relloead0ec92019-10-21 23:01:31 +03007633 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7634 transceiver->receiver()) {
7635 Observer()->OnRemoveTrack(transceiver->receiver());
7636 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007637 if (state.newly_created()) {
7638 // Remove added transceivers with no added track.
7639 if (transceiver->internal()->sender()->track()) {
7640 transceiver->internal()->set_created_by_addtrack(true);
7641 } else {
7642 int remaining_transceiver_count = 0;
7643 for (auto&& t : transceivers_) {
7644 if (t != transceiver) {
7645 transceivers_[remaining_transceiver_count++] = t;
7646 }
7647 }
7648 transceivers_.resize(remaining_transceiver_count);
7649 }
7650 }
7651 transceiver->internal()->sender_internal()->set_transport(nullptr);
7652 transceiver->internal()->receiver_internal()->set_transport(nullptr);
7653 transceiver->internal()->set_direction(state.direction());
7654 transceiver->internal()->set_mid(state.mid());
7655 transceiver->internal()->set_mline_index(state.mline_index());
7656 }
7657 transceiver_stable_states_by_transceivers_.clear();
7658 pending_local_description_.reset();
7659 pending_remote_description_.reset();
7660 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03007661
7662 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
7663 // gets called in SetRemoteDescription.
7664 if (sdp_type == SdpType::kRollback) {
7665 UpdateNegotiationNeeded();
7666 if (is_negotiation_needed_) {
7667 Observer()->OnRenegotiationNeeded();
7668 }
7669 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007670 return RTCError::OK();
7671}
7672
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007673} // namespace webrtc