blob: 7dc2e35aeda89d957039aa6842d9f2229c4c01af [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
Henrik Boströma3728d32019-10-28 12:09:49 +0100650// Wraps a CreateSessionDescriptionObserver and an OperationsChain operation
651// complete callback. When the observer is invoked, the wrapped observer is
652// invoked followed by invoking the completion callback.
653class CreateSessionDescriptionObserverOperationWrapper
654 : public CreateSessionDescriptionObserver {
655 public:
656 CreateSessionDescriptionObserverOperationWrapper(
657 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer,
658 std::function<void()> operation_complete_callback)
659 : observer_(std::move(observer)),
660 operation_complete_callback_(std::move(operation_complete_callback)) {
661 RTC_DCHECK(observer_);
662 }
663 ~CreateSessionDescriptionObserverOperationWrapper() override {
664 RTC_DCHECK(was_called_);
665 }
666
667 void OnSuccess(SessionDescriptionInterface* desc) override {
668 RTC_DCHECK(!was_called_);
669#ifdef RTC_DCHECK_IS_ON
670 was_called_ = true;
671#endif // RTC_DCHECK_IS_ON
672 // Completing the operation before invoking the observer allows the observer
673 // to execute SetLocalDescription() without delay.
674 operation_complete_callback_();
675 observer_->OnSuccess(desc);
676 }
677
678 void OnFailure(RTCError error) override {
679 RTC_DCHECK(!was_called_);
680#ifdef RTC_DCHECK_IS_ON
681 was_called_ = true;
682#endif // RTC_DCHECK_IS_ON
683 operation_complete_callback_();
684 observer_->OnFailure(std::move(error));
685 }
686
687 private:
688#ifdef RTC_DCHECK_IS_ON
689 bool was_called_ = false;
690#endif // RTC_DCHECK_IS_ON
691 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_;
692 std::function<void()> operation_complete_callback_;
693};
694
Steve Anton75737c02017-11-06 10:37:17 -0800695} // namespace
696
Henrik Boström79b69802019-07-18 11:16:56 +0200697class PeerConnection::LocalIceCredentialsToReplace {
698 public:
699 // Sets the ICE credentials that need restarting to the ICE credentials of
700 // the current and pending descriptions.
701 void SetIceCredentialsFromLocalDescriptions(
702 const SessionDescriptionInterface* current_local_description,
703 const SessionDescriptionInterface* pending_local_description) {
704 ice_credentials_.clear();
705 if (current_local_description) {
706 AppendIceCredentialsFromSessionDescription(*current_local_description);
707 }
708 if (pending_local_description) {
709 AppendIceCredentialsFromSessionDescription(*pending_local_description);
710 }
711 }
712
713 void ClearIceCredentials() { ice_credentials_.clear(); }
714
715 // Returns true if we have ICE credentials that need restarting.
716 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
717
718 // Returns true if |local_description| shares no ICE credentials with the
719 // ICE credentials that need restarting.
720 bool SatisfiesIceRestart(
721 const SessionDescriptionInterface& local_description) const {
722 for (const auto& transport_info :
723 local_description.description()->transport_infos()) {
724 if (ice_credentials_.find(std::make_pair(
725 transport_info.description.ice_ufrag,
726 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
727 return false;
728 }
729 }
730 return true;
731 }
732
733 private:
734 void AppendIceCredentialsFromSessionDescription(
735 const SessionDescriptionInterface& desc) {
736 for (const auto& transport_info : desc.description()->transport_infos()) {
737 ice_credentials_.insert(
738 std::make_pair(transport_info.description.ice_ufrag,
739 transport_info.description.ice_pwd));
740 }
741 }
742
743 std::set<std::pair<std::string, std::string>> ice_credentials_;
744};
745
Henrik Boström31638672017-11-23 17:48:32 +0100746// Upon completion, posts a task to execute the callback of the
747// SetSessionDescriptionObserver asynchronously on the same thread. At this
748// point, the state of the peer connection might no longer reflect the effects
749// of the SetRemoteDescription operation, as the peer connection could have been
750// modified during the post.
751// TODO(hbos): Remove this class once we remove the version of
752// PeerConnectionInterface::SetRemoteDescription() that takes a
753// SetSessionDescriptionObserver as an argument.
754class PeerConnection::SetRemoteDescriptionObserverAdapter
755 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
756 public:
757 SetRemoteDescriptionObserverAdapter(
758 rtc::scoped_refptr<PeerConnection> pc,
759 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
760 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
761
762 // SetRemoteDescriptionObserverInterface implementation.
763 void OnSetRemoteDescriptionComplete(RTCError error) override {
764 if (error.ok())
765 pc_->PostSetSessionDescriptionSuccess(wrapper_);
766 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100767 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100768 }
769
770 private:
771 rtc::scoped_refptr<PeerConnection> pc_;
772 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
773};
774
deadbeef293e9262017-01-11 12:28:30 -0800775bool PeerConnectionInterface::RTCConfiguration::operator==(
776 const PeerConnectionInterface::RTCConfiguration& o) const {
777 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700778 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800779 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000780 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700781 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800782 BundlePolicy bundle_policy;
783 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700784 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
785 int ice_candidate_pool_size;
786 bool disable_ipv6;
787 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700788 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100789 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700790 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200791 absl::optional<int> screencast_min_bitrate;
792 absl::optional<bool> combined_audio_video_bwe;
793 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800794 TcpCandidatePolicy tcp_candidate_policy;
795 CandidateNetworkPolicy candidate_network_policy;
796 int audio_jitter_buffer_max_packets;
797 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100798 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100799 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800800 int ice_connection_receiving_timeout;
801 int ice_backup_candidate_pair_ping_interval;
802 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800803 bool prioritize_most_likely_ice_candidate_pairs;
804 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800805 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700806 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800807 bool presume_writable_when_fully_relayed;
808 bool enable_ice_renomination;
809 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700810 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200811 absl::optional<int> ice_check_interval_strong_connectivity;
812 absl::optional<int> ice_check_interval_weak_connectivity;
813 absl::optional<int> ice_check_min_interval;
814 absl::optional<int> ice_unwritable_timeout;
815 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800816 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200817 absl::optional<int> stun_candidate_keepalive_interval;
818 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200819 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800820 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200821 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700822 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700823 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700824 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700825 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700826 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700827 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700828 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100829 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200830 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300831 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 12:23:02 +0200832 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800833 };
834 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
835 "Did you add something to RTCConfiguration and forget to "
836 "update operator==?");
837 return type == o.type && servers == o.servers &&
838 bundle_policy == o.bundle_policy &&
839 rtcp_mux_policy == o.rtcp_mux_policy &&
840 tcp_candidate_policy == o.tcp_candidate_policy &&
841 candidate_network_policy == o.candidate_network_policy &&
842 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
843 audio_jitter_buffer_fast_accelerate ==
844 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100845 audio_jitter_buffer_min_delay_ms ==
846 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100847 audio_jitter_buffer_enable_rtx_handling ==
848 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800849 ice_connection_receiving_timeout ==
850 o.ice_connection_receiving_timeout &&
851 ice_backup_candidate_pair_ping_interval ==
852 o.ice_backup_candidate_pair_ping_interval &&
853 continual_gathering_policy == o.continual_gathering_policy &&
854 certificates == o.certificates &&
855 prioritize_most_likely_ice_candidate_pairs ==
856 o.prioritize_most_likely_ice_candidate_pairs &&
857 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800858 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700859 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100860 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800861 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800862 screencast_min_bitrate == o.screencast_min_bitrate &&
863 combined_audio_video_bwe == o.combined_audio_video_bwe &&
864 enable_dtls_srtp == o.enable_dtls_srtp &&
865 ice_candidate_pool_size == o.ice_candidate_pool_size &&
866 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700867 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800868 presume_writable_when_fully_relayed ==
869 o.presume_writable_when_fully_relayed &&
870 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800871 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700872 surface_ice_candidates_on_ice_transport_type_changed ==
873 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800874 ice_check_interval_strong_connectivity ==
875 o.ice_check_interval_strong_connectivity &&
876 ice_check_interval_weak_connectivity ==
877 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700878 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700879 ice_unwritable_timeout == o.ice_unwritable_timeout &&
880 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800881 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800882 stun_candidate_keepalive_interval ==
883 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200884 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800885 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800886 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700887 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700888 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700889 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700890 use_media_transport_for_data_channels ==
891 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700892 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700893 use_datagram_transport_for_data_channels ==
894 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700895 use_datagram_transport_for_data_channels_receive_only ==
896 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100897 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200898 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300899 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 12:23:02 +0200900 enable_implicit_rollback == o.enable_implicit_rollback &&
901 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800902}
903
904bool PeerConnectionInterface::RTCConfiguration::operator!=(
905 const PeerConnectionInterface::RTCConfiguration& o) const {
906 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800907}
908
zhihuang8f65cdf2016-05-06 18:40:30 -0700909// Generate a RTCP CNAME when a PeerConnection is created.
910std::string GenerateRtcpCname() {
911 std::string cname;
912 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100913 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800914 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700915 }
916 return cname;
917}
918
zhihuang1c378ed2017-08-17 14:10:50 -0700919bool ValidateOfferAnswerOptions(
920 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
921 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
922 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700923}
924
zhihuang1c378ed2017-08-17 14:10:50 -0700925// From |rtc_options|, fill parts of |session_options| shared by all generated
926// m= sections (in other words, nothing that involves a map/array).
927void ExtractSharedMediaSessionOptions(
928 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
929 cricket::MediaSessionOptions* session_options) {
930 session_options->vad_enabled = rtc_options.voice_activity_detection;
931 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200932 session_options->raw_packetization_for_video =
933 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700934}
zhihuanga77e6bb2017-08-14 18:17:48 -0700935
zhihuang38ede132017-06-15 12:52:32 -0700936PeerConnection::PeerConnection(PeerConnectionFactory* factory,
937 std::unique_ptr<RtcEventLog> event_log,
938 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700940 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100941 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 12:09:49 +0100942 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700943 datagram_transport_config_(
944 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700945 datagram_transport_data_channel_config_(
946 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700947 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700948 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700949 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100950 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200951 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -0700952 data_channel_transport_(nullptr),
Henrik Boströma3728d32019-10-28 12:09:49 +0100953 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
954 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955
956PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100957 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800958 RTC_DCHECK_RUN_ON(signaling_thread());
959
Henrik Boströma3728d32019-10-28 12:09:49 +0100960 weak_ptr_factory_.InvalidateWeakPtrs();
961
Steve Anton8af21862017-12-15 11:20:13 -0800962 // Need to stop transceivers before destroying the stats collector because
963 // AudioRtpSender has a reference to the StatsCollector it will update when
964 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100965 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800966 transceiver->Stop();
967 }
Steve Anton4171afb2017-11-20 10:20:22 -0800968
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700969 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800970 if (stats_collector_) {
971 stats_collector_->WaitForPendingRequest();
972 stats_collector_ = nullptr;
973 }
Steve Anton75737c02017-11-06 10:37:17 -0800974
Steve Anton8af21862017-12-15 11:20:13 -0800975 // Don't destroy BaseChannels until after stats has been cleaned up so that
976 // the last stats request can still read from the channels.
977 DestroyAllChannels();
978
Mirko Bonadei675513b2017-11-09 11:09:25 +0100979 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800980
981 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800982 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700983 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800984 transport_controller_.reset();
985
deadbeef91dd5672016-05-18 16:55:30 -0700986 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100987 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
988 RTC_DCHECK_RUN_ON(network_thread());
989 port_allocator_.reset();
990 });
eladalon248fd4f2017-09-06 05:18:15 -0700991 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700992 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100993 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700994 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800995 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700996 event_log_.reset();
997 });
Henrik Boströma3728d32019-10-28 12:09:49 +0100998
999 // Process all pending notifications in the message queue. If we don't do
1000 // this, requests will linger and not know they succeeded or failed.
1001 rtc::MessageList list;
1002 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1003 for (auto& msg : list) {
1004 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1005 // Processing CreateOffer() and CreateAnswer() messages ensures their
1006 // observers are invoked even if the PeerConnection is destroyed early.
1007 OnMessage(&msg);
1008 } else {
1009 // TODO(hbos): Consider processing all pending messages. This would mean
1010 // that SetLocalDescription() and SetRemoteDescription() observers are
1011 // informed of successes and failures; this is currently NOT the case.
1012 delete msg.pdata;
1013 }
1014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015}
1016
Steve Anton8af21862017-12-15 11:20:13 -08001017void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -08001018 // Destroy video channels first since they may have a pointer to a voice
1019 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001020 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001021 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001022 DestroyTransceiverChannel(transceiver);
1023 }
1024 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01001025 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001026 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001027 DestroyTransceiverChannel(transceiver);
1028 }
1029 }
1030 DestroyDataChannel();
1031}
1032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001034 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -07001035 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001036 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01001037 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01001038 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -07001039
1040 RTCError config_error = ValidateConfiguration(configuration);
1041 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001042 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001043 return false;
1044 }
1045
Benjamin Wrightcab58882018-05-02 15:12:47 -07001046 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001047 RTC_LOG(LS_ERROR)
1048 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001049 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001050 return false;
1051 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001052
Benjamin Wrightcab58882018-05-02 15:12:47 -07001053 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001054 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001055 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001056 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001057 return false;
1058 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001059
Benjamin Wrightcab58882018-05-02 15:12:47 -07001060 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001061 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001062 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001063 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001064
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001065 cricket::ServerAddresses stun_servers;
1066 std::vector<cricket::RelayServerConfig> turn_servers;
1067
1068 RTCErrorType parse_error =
1069 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1070 if (parse_error != RTCErrorType::NONE) {
1071 return false;
1072 }
1073
Jonas Oreland3c028422019-08-22 16:16:35 +02001074 // Add the turn logging id to all turn servers
1075 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1076 turn_server.turn_logging_id = configuration.turn_logging_id;
1077 }
1078
deadbeef91dd5672016-05-18 16:55:30 -07001079 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001080 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001081 const auto pa_result =
1082 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001083 RTC_FROM_HERE,
1084 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001085 stun_servers, turn_servers, configuration));
1086
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001087 // If initialization was successful, note if STUN or TURN servers
1088 // were supplied.
1089 if (!stun_servers.empty()) {
1090 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1091 }
1092 if (!turn_servers.empty()) {
1093 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1094 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001096 // Send information about IPv4/IPv6 status.
1097 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001098 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001099 address_family = kPeerConnection_IPv6;
1100 } else {
1101 address_family = kPeerConnection_IPv4;
1102 }
1103 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1104 kPeerConnectionAddressFamilyCounter_Max);
1105
Zhi Huange830e682018-03-30 10:48:35 -07001106 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1107
Steve Anton75737c02017-11-06 10:37:17 -08001108 // RFC 3264: The numeric value of the session id and version in the
1109 // o line MUST be representable with a "64 bit signed integer".
1110 // Due to this constraint session id |session_id_| is max limited to
1111 // LLONG_MAX.
1112 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001113 JsepTransportController::Config config;
1114 config.redetermine_role_on_ice_restart =
1115 configuration.redetermine_role_on_ice_restart;
1116 config.ssl_max_version = factory_->options().ssl_max_version;
1117 config.disable_encryption = options.disable_encryption;
1118 config.bundle_policy = configuration.bundle_policy;
1119 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001120 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1121 // stub.
1122 config.crypto_options = configuration.crypto_options.has_value()
1123 ? *configuration.crypto_options
1124 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001125 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001126 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1127 // since the JsepTransportController instance is owned by this PeerConnection
1128 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1129 // pointer.
1130 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1131 int64_t packet_time_us) {
1132 RTC_DCHECK_RUN_ON(network_thread());
1133 rtcp_invoker_.AsyncInvoke<void>(
1134 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1135 RTC_DCHECK_RUN_ON(worker_thread());
1136 // |call_| is reset on the worker thread in the PeerConnection
1137 // destructor, so we check that it's still valid before propagating
1138 // the packet.
1139 if (call_) {
1140 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1141 packet_time_us);
1142 }
1143 });
1144 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001145 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001146#if defined(ENABLE_EXTERNAL_AUTH)
1147 config.enable_external_auth = true;
1148#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001149 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001150
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001151 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001152 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001153 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001154 use_datagram_transport_for_data_channels_ =
1155 datagram_transport_data_channel_config_.enabled &&
1156 configuration.use_datagram_transport_for_data_channels.value_or(
1157 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001158 use_datagram_transport_for_data_channels_receive_only_ =
1159 configuration.use_datagram_transport_for_data_channels_receive_only
1160 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001161 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1162 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001163 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001164 if (!factory_->media_transport_factory()) {
1165 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001166 << "PeerConnecton is initialized with use_media_transport = true or "
1167 << "use_media_transport_for_data_channels = true "
1168 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001169 return false;
1170 }
1171
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001172 if (configuration.use_media_transport ||
1173 configuration.use_media_transport_for_data_channels) {
1174 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1175 // RTP media transport is introduced. But until then, we require SDES to
1176 // be enabled.
1177 if (configuration.enable_dtls_srtp.has_value() &&
1178 configuration.enable_dtls_srtp.value()) {
1179 RTC_LOG(LS_WARNING)
1180 << "When media transport is used, SDES must be enabled. Set "
1181 "configuration.enable_dtls_srtp to false. use_media_transport="
1182 << configuration.use_media_transport
1183 << ", use_media_transport_for_data_channels="
1184 << configuration.use_media_transport_for_data_channels;
1185 return false;
1186 }
1187 }
1188
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001189 config.use_media_transport_for_media = configuration.use_media_transport;
1190 config.use_media_transport_for_data_channels =
1191 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001192 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001193 config.use_datagram_transport_for_data_channels =
1194 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001195 config.use_datagram_transport_for_data_channels_receive_only =
1196 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001197 config.media_transport_factory = factory_->media_transport_factory();
1198 }
1199
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001200 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1201 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1202 if (!configuration.certificates.empty()) {
1203 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1204 // just picking the first one. The decision should be made based on the DTLS
1205 // handshake. The DTLS negotiations need to know about all certificates.
1206 certificate = configuration.certificates[0];
1207 }
1208
1209 if (options.disable_encryption) {
1210 dtls_enabled_ = false;
1211 } else {
1212 // Enable DTLS by default if we have an identity store or a certificate.
1213 dtls_enabled_ = (dependencies.cert_generator || certificate);
1214 // |configuration| can override the default |dtls_enabled_| value.
1215 if (configuration.enable_dtls_srtp) {
1216 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1217 }
1218 }
1219
1220 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1221
1222 if (use_datagram_transport_for_data_channels_) {
1223 if (configuration.enable_rtp_data_channel) {
1224 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1225 "use_datagram_transport_for_data_channels are "
1226 "incompatible and cannot both be set to true";
1227 return false;
1228 }
1229 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1230 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1231 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1232 } else {
1233 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1234 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1235 config.sctp_factory = sctp_factory_.get();
1236 }
1237 } else if (configuration.use_media_transport_for_data_channels) {
1238 if (configuration.enable_rtp_data_channel) {
1239 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1240 "use_media_transport_for_data_channels are "
1241 "incompatible and cannot both be set to true";
1242 return false;
1243 }
1244 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1245 } else if (configuration.enable_rtp_data_channel) {
1246 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1247 // set. It takes precendence over the disable_sctp_data_channels
1248 // PeerConnectionFactoryInterface::Options.
1249 data_channel_type_ = cricket::DCT_RTP;
1250 } else {
1251 // DTLS has to be enabled to use SCTP.
1252 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1253 data_channel_type_ = cricket::DCT_SCTP;
1254 config.sctp_factory = sctp_factory_.get();
1255 }
1256 }
1257
Zhi Huange830e682018-03-30 10:48:35 -07001258 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001259 signaling_thread(), network_thread(), port_allocator_.get(),
1260 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001261 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001262 this, &PeerConnection::OnTransportControllerConnectionState);
1263 transport_controller_->SignalStandardizedIceConnectionState.connect(
1264 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001265 transport_controller_->SignalConnectionState.connect(
1266 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001267 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001268 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001269 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001270 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001271 transport_controller_->SignalIceCandidateError.connect(
1272 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001273 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001274 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1275 transport_controller_->SignalDtlsHandshakeError.connect(
1276 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001277 transport_controller_->SignalIceCandidatePairChanged.connect(
1278 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001279
deadbeefab9b2d12015-10-14 11:33:11 -07001280 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001281 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282
Steve Antonba818672017-11-06 10:21:57 -08001283 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001284 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001285
Steve Antond25da372017-11-06 14:50:29 -08001286 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001287
Steve Anton75737c02017-11-06 10:37:17 -08001288 video_options_.screencast_min_bitrate_kbps =
1289 configuration.screencast_min_bitrate;
1290 audio_options_.combined_audio_video_bwe =
1291 configuration.combined_audio_video_bwe;
1292
1293 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001294 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001295
1296 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001297 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001298
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001299 audio_options_.audio_jitter_buffer_min_delay_ms =
1300 configuration.audio_jitter_buffer_min_delay_ms;
1301
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001302 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1303 configuration.audio_jitter_buffer_enable_rtx_handling;
1304
Steve Anton75737c02017-11-06 10:37:17 -08001305 // Whether the certificate generator/certificate is null or not determines
1306 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1307 // the right instructions by clearing the variables if needed.
1308 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001309 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001310 certificate = nullptr;
1311 } else if (certificate) {
1312 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001313 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001314 }
1315
1316 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1317 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001318 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001319 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1320 this, &PeerConnection::OnCertificateReady);
1321
1322 if (options.disable_encryption) {
1323 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1324 }
1325
1326 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001327 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001328 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329
Steve Anton4171afb2017-11-20 10:20:22 -08001330 // Add default audio/video transceivers for Plan B SDP.
1331 if (!IsUnifiedPlan()) {
1332 transceivers_.push_back(
1333 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1334 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1335 transceivers_.push_back(
1336 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1337 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1338 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001339 int delay_ms =
1340 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001341 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1342 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001343
1344 if (dependencies.video_bitrate_allocator_factory) {
1345 video_bitrate_allocator_factory_ =
1346 std::move(dependencies.video_bitrate_allocator_factory);
1347 } else {
1348 video_bitrate_allocator_factory_ =
1349 CreateBuiltinVideoBitrateAllocatorFactory();
1350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 return true;
1352}
1353
Steve Anton038834f2017-07-14 15:59:59 -07001354RTCError PeerConnection::ValidateConfiguration(
1355 const RTCConfiguration& config) const {
1356 if (config.ice_regather_interval_range &&
1357 config.continual_gathering_policy == GATHER_ONCE) {
1358 return RTCError(RTCErrorType::INVALID_PARAMETER,
1359 "ice_regather_interval_range specified but continual "
1360 "gathering policy is GATHER_ONCE");
1361 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001362 auto result =
1363 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1364 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001365}
1366
Yves Gerey665174f2018-06-19 15:03:05 +02001367rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001368 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001369 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1370 "Plan SdpSemantics. Please use GetSenders "
1371 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001372 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373}
1374
Yves Gerey665174f2018-06-19 15:03:05 +02001375rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001376 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001377 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1378 "Plan SdpSemantics. Please use GetReceivers "
1379 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001380 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381}
1382
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001383bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001384 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001385 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1386 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001387 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 if (IsClosed()) {
1389 return false;
1390 }
deadbeefab9b2d12015-10-14 11:33:11 -07001391 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 return false;
1393 }
deadbeefab9b2d12015-10-14 11:33:11 -07001394
1395 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001396 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1397 observer->SignalAudioTrackAdded.connect(this,
1398 &PeerConnection::OnAudioTrackAdded);
1399 observer->SignalAudioTrackRemoved.connect(
1400 this, &PeerConnection::OnAudioTrackRemoved);
1401 observer->SignalVideoTrackAdded.connect(this,
1402 &PeerConnection::OnVideoTrackAdded);
1403 observer->SignalVideoTrackRemoved.connect(
1404 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001405 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001406
deadbeefab9b2d12015-10-14 11:33:11 -07001407 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001408 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001409 }
1410 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001411 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001412 }
1413
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001414 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001415 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 return true;
1417}
1418
1419void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001420 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001421 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1422 "Plan SdpSemantics. Please use RemoveTrack "
1423 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001424 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001425 if (!IsClosed()) {
1426 for (const auto& track : local_stream->GetAudioTracks()) {
1427 RemoveAudioTrack(track.get(), local_stream);
1428 }
1429 for (const auto& track : local_stream->GetVideoTracks()) {
1430 RemoveVideoTrack(track.get(), local_stream);
1431 }
deadbeefab9b2d12015-10-14 11:33:11 -07001432 }
deadbeefab9b2d12015-10-14 11:33:11 -07001433 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001434 stream_observers_.erase(
1435 std::remove_if(
1436 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001437 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001438 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001439 }),
1440 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 if (IsClosed()) {
1443 return;
1444 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001445 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446}
1447
Steve Anton2d6c76a2018-01-05 17:10:52 -08001448RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001449 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001450 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001451 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001452 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001453 if (!track) {
1454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1455 }
1456 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1457 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1458 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1459 "Track has invalid kind: " + track->kind());
1460 }
Steve Antonf9381f02017-12-14 10:23:57 -08001461 if (IsClosed()) {
1462 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1463 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001464 }
Steve Anton4171afb2017-11-20 10:20:22 -08001465 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001466 LOG_AND_RETURN_ERROR(
1467 RTCErrorType::INVALID_PARAMETER,
1468 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001469 }
Steve Antonf9381f02017-12-14 10:23:57 -08001470 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001471 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1472 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001473 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001474 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001475 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001476 }
1477 return sender_or_error;
1478}
deadbeefe1f9d832016-01-14 15:35:42 -08001479
Steve Antonf9381f02017-12-14 10:23:57 -08001480RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1481PeerConnection::AddTrackPlanB(
1482 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001483 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001484 if (stream_ids.size() > 1u) {
1485 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1486 "AddTrack with more than one stream is not "
1487 "supported with Plan B semantics.");
1488 }
1489 std::vector<std::string> adjusted_stream_ids = stream_ids;
1490 if (adjusted_stream_ids.empty()) {
1491 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1492 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001493 cricket::MediaType media_type =
1494 (track->kind() == MediaStreamTrackInterface::kAudioKind
1495 ? cricket::MEDIA_TYPE_AUDIO
1496 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001497 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001498 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001499 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001500 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001501 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001502 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001503 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001504 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001505 if (sender_info) {
1506 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001507 }
Steve Antonf9381f02017-12-14 10:23:57 -08001508 } else {
1509 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001510 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001511 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001512 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001513 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001514 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001515 if (sender_info) {
1516 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001517 }
deadbeefe1f9d832016-01-14 15:35:42 -08001518 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001520}
deadbeefe1f9d832016-01-14 15:35:42 -08001521
Steve Antonf9381f02017-12-14 10:23:57 -08001522RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1523PeerConnection::AddTrackUnifiedPlan(
1524 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001525 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001526 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1527 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001528 RTC_LOG(LS_INFO) << "Reusing an existing "
1529 << cricket::MediaTypeToString(transceiver->media_type())
1530 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001531 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001532 transceiver->internal()->set_direction(
1533 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001534 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001535 transceiver->internal()->set_direction(
1536 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001537 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001539 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001540 } else {
1541 cricket::MediaType media_type =
1542 (track->kind() == MediaStreamTrackInterface::kAudioKind
1543 ? cricket::MEDIA_TYPE_AUDIO
1544 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001545 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1546 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001547 std::string sender_id = track->id();
1548 // Avoid creating a sender with an existing ID by generating a random ID.
1549 // This can happen if this is the second time AddTrack has created a sender
1550 // for this track.
1551 if (FindSenderById(sender_id)) {
1552 sender_id = rtc::CreateRandomUuid();
1553 }
Florent Castelli892acf02018-10-01 22:47:20 +02001554 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001555 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1556 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001557 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001558 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001559 }
Steve Antonf9381f02017-12-14 10:23:57 -08001560 return transceiver->sender();
1561}
1562
1563rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1564PeerConnection::FindFirstTransceiverForAddedTrack(
1565 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1566 RTC_DCHECK(track);
1567 for (auto transceiver : transceivers_) {
1568 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001569 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001570 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001571 !transceiver->internal()->has_ever_been_used_to_send() &&
1572 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001573 return transceiver;
1574 }
1575 }
1576 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001577}
1578
1579bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1580 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001581 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001582}
1583
Steve Anton24db5732018-07-23 10:27:33 -07001584RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001585 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001586 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001587 if (!sender) {
1588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1589 }
deadbeefe1f9d832016-01-14 15:35:42 -08001590 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001591 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1592 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001593 }
Steve Antonf9381f02017-12-14 10:23:57 -08001594 if (IsUnifiedPlan()) {
1595 auto transceiver = FindTransceiverBySender(sender);
1596 if (!transceiver || !sender->track()) {
1597 return RTCError::OK();
1598 }
1599 sender->SetTrack(nullptr);
1600 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001601 transceiver->internal()->set_direction(
1602 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001603 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001604 transceiver->internal()->set_direction(
1605 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001606 }
Steve Anton4171afb2017-11-20 10:20:22 -08001607 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001608 bool removed;
1609 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1610 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1611 } else {
1612 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1613 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1614 }
1615 if (!removed) {
1616 LOG_AND_RETURN_ERROR(
1617 RTCErrorType::INVALID_PARAMETER,
1618 "Couldn't find sender " + sender->id() + " to remove.");
1619 }
Steve Anton4171afb2017-11-20 10:20:22 -08001620 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001621 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001622 return RTCError::OK();
1623}
1624
1625rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1626PeerConnection::FindTransceiverBySender(
1627 rtc::scoped_refptr<RtpSenderInterface> sender) {
1628 for (auto transceiver : transceivers_) {
1629 if (transceiver->sender() == sender) {
1630 return transceiver;
1631 }
1632 }
1633 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001634}
1635
Steve Anton9158ef62017-11-27 13:01:52 -08001636RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1637PeerConnection::AddTransceiver(
1638 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1639 return AddTransceiver(track, RtpTransceiverInit());
1640}
1641
1642RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1643PeerConnection::AddTransceiver(
1644 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1645 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001646 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001647 RTC_CHECK(IsUnifiedPlan())
1648 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001649 if (!track) {
1650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1651 }
1652 cricket::MediaType media_type;
1653 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1654 media_type = cricket::MEDIA_TYPE_AUDIO;
1655 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1656 media_type = cricket::MEDIA_TYPE_VIDEO;
1657 } else {
1658 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1659 "Track kind is not audio or video");
1660 }
1661 return AddTransceiver(media_type, track, init);
1662}
1663
1664RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1665PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1666 return AddTransceiver(media_type, RtpTransceiverInit());
1667}
1668
1669RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1670PeerConnection::AddTransceiver(cricket::MediaType media_type,
1671 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001672 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001673 RTC_CHECK(IsUnifiedPlan())
1674 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001675 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1676 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1677 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1678 "media type is not audio or video");
1679 }
1680 return AddTransceiver(media_type, nullptr, init);
1681}
1682
1683RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1684PeerConnection::AddTransceiver(
1685 cricket::MediaType media_type,
1686 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001687 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001688 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001689 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1690 media_type == cricket::MEDIA_TYPE_VIDEO));
1691 if (track) {
1692 RTC_DCHECK_EQ(media_type,
1693 (track->kind() == MediaStreamTrackInterface::kAudioKind
1694 ? cricket::MEDIA_TYPE_AUDIO
1695 : cricket::MEDIA_TYPE_VIDEO));
1696 }
1697
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001698 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1699 init.send_encodings.size(), 0, 7, 8);
1700
Amit Hilbuchaa584152019-02-06 17:09:52 -08001701 size_t num_rids = absl::c_count_if(init.send_encodings,
1702 [](const RtpEncodingParameters& encoding) {
1703 return !encoding.rid.empty();
1704 });
1705 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001706 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001707 RTCErrorType::INVALID_PARAMETER,
1708 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001709 }
1710
Amit Hilbuchf4770402019-04-08 14:11:57 -07001711 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1712 [](const RtpEncodingParameters& encoding) {
1713 return !IsLegalRsidName(encoding.rid);
1714 })) {
1715 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1716 "Invalid RID value provided.");
1717 }
1718
Amit Hilbuchaa584152019-02-06 17:09:52 -08001719 if (absl::c_any_of(init.send_encodings,
1720 [](const RtpEncodingParameters& encoding) {
1721 return encoding.ssrc.has_value();
1722 })) {
1723 LOG_AND_RETURN_ERROR(
1724 RTCErrorType::UNSUPPORTED_PARAMETER,
1725 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001726 }
1727
1728 RtpParameters parameters;
1729 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001730
1731 // Encodings are dropped from the tail if too many are provided.
1732 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1733 parameters.encodings.erase(
1734 parameters.encodings.begin() + kMaxSimulcastStreams,
1735 parameters.encodings.end());
1736 }
1737
1738 // Single RID should be removed.
1739 if (parameters.encodings.size() == 1 &&
1740 !parameters.encodings[0].rid.empty()) {
1741 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1742 parameters.encodings[0].rid.clear();
1743 }
1744
1745 // If RIDs were not provided, they are generated for simulcast scenario.
1746 if (parameters.encodings.size() > 1 && num_rids == 0) {
1747 rtc::UniqueStringGenerator rid_generator;
1748 for (RtpEncodingParameters& encoding : parameters.encodings) {
1749 encoding.rid = rid_generator();
1750 }
1751 }
1752
Florent Castelli892acf02018-10-01 22:47:20 +02001753 if (UnimplementedRtpParameterHasValue(parameters)) {
1754 LOG_AND_RETURN_ERROR(
1755 RTCErrorType::UNSUPPORTED_PARAMETER,
1756 "Attempted to set an unimplemented parameter of RtpParameters.");
1757 }
Steve Anton9158ef62017-11-27 13:01:52 -08001758
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001759 auto result = cricket::CheckRtpParametersValues(parameters);
1760 if (!result.ok()) {
1761 LOG_AND_RETURN_ERROR(result.type(), result.message());
1762 }
1763
Steve Anton3d954a62018-04-02 11:27:23 -07001764 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1765 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001766 // Set the sender ID equal to the track ID if the track is specified unless
1767 // that sender ID is already in use.
1768 std::string sender_id =
1769 (track && !FindSenderById(track->id()) ? track->id()
1770 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001771 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001772 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001773 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1774 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1775 transceiver->internal()->set_direction(init.direction);
1776
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001777 if (update_negotiation_needed) {
1778 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001779 }
Steve Antonf9381f02017-12-14 10:23:57 -08001780
1781 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1782}
1783
Steve Anton02ee47c2018-01-10 16:26:06 -08001784rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1785PeerConnection::CreateSender(
1786 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001787 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001788 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001789 const std::vector<std::string>& stream_ids,
1790 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001791 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001792 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001793 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1794 RTC_DCHECK(!track ||
1795 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1796 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1797 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001798 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001799 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001800 } else {
1801 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1802 RTC_DCHECK(!track ||
1803 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1804 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001805 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001806 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001807 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001808 bool set_track_succeeded = sender->SetTrack(track);
1809 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001810 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001811 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001812 return sender;
1813}
1814
1815rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1816PeerConnection::CreateReceiver(cricket::MediaType media_type,
1817 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001818 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1819 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001820 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001821 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001822 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1823 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001824 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001825 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001826 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001827 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001828 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1829 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001830 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001831 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001832 return receiver;
1833}
1834
1835rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1836PeerConnection::CreateAndAddTransceiver(
1837 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1838 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1839 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001840 // Ensure that the new sender does not have an ID that is already in use by
1841 // another sender.
1842 // Allow receiver IDs to conflict since those come from remote SDP (which
1843 // could be invalid, but should not cause a crash).
1844 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001845 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001846 signaling_thread(),
1847 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001848 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001849 transceiver->internal()->SignalNegotiationNeeded.connect(
1850 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001851 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001852}
1853
Steve Anton52d86772018-02-20 15:48:12 -08001854void PeerConnection::OnNegotiationNeeded() {
1855 RTC_DCHECK_RUN_ON(signaling_thread());
1856 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001857 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001858}
1859
deadbeeffac06552015-11-25 11:26:01 -08001860rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001861 const std::string& kind,
1862 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001863 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001864 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1865 "Plan SdpSemantics. Please use AddTransceiver "
1866 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001867 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001868 if (IsClosed()) {
1869 return nullptr;
1870 }
Steve Anton4171afb2017-11-20 10:20:22 -08001871
Seth Hampson5b4f0752018-04-02 16:31:36 -07001872 // Internally we need to have one stream with Plan B semantics, so we
1873 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001874 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001875 if (stream_id.empty()) {
1876 stream_ids.push_back(rtc::CreateRandomUuid());
1877 RTC_LOG(LS_INFO)
1878 << "No stream_id specified for sender. Generated stream ID: "
1879 << stream_ids[0];
1880 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001881 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001882 }
1883
Steve Anton4171afb2017-11-20 10:20:22 -08001884 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001885 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001886 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001887 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001888 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001889 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001890 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001891 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001892 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001893 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001894 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001895 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001896 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001897 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001898 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001899 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001900 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001901 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001902 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001903 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001904 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001905
deadbeefe1f9d832016-01-14 15:35:42 -08001906 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001907}
1908
deadbeef70ab1a12015-09-28 16:53:55 -07001909std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1910 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001912 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001913 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001914 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001915 }
1916 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001917}
1918
Steve Anton4171afb2017-11-20 10:20:22 -08001919std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1920PeerConnection::GetSendersInternal() const {
1921 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1922 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001923 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001924 auto senders = transceiver->internal()->senders();
1925 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1926 }
1927 return all_senders;
1928}
1929
deadbeef70ab1a12015-09-28 16:53:55 -07001930std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1931PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001932 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001933 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001934 for (const auto& receiver : GetReceiversInternal()) {
1935 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001936 }
1937 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001938}
1939
Steve Anton4171afb2017-11-20 10:20:22 -08001940std::vector<
1941 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1942PeerConnection::GetReceiversInternal() const {
1943 std::vector<
1944 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1945 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001946 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001947 auto receivers = transceiver->internal()->receivers();
1948 all_receivers.insert(all_receivers.end(), receivers.begin(),
1949 receivers.end());
1950 }
1951 return all_receivers;
1952}
1953
Steve Anton9158ef62017-11-27 13:01:52 -08001954std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1955PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001956 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001957 RTC_CHECK(IsUnifiedPlan())
1958 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001959 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001960 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001961 all_transceivers.push_back(transceiver);
1962 }
1963 return all_transceivers;
1964}
1965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001967 MediaStreamTrackInterface* track,
1968 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001969 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001970 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001971 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 return false;
1974 }
1975
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001976 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001977 // The StatsCollector is used to tell if a track is valid because it may
1978 // remember tracks that the PeerConnection previously removed.
1979 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001980 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1981 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001982 return false;
1983 }
Steve Antonad182762018-09-05 20:22:40 +00001984 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1985 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 return true;
1987}
1988
hbos74e1a4f2016-09-15 23:33:01 -07001989void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001990 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001991 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001992 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001993 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001994 stats_collector_->GetStatsReport(callback);
1995}
1996
Henrik Boström1df1bf82018-03-20 13:24:20 +01001997void PeerConnection::GetStats(
1998 rtc::scoped_refptr<RtpSenderInterface> selector,
1999 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2000 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002001 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002002 RTC_DCHECK(callback);
2003 RTC_DCHECK(stats_collector_);
2004 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2005 if (selector) {
2006 for (const auto& proxy_transceiver : transceivers_) {
2007 for (const auto& proxy_sender :
2008 proxy_transceiver->internal()->senders()) {
2009 if (proxy_sender == selector) {
2010 internal_sender = proxy_sender->internal();
2011 break;
2012 }
2013 }
2014 if (internal_sender)
2015 break;
2016 }
2017 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002018 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01002019 // belong to the PeerConnection (in Plan B, senders can be removed from the
2020 // PeerConnection). This means that "all the stats objects representing the
2021 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2022 // produces an empty stats report.
2023 stats_collector_->GetStatsReport(internal_sender, callback);
2024}
2025
2026void PeerConnection::GetStats(
2027 rtc::scoped_refptr<RtpReceiverInterface> selector,
2028 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2029 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002030 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002031 RTC_DCHECK(callback);
2032 RTC_DCHECK(stats_collector_);
2033 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2034 if (selector) {
2035 for (const auto& proxy_transceiver : transceivers_) {
2036 for (const auto& proxy_receiver :
2037 proxy_transceiver->internal()->receivers()) {
2038 if (proxy_receiver == selector) {
2039 internal_receiver = proxy_receiver->internal();
2040 break;
2041 }
2042 }
2043 if (internal_receiver)
2044 break;
2045 }
2046 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002047 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01002048 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2049 // the PeerConnection). This means that "all the stats objects representing
2050 // the selector" is an empty set. Invoking GetStatsReport() with a null
2051 // selector produces an empty stats report.
2052 stats_collector_->GetStatsReport(internal_receiver, callback);
2053}
2054
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002056 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002057 return signaling_state_;
2058}
2059
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060PeerConnectionInterface::IceConnectionState
2061PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002062 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 return ice_connection_state_;
2064}
2065
Alex Loiko9289eda2018-11-23 16:18:59 +00002066PeerConnectionInterface::IceConnectionState
2067PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002068 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002069 return standardized_ice_connection_state_;
2070}
2071
Jonas Olsson635474e2018-10-18 15:58:17 +02002072PeerConnectionInterface::PeerConnectionState
2073PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002074 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002075 return connection_state_;
2076}
2077
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002078PeerConnectionInterface::IceGatheringState
2079PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002080 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002081 return ice_gathering_state_;
2082}
2083
Yves Gerey665174f2018-06-19 15:03:05 +02002084rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085 const std::string& label,
2086 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002087 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002088 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002089
deadbeefab9b2d12015-10-14 11:33:11 -07002090 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002091
kwibergd1fe2812016-04-27 06:47:29 -07002092 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002093 if (config) {
2094 internal_config.reset(new InternalDataChannelInit(*config));
2095 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002096 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002097 InternalCreateDataChannel(label, internal_config.get()));
2098 if (!channel.get()) {
2099 return nullptr;
2100 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002102 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2103 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002104 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002105 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002106 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002107 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 return DataChannelProxy::Create(signaling_thread(), channel.get());
2109}
2110
Henrik Boström79b69802019-07-18 11:16:56 +02002111void PeerConnection::RestartIce() {
2112 RTC_DCHECK_RUN_ON(signaling_thread());
2113 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2114 current_local_description_.get(), pending_local_description_.get());
2115 UpdateNegotiationNeeded();
2116}
2117
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002119 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002120 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002121 // Chain this operation. If asynchronous operations are pending on the chain,
2122 // this operation will be queued to be invoked, otherwise the contents of the
2123 // lambda will execute immediately.
2124 operations_chain_->ChainOperation(
2125 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2126 observer_refptr =
2127 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2128 options](std::function<void()> operations_chain_callback) {
2129 // Abort early if |this_weak_ptr| is no longer valid.
2130 if (!this_weak_ptr) {
2131 observer_refptr->OnFailure(
2132 RTCError(RTCErrorType::INTERNAL_ERROR,
2133 "CreateOffer failed because the session was shut down"));
2134 operations_chain_callback();
2135 return;
2136 }
2137 // The operation completes asynchronously when the wrapper is invoked.
2138 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2139 observer_wrapper(new rtc::RefCountedObject<
2140 CreateSessionDescriptionObserverOperationWrapper>(
2141 std::move(observer_refptr),
2142 std::move(operations_chain_callback)));
2143 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2144 });
2145}
2146
2147void PeerConnection::DoCreateOffer(
2148 const RTCOfferAnswerOptions& options,
2149 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2150 RTC_DCHECK_RUN_ON(signaling_thread());
2151 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002152
nisse7ce109a2017-01-31 00:57:56 -08002153 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002154 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002155 return;
2156 }
deadbeefab9b2d12015-10-14 11:33:11 -07002157
Steve Anton8d3444d2017-10-20 15:30:51 -07002158 if (IsClosed()) {
2159 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002160 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002161 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002162 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002163 return;
2164 }
2165
Steve Anton25ca0ac2019-06-25 10:40:48 -07002166 // If a session error has occurred the PeerConnection is in a possibly
2167 // inconsistent state so fail right away.
2168 if (session_error() != SessionError::kNone) {
2169 std::string error_message = GetSessionErrorMsg();
2170 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2171 PostCreateSessionDescriptionFailure(
2172 observer,
2173 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2174 return;
2175 }
2176
zhihuang1c378ed2017-08-17 14:10:50 -07002177 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002178 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002179 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002180 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002181 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002182 return;
2183 }
2184
Steve Anton22da89f2018-01-25 13:58:07 -08002185 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2186 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2187 if (IsUnifiedPlan()) {
2188 RTCError error = HandleLegacyOfferOptions(options);
2189 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002190 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002191 return;
2192 }
2193 }
2194
zhihuang1c378ed2017-08-17 14:10:50 -07002195 cricket::MediaSessionOptions session_options;
2196 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002197 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198}
2199
Steve Anton22da89f2018-01-25 13:58:07 -08002200RTCError PeerConnection::HandleLegacyOfferOptions(
2201 const RTCOfferAnswerOptions& options) {
2202 RTC_DCHECK(IsUnifiedPlan());
2203
2204 if (options.offer_to_receive_audio == 0) {
2205 RemoveRecvDirectionFromReceivingTransceiversOfType(
2206 cricket::MEDIA_TYPE_AUDIO);
2207 } else if (options.offer_to_receive_audio == 1) {
2208 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2209 } else if (options.offer_to_receive_audio > 1) {
2210 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2211 "offer_to_receive_audio > 1 is not supported.");
2212 }
2213
2214 if (options.offer_to_receive_video == 0) {
2215 RemoveRecvDirectionFromReceivingTransceiversOfType(
2216 cricket::MEDIA_TYPE_VIDEO);
2217 } else if (options.offer_to_receive_video == 1) {
2218 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2219 } else if (options.offer_to_receive_video > 1) {
2220 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2221 "offer_to_receive_video > 1 is not supported.");
2222 }
2223
2224 return RTCError::OK();
2225}
2226
2227void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2228 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002229 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002230 RtpTransceiverDirection new_direction =
2231 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2232 if (new_direction != transceiver->direction()) {
2233 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2234 << " transceiver (MID="
2235 << transceiver->mid().value_or("<not set>") << ") from "
2236 << RtpTransceiverDirectionToString(
2237 transceiver->direction())
2238 << " to "
2239 << RtpTransceiverDirectionToString(new_direction)
2240 << " since CreateOffer specified offer_to_receive=0";
2241 transceiver->internal()->set_direction(new_direction);
2242 }
Steve Anton22da89f2018-01-25 13:58:07 -08002243 }
2244}
2245
2246void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2247 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002248 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002249 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002250 RTC_LOG(LS_INFO)
2251 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2252 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002253 RtpTransceiverInit init;
2254 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002255 AddTransceiver(media_type, nullptr, init,
2256 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002257 }
2258}
2259
2260std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2261PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2262 std::vector<
2263 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2264 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002265 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002266 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002267 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2268 receiving_transceivers.push_back(transceiver);
2269 }
2270 }
2271 return receiving_transceivers;
2272}
2273
htaa2a49d92016-03-04 02:51:39 -08002274void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2275 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002276 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002277 // Chain this operation. If asynchronous operations are pending on the chain,
2278 // this operation will be queued to be invoked, otherwise the contents of the
2279 // lambda will execute immediately.
2280 operations_chain_->ChainOperation(
2281 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2282 observer_refptr =
2283 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2284 options](std::function<void()> operations_chain_callback) {
2285 // Abort early if |this_weak_ptr| is no longer valid.
2286 if (!this_weak_ptr) {
2287 observer_refptr->OnFailure(RTCError(
2288 RTCErrorType::INTERNAL_ERROR,
2289 "CreateAnswer failed because the session was shut down"));
2290 operations_chain_callback();
2291 return;
2292 }
2293 // The operation completes asynchronously when the wrapper is invoked.
2294 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2295 observer_wrapper(new rtc::RefCountedObject<
2296 CreateSessionDescriptionObserverOperationWrapper>(
2297 std::move(observer_refptr),
2298 std::move(operations_chain_callback)));
2299 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2300 });
2301}
2302
2303void PeerConnection::DoCreateAnswer(
2304 const RTCOfferAnswerOptions& options,
2305 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2306 RTC_DCHECK_RUN_ON(signaling_thread());
2307 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002308 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002309 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002310 return;
2311 }
2312
Steve Anton25ca0ac2019-06-25 10:40:48 -07002313 // If a session error has occurred the PeerConnection is in a possibly
2314 // inconsistent state so fail right away.
2315 if (session_error() != SessionError::kNone) {
2316 std::string error_message = GetSessionErrorMsg();
2317 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2318 PostCreateSessionDescriptionFailure(
2319 observer,
2320 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2321 return;
2322 }
2323
Steve Antondffead82018-02-06 10:31:29 -08002324 if (!(signaling_state_ == kHaveRemoteOffer ||
2325 signaling_state_ == kHaveLocalPrAnswer)) {
2326 std::string error =
2327 "PeerConnection cannot create an answer in a state other than "
2328 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002329 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002330 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002331 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002332 return;
2333 }
2334
Steve Antondffead82018-02-06 10:31:29 -08002335 // The remote description should be set if we're in the right state.
2336 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002337
Steve Anton22da89f2018-01-25 13:58:07 -08002338 if (IsUnifiedPlan()) {
2339 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2340 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2341 "supported with Unified Plan semantics. Use the "
2342 "RtpTransceiver API instead.";
2343 }
2344 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2345 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2346 "supported with Unified Plan semantics. Use the "
2347 "RtpTransceiver API instead.";
2348 }
2349 }
2350
htaa2a49d92016-03-04 02:51:39 -08002351 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002352 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002353
Steve Antond25da372017-11-06 14:50:29 -08002354 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002355}
2356
2357void PeerConnection::SetLocalDescription(
2358 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002359 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002360 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002361 // Chain this operation. If asynchronous operations are pending on the chain,
2362 // this operation will be queued to be invoked, otherwise the contents of the
2363 // lambda will execute immediately.
2364 operations_chain_->ChainOperation(
2365 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2366 observer_refptr =
2367 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2368 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2369 std::function<void()> operations_chain_callback) mutable {
2370 // Abort early if |this_weak_ptr| is no longer valid.
2371 if (!this_weak_ptr) {
2372 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2373 // |observer_refptr| that the operation failed in this case.
2374 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2375 // the consistent thing would be to inform the observer here.
2376 operations_chain_callback();
2377 return;
2378 }
2379 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2380 std::move(observer_refptr));
2381 // DoSetLocalDescription() is currently implemented as a synchronous
2382 // operation but where the |observer|'s callbacks are invoked
2383 // asynchronously in a post to OnMessage().
2384 // For backwards-compatability reasons, we declare the operation as
2385 // completed here (rather than in OnMessage()). This ensures that:
2386 // - This operation is not keeping the PeerConnection alive past this
2387 // point.
2388 // - Subsequent offer/answer operations can start immediately (without
2389 // waiting for OnMessage()).
2390 operations_chain_callback();
2391 });
2392}
Steve Anton8a006912017-12-04 15:25:56 -08002393
Henrik Boströma3728d32019-10-28 12:09:49 +01002394void PeerConnection::DoSetLocalDescription(
2395 std::unique_ptr<SessionDescriptionInterface> desc,
2396 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2397 RTC_DCHECK_RUN_ON(signaling_thread());
2398 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-16 17:08:42 -08002399
nisse7ce109a2017-01-31 00:57:56 -08002400 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002401 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 return;
2403 }
Steve Anton8a006912017-12-04 15:25:56 -08002404
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002406 PostSetSessionDescriptionFailure(
2407 observer,
2408 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002409 return;
2410 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002411
Steve Anton80dd7b52018-02-16 17:08:42 -08002412 // If a session error has occurred the PeerConnection is in a possibly
2413 // inconsistent state so fail right away.
2414 if (session_error() != SessionError::kNone) {
2415 std::string error_message = GetSessionErrorMsg();
2416 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002417 PostSetSessionDescriptionFailure(
2418 observer,
2419 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002420 return;
2421 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002422
Eldar Rello5ab79e62019-10-09 18:29:44 +03002423 // For SLD we support only explicit rollback.
2424 if (desc->GetType() == SdpType::kRollback) {
2425 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002426 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002427 if (error.ok()) {
2428 PostSetSessionDescriptionSuccess(observer);
2429 } else {
2430 PostSetSessionDescriptionFailure(observer, std::move(error));
2431 }
2432 } else {
2433 PostSetSessionDescriptionFailure(
2434 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2435 "Rollback not supported in Plan B"));
2436 }
2437 return;
2438 }
2439
Steve Anton80dd7b52018-02-16 17:08:42 -08002440 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2441 if (!error.ok()) {
2442 std::string error_message = GetSetDescriptionErrorMessage(
2443 cricket::CS_LOCAL, desc->GetType(), error);
2444 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002445 PostSetSessionDescriptionFailure(
2446 observer,
2447 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002448 return;
2449 }
2450
2451 // Grab the description type before moving ownership to ApplyLocalDescription,
2452 // which may destroy it before returning.
2453 const SdpType type = desc->GetType();
2454
2455 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002456 // |desc| may be destroyed at this point.
2457
2458 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002459 // If ApplyLocalDescription fails, the PeerConnection could be in an
2460 // inconsistent state, so act conservatively here and set the session error
2461 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2462 SetSessionError(SessionError::kContent, error.message());
2463 std::string error_message =
2464 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2465 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002466 PostSetSessionDescriptionFailure(
2467 observer,
2468 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002469 return;
2470 }
Steve Anton8a006912017-12-04 15:25:56 -08002471 RTC_DCHECK(local_description());
2472
2473 PostSetSessionDescriptionSuccess(observer);
2474
Steve Antonad182762018-09-05 20:22:40 +00002475 // MaybeStartGathering needs to be called after posting
2476 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2477 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002478 transport_controller_->MaybeStartGathering();
2479
Steve Antona3a92c22017-12-07 10:27:41 -08002480 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002481 // TODO(deadbeef): We already had to hop to the network thread for
2482 // MaybeStartGathering...
2483 network_thread()->Invoke<void>(
2484 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2485 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002486 // Make UMA notes about what was agreed to.
2487 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002488 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002489
2490 if (IsUnifiedPlan()) {
2491 bool was_negotiation_needed = is_negotiation_needed_;
2492 UpdateNegotiationNeeded();
2493 if (signaling_state() == kStable && was_negotiation_needed &&
2494 is_negotiation_needed_) {
2495 Observer()->OnRenegotiationNeeded();
2496 }
2497 }
2498
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002499 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002500}
2501
2502RTCError PeerConnection::ApplyLocalDescription(
2503 std::unique_ptr<SessionDescriptionInterface> desc) {
2504 RTC_DCHECK_RUN_ON(signaling_thread());
2505 RTC_DCHECK(desc);
2506
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002507 // Update stats here so that we have the most recent stats for tracks and
2508 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002509 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002510
Steve Antondcc3c022017-12-22 16:02:54 -08002511 // Take a reference to the old local description since it's used below to
2512 // compare against the new local description. When setting the new local
2513 // description, grab ownership of the replaced session description in case it
2514 // is the same as |old_local_description|, to keep it alive for the duration
2515 // of the method.
2516 const SessionDescriptionInterface* old_local_description =
2517 local_description();
2518 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002519 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002520 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002521 replaced_local_description = pending_local_description_
2522 ? std::move(pending_local_description_)
2523 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002524 current_local_description_ = std::move(desc);
2525 pending_local_description_ = nullptr;
2526 current_remote_description_ = std::move(pending_remote_description_);
2527 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002528 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002529 pending_local_description_ = std::move(desc);
2530 }
2531 // The session description to apply now must be accessed by
2532 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002533 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002534
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002535 // Report statistics about any use of simulcast.
2536 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2537 *local_description()->description());
2538
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002539 if (!is_caller_) {
2540 if (remote_description()) {
2541 // Remote description was applied first, so this PC is the callee.
2542 is_caller_ = false;
2543 } else {
2544 // Local description is applied first, so this PC is the caller.
2545 is_caller_ = true;
2546 }
2547 }
2548
Zhi Huange830e682018-03-30 10:48:35 -07002549 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2550 if (!error.ok()) {
2551 return error;
2552 }
2553
Steve Antondcc3c022017-12-22 16:02:54 -08002554 if (IsUnifiedPlan()) {
2555 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002556 cricket::CS_LOCAL, *local_description(), old_local_description,
2557 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002558 if (!error.ok()) {
2559 return error;
2560 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002561 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2562 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002563 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002564 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2565 // Note that code paths that don't set MID won't be able to use
2566 // information about DTLS transports.
2567 if (transceiver->mid()) {
2568 auto dtls_transport =
2569 LookupDtlsTransportByMidInternal(*transceiver->mid());
2570 transceiver->internal()->sender_internal()->set_transport(
2571 dtls_transport);
2572 transceiver->internal()->receiver_internal()->set_transport(
2573 dtls_transport);
2574 }
2575
Steve Antondcc3c022017-12-22 16:02:54 -08002576 const ContentInfo* content =
2577 FindMediaSectionForTransceiver(transceiver, local_description());
2578 if (!content) {
2579 continue;
2580 }
2581 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002582 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2583 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002584 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002585 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2586 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2587 // "recvonly", process the removal of a remote track for the media
2588 // description, given transceiver, removeList, and muteTracks.
2589 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2590 (transceiver->internal()->fired_direction() &&
2591 RtpTransceiverDirectionHasRecv(
2592 *transceiver->internal()->fired_direction()))) {
2593 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2594 &removed_streams);
2595 }
2596 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2597 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002598 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002599 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002600 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002601 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002602 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002603 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002604 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002605 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002606 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002607 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002608 }
2609 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002610 // Media channels will be created only when offer is set. These may use new
2611 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002612 if (type == SdpType::kOffer) {
2613 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2614 // description is applied. Restore back to old description.
2615 RTCError error = CreateChannels(*local_description()->description());
2616 if (!error.ok()) {
2617 return error;
2618 }
2619 }
Steve Antondcc3c022017-12-22 16:02:54 -08002620 // Remove unused channels if MediaContentDescription is rejected.
2621 RemoveUnusedChannels(local_description()->description());
2622 }
Steve Anton8a006912017-12-04 15:25:56 -08002623
Zhi Huange830e682018-03-30 10:48:35 -07002624 error = UpdateSessionState(type, cricket::CS_LOCAL,
2625 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002626 if (!error.ok()) {
2627 return error;
2628 }
Steve Antondcc3c022017-12-22 16:02:54 -08002629
Steve Anton8a006912017-12-04 15:25:56 -08002630 if (remote_description()) {
2631 // Now that we have a local description, we can push down remote candidates.
2632 UseCandidatesInSessionDescription(remote_description());
2633 }
2634
2635 pending_ice_restarts_.clear();
2636 if (session_error() != SessionError::kNone) {
2637 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2638 }
2639
deadbeefab9b2d12015-10-14 11:33:11 -07002640 // If setting the description decided our SSL role, allocate any necessary
2641 // SCTP sids.
2642 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002643 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002644 AllocateSctpSids(role);
2645 }
2646
Steve Antond3679212018-01-17 17:41:02 -08002647 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002648 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002649 const ContentInfo* content =
2650 FindMediaSectionForTransceiver(transceiver, local_description());
2651 if (!content) {
2652 continue;
2653 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002654 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2655 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002656 // 0 is a special value meaning "this sender has no associated send
2657 // stream". Need to call this so the sender won't attempt to configure
2658 // a no longer existing stream and run into DCHECKs in the lower
2659 // layers.
2660 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002661 } else {
2662 // Get the StreamParams from the channel which could generate SSRCs.
2663 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002664 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002665 streams[0].stream_ids());
2666 transceiver->internal()->sender_internal()->SetSsrc(
2667 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002668 }
2669 }
2670 } else {
2671 // Plan B semantics.
2672
Steve Antondcc3c022017-12-22 16:02:54 -08002673 // Update state and SSRC of local MediaStreams and DataChannels based on the
2674 // local session description.
2675 const cricket::ContentInfo* audio_content =
2676 GetFirstAudioContent(local_description()->description());
2677 if (audio_content) {
2678 if (audio_content->rejected) {
2679 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2680 } else {
2681 const cricket::AudioContentDescription* audio_desc =
2682 audio_content->media_description()->as_audio();
2683 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2684 }
deadbeeffaac4972015-11-12 15:33:07 -08002685 }
deadbeefab9b2d12015-10-14 11:33:11 -07002686
Steve Antondcc3c022017-12-22 16:02:54 -08002687 const cricket::ContentInfo* video_content =
2688 GetFirstVideoContent(local_description()->description());
2689 if (video_content) {
2690 if (video_content->rejected) {
2691 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2692 } else {
2693 const cricket::VideoContentDescription* video_desc =
2694 video_content->media_description()->as_video();
2695 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2696 }
deadbeeffaac4972015-11-12 15:33:07 -08002697 }
deadbeefab9b2d12015-10-14 11:33:11 -07002698 }
2699
2700 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002701 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002702 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002703 const cricket::RtpDataContentDescription* rtp_data_desc =
2704 data_content->media_description()->as_rtp_data();
2705 // rtp_data_desc will be null if this is an SCTP description.
2706 if (rtp_data_desc) {
2707 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002708 }
2709 }
2710
Henrik Boström79b69802019-07-18 11:16:56 +02002711 if (type == SdpType::kAnswer &&
2712 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2713 *current_local_description_)) {
2714 local_ice_credentials_to_replace_->ClearIceCredentials();
2715 }
2716
Steve Anton8a006912017-12-04 15:25:56 -08002717 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718}
2719
Steve Anton06817cd2018-12-18 15:55:30 -08002720// The SDP parser used to populate these values by default for the 'content
2721// name' if an a=mid line was absent.
2722static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2723 switch (media_type) {
2724 case cricket::MEDIA_TYPE_AUDIO:
2725 return cricket::CN_AUDIO;
2726 case cricket::MEDIA_TYPE_VIDEO:
2727 return cricket::CN_VIDEO;
2728 case cricket::MEDIA_TYPE_DATA:
2729 return cricket::CN_DATA;
2730 }
2731 RTC_NOTREACHED();
2732 return "";
2733}
2734
2735void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002736 cricket::SessionDescription* new_remote_description) {
2737 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002738 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002739 const cricket::ContentInfos& local_contents =
2740 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002741 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002742 const cricket::ContentInfos& remote_contents =
2743 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002744 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002745 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2746 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002747 if (!content.name.empty()) {
2748 continue;
2749 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002750 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002751 absl::string_view source_explanation;
2752 if (IsUnifiedPlan()) {
2753 if (i < local_contents.size()) {
2754 new_mid = local_contents[i].name;
2755 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002756 } else if (i < remote_contents.size()) {
2757 new_mid = remote_contents[i].name;
2758 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002759 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002760 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002761 source_explanation = "generated just now";
2762 }
2763 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002764 new_mid = std::string(
2765 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002766 source_explanation = "to match pre-existing behavior";
2767 }
Steve Antond7180cc2019-02-07 10:44:53 -08002768 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002769 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002770 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002771 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2772 << " is missing an a=mid line. Filling in the value '"
2773 << new_mid << "' " << source_explanation << ".";
2774 }
2775}
2776
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002778 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 12:09:49 +01002779 SessionDescriptionInterface* desc_ptr) {
2780 RTC_DCHECK_RUN_ON(signaling_thread());
2781 // Chain this operation. If asynchronous operations are pending on the chain,
2782 // this operation will be queued to be invoked, otherwise the contents of the
2783 // lambda will execute immediately.
2784 operations_chain_->ChainOperation(
2785 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2786 observer_refptr =
2787 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2788 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2789 std::function<void()> operations_chain_callback) mutable {
2790 // Abort early if |this_weak_ptr| is no longer valid.
2791 if (!this_weak_ptr) {
2792 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2793 // inform the |observer_refptr| that the operation failed in this
2794 // case.
2795 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2796 // the consistent thing would be to inform the observer here.
2797 operations_chain_callback();
2798 return;
2799 }
2800 this_weak_ptr->DoSetRemoteDescription(
2801 std::move(desc),
2802 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2803 new SetRemoteDescriptionObserverAdapter(
2804 this_weak_ptr.get(), std::move(observer_refptr))));
2805 // DoSetRemoteDescription() is currently implemented as a synchronous
2806 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2807 // the |observer|'s callbacks are invoked asynchronously in a post to
2808 // OnMessage().
2809 // For backwards-compatability reasons, we declare the operation as
2810 // completed here (rather than in OnMessage()). This ensures that:
2811 // - This operation is not keeping the PeerConnection alive past this
2812 // point.
2813 // - Subsequent offer/answer operations can start immediately (without
2814 // waiting for OnMessage()).
2815 operations_chain_callback();
2816 });
Henrik Boström31638672017-11-23 17:48:32 +01002817}
2818
2819void PeerConnection::SetRemoteDescription(
2820 std::unique_ptr<SessionDescriptionInterface> desc,
2821 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002822 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002823 // Chain this operation. If asynchronous operations are pending on the chain,
2824 // this operation will be queued to be invoked, otherwise the contents of the
2825 // lambda will execute immediately.
2826 operations_chain_->ChainOperation(
2827 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2828 desc = std::move(desc)](
2829 std::function<void()> operations_chain_callback) mutable {
2830 // Abort early if |this_weak_ptr| is no longer valid.
2831 if (!this_weak_ptr) {
2832 // For consistency with DoSetRemoteDescription(), we DO inform the
2833 // |observer| that the operation failed in this case.
2834 observer->OnSetRemoteDescriptionComplete(RTCError(
2835 RTCErrorType::INVALID_STATE,
2836 "Failed to set remote offer sdp: failed because the session was "
2837 "shut down"));
2838 operations_chain_callback();
2839 return;
2840 }
2841 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
2842 std::move(observer));
2843 // DoSetRemoteDescription() is currently implemented as a synchronous
2844 // operation. The |observer| will already have been informed that it
2845 // completed, and we can mark this operation as complete without any
2846 // loose ends.
2847 operations_chain_callback();
2848 });
2849}
2850
2851void PeerConnection::DoSetRemoteDescription(
2852 std::unique_ptr<SessionDescriptionInterface> desc,
2853 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
2854 RTC_DCHECK_RUN_ON(signaling_thread());
2855 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002856
nisse7ce109a2017-01-31 00:57:56 -08002857 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002858 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 return;
2860 }
Steve Anton8a006912017-12-04 15:25:56 -08002861
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002862 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002863 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002864 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 return;
2866 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002867
Steve Anton80dd7b52018-02-16 17:08:42 -08002868 // If a session error has occurred the PeerConnection is in a possibly
2869 // inconsistent state so fail right away.
2870 if (session_error() != SessionError::kNone) {
2871 std::string error_message = GetSessionErrorMsg();
2872 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2873 observer->OnSetRemoteDescriptionComplete(
2874 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2875 return;
2876 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03002877 if (IsUnifiedPlan()) {
2878 if (configuration_.enable_implicit_rollback) {
2879 if (desc->GetType() == SdpType::kOffer &&
2880 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002881 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002882 }
2883 }
2884 // Explicit rollback.
2885 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002886 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03002887 return;
2888 }
2889 } else if (desc->GetType() == SdpType::kRollback) {
2890 observer->OnSetRemoteDescriptionComplete(
2891 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2892 "Rollback not supported in Plan B"));
2893 return;
2894 }
Steve Antonba42e992018-04-09 14:10:01 -07002895 if (desc->GetType() == SdpType::kOffer) {
2896 // Report to UMA the format of the received offer.
2897 ReportSdpFormatReceived(*desc);
2898 }
2899
Steve Anton06817cd2018-12-18 15:55:30 -08002900 // Handle remote descriptions missing a=mid lines for interop with legacy end
2901 // points.
2902 FillInMissingRemoteMids(desc->description());
2903
Steve Anton80dd7b52018-02-16 17:08:42 -08002904 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002905 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002906 std::string error_message = GetSetDescriptionErrorMessage(
2907 cricket::CS_REMOTE, desc->GetType(), error);
2908 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002909 observer->OnSetRemoteDescriptionComplete(
2910 RTCError(error.type(), std::move(error_message)));
2911 return;
2912 }
Steve Anton71439a62018-02-15 11:53:06 -08002913
Steve Anton80dd7b52018-02-16 17:08:42 -08002914 // Grab the description type before moving ownership to
2915 // ApplyRemoteDescription, which may destroy it before returning.
2916 const SdpType type = desc->GetType();
2917
2918 error = ApplyRemoteDescription(std::move(desc));
2919 // |desc| may be destroyed at this point.
2920
2921 if (!error.ok()) {
2922 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2923 // inconsistent state, so act conservatively here and set the session error
2924 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2925 SetSessionError(SessionError::kContent, error.message());
2926 std::string error_message =
2927 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2928 RTC_LOG(LS_ERROR) << error_message;
2929 observer->OnSetRemoteDescriptionComplete(
2930 RTCError(error.type(), std::move(error_message)));
2931 return;
2932 }
2933 RTC_DCHECK(remote_description());
2934
2935 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002936 // TODO(deadbeef): We already had to hop to the network thread for
2937 // MaybeStartGathering...
2938 network_thread()->Invoke<void>(
2939 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2940 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002941 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002942 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002943 }
2944
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002945 if (IsUnifiedPlan()) {
2946 bool was_negotiation_needed = is_negotiation_needed_;
2947 UpdateNegotiationNeeded();
2948 if (signaling_state() == kStable && was_negotiation_needed &&
2949 is_negotiation_needed_) {
2950 Observer()->OnRenegotiationNeeded();
2951 }
2952 }
2953
Steve Anton8a006912017-12-04 15:25:56 -08002954 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002955 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002956}
2957
2958RTCError PeerConnection::ApplyRemoteDescription(
2959 std::unique_ptr<SessionDescriptionInterface> desc) {
2960 RTC_DCHECK_RUN_ON(signaling_thread());
2961 RTC_DCHECK(desc);
2962
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002963 // Update stats here so that we have the most recent stats for tracks and
2964 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002965 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002966
Steve Antondcc3c022017-12-22 16:02:54 -08002967 // Take a reference to the old remote description since it's used below to
2968 // compare against the new remote description. When setting the new remote
2969 // description, grab ownership of the replaced session description in case it
2970 // is the same as |old_remote_description|, to keep it alive for the duration
2971 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002972 const SessionDescriptionInterface* old_remote_description =
2973 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002974 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002975 SdpType type = desc->GetType();
2976 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002977 replaced_remote_description = pending_remote_description_
2978 ? std::move(pending_remote_description_)
2979 : std::move(current_remote_description_);
2980 current_remote_description_ = std::move(desc);
2981 pending_remote_description_ = nullptr;
2982 current_local_description_ = std::move(pending_local_description_);
2983 } else {
2984 replaced_remote_description = std::move(pending_remote_description_);
2985 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002986 }
Steve Anton8a006912017-12-04 15:25:56 -08002987 // The session description to apply now must be accessed by
2988 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002989 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002991 // Report statistics about any use of simulcast.
2992 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2993 *remote_description()->description());
2994
Zhi Huange830e682018-03-30 10:48:35 -07002995 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2996 if (!error.ok()) {
2997 return error;
2998 }
Steve Anton8a006912017-12-04 15:25:56 -08002999 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08003000 if (IsUnifiedPlan()) {
3001 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003002 cricket::CS_REMOTE, *remote_description(), local_description(),
3003 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08003004 if (!error.ok()) {
3005 return error;
3006 }
Steve Antondcc3c022017-12-22 16:02:54 -08003007 } else {
Zhi Huange830e682018-03-30 10:48:35 -07003008 // Media channels will be created only when offer is set. These may use new
3009 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08003010 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07003011 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08003012 // description is applied. Restore back to old description.
3013 RTCError error = CreateChannels(*remote_description()->description());
3014 if (!error.ok()) {
3015 return error;
3016 }
3017 }
Steve Antondcc3c022017-12-22 16:02:54 -08003018 // Remove unused channels if MediaContentDescription is rejected.
3019 RemoveUnusedChannels(remote_description()->description());
3020 }
Steve Anton8a006912017-12-04 15:25:56 -08003021
Zhi Huange830e682018-03-30 10:48:35 -07003022 // NOTE: Candidates allocation will be initiated only when
3023 // SetLocalDescription is called.
3024 error = UpdateSessionState(type, cricket::CS_REMOTE,
3025 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08003026 if (!error.ok()) {
3027 return error;
3028 }
3029
3030 if (local_description() &&
3031 !UseCandidatesInSessionDescription(remote_description())) {
3032 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3033 }
3034
3035 if (old_remote_description) {
3036 for (const cricket::ContentInfo& content :
3037 old_remote_description->description()->contents()) {
3038 // Check if this new SessionDescription contains new ICE ufrag and
3039 // password that indicates the remote peer requests an ICE restart.
3040 // TODO(deadbeef): When we start storing both the current and pending
3041 // remote description, this should reset pending_ice_restarts and compare
3042 // against the current description.
3043 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3044 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08003045 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08003046 pending_ice_restarts_.insert(content.name);
3047 }
3048 } else {
3049 // We retain all received candidates only if ICE is not restarted.
3050 // When ICE is restarted, all previous candidates belong to an old
3051 // generation and should not be kept.
3052 // TODO(deadbeef): This goes against the W3C spec which says the remote
3053 // description should only contain candidates from the last set remote
3054 // description plus any candidates added since then. We should remove
3055 // this once we're sure it won't break anything.
3056 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3057 old_remote_description, content.name, mutable_remote_description());
3058 }
3059 }
3060 }
3061
3062 if (session_error() != SessionError::kNone) {
3063 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3064 }
3065
3066 // Set the the ICE connection state to connecting since the connection may
3067 // become writable with peer reflexive candidates before any remote candidate
3068 // is signaled.
3069 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3070 // is to have a new signal the indicates a change in checking state from the
3071 // transport and expose a new checking() member from transport that can be
3072 // read to determine the current checking state. The existing SignalConnecting
3073 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08003074 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07003075 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08003076 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3077 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3078 }
3079
deadbeefab9b2d12015-10-14 11:33:11 -07003080 // If setting the description decided our SSL role, allocate any necessary
3081 // SCTP sids.
3082 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003083 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07003084 AllocateSctpSids(role);
3085 }
3086
Steve Antondcc3c022017-12-22 16:02:54 -08003087 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08003088 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07003089 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07003090 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08003091 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07003092 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01003093 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08003094 const ContentInfo* content =
3095 FindMediaSectionForTransceiver(transceiver, remote_description());
3096 if (!content) {
3097 continue;
3098 }
3099 const MediaContentDescription* media_desc = content->media_description();
3100 RtpTransceiverDirection local_direction =
3101 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003102 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3103 // RTCSessionDescription: Set the associated remote streams given
3104 // transceiver.[[Receiver]], msids, addList, and removeList".
3105 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3106 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3107 std::vector<std::string> stream_ids;
3108 if (!media_desc->streams().empty()) {
3109 // The remote description has signaled the stream IDs.
3110 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08003111 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003112 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3113 << " (" << GetStreamIdsString(stream_ids) << ").";
3114 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3115 stream_ids, &added_streams,
3116 &removed_streams);
3117 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3118 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3119 // and transceiver's current direction is neither sendrecv nor recvonly,
3120 // process the addition of a remote track for the media description.
3121 if (!transceiver->fired_direction() ||
3122 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3123 RTC_LOG(LS_INFO)
3124 << "Processing the addition of a remote track for MID="
3125 << content->name << ".";
3126 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01003127 }
Steve Antondcc3c022017-12-22 16:02:54 -08003128 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003129 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07003130 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3131 // removal of a remote track for the media description, given transceiver,
3132 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08003133 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07003134 (transceiver->fired_direction() &&
3135 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3136 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3137 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08003138 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003139 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07003140 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003141 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07003142 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08003143 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003144 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07003145 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08003146 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003147 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3148 if (transceiver->mid()) {
3149 auto dtls_transport =
3150 LookupDtlsTransportByMidInternal(*transceiver->mid());
3151 transceiver->internal()->sender_internal()->set_transport(
3152 dtls_transport);
3153 transceiver->internal()->receiver_internal()->set_transport(
3154 dtls_transport);
3155 }
Steve Antondcc3c022017-12-22 16:02:54 -08003156 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003157 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07003158 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08003159 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07003160 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3161 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08003162 transceiver->Stop();
3163 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003164 if (!content->rejected &&
3165 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07003166 if (!media_desc->streams().empty() &&
3167 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07003168 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3169 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3170 } else {
3171 transceiver->internal()
3172 ->receiver_internal()
3173 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08003174 }
Steve Antond3679212018-01-17 17:41:02 -08003175 }
Steve Antondcc3c022017-12-22 16:02:54 -08003176 }
Steve Antonc49bcd92018-02-14 14:28:13 -08003177 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003178 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01003179 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08003180 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003181 observer->OnTrack(transceiver);
3182 observer->OnAddTrack(transceiver->receiver(),
3183 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08003184 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003185 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003186 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08003187 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003188 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003189 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07003190 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003191 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003192 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07003193 }
Steve Antondcc3c022017-12-22 16:02:54 -08003194 }
3195
Henrik Boströmfdb92012017-11-09 19:55:44 +01003196 const cricket::ContentInfo* audio_content =
3197 GetFirstAudioContent(remote_description()->description());
3198 const cricket::ContentInfo* video_content =
3199 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003200 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003201 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003202 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003203 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003204 const cricket::RtpDataContentDescription* rtp_data_desc =
3205 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003206
3207 // Check if the descriptions include streams, just in case the peer supports
3208 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01003209 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08003210 (audio_desc && !audio_desc->streams().empty()) ||
3211 (video_desc && !video_desc->streams().empty())) {
3212 remote_peer_supports_msid_ = true;
3213 }
deadbeefab9b2d12015-10-14 11:33:11 -07003214
3215 // We wait to signal new streams until we finish processing the description,
3216 // since only at that point will new streams have all their tracks.
3217 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3218
Steve Antondcc3c022017-12-22 16:02:54 -08003219 if (!IsUnifiedPlan()) {
3220 // TODO(steveanton): When removing RTP senders/receivers in response to a
3221 // rejected media section, there is some cleanup logic that expects the
3222 // voice/ video channel to still be set. But in this method the voice/video
3223 // channel would have been destroyed by the SetRemoteDescription caller
3224 // above so the cleanup that relies on them fails to run. The RemoveSenders
3225 // calls should be moved to right before the DestroyChannel calls to fix
3226 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003227
Steve Antondcc3c022017-12-22 16:02:54 -08003228 // Find all audio rtp streams and create corresponding remote AudioTracks
3229 // and MediaStreams.
3230 if (audio_content) {
3231 if (audio_content->rejected) {
3232 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3233 } else {
3234 bool default_audio_track_needed =
3235 !remote_peer_supports_msid_ &&
3236 RtpTransceiverDirectionHasSend(audio_desc->direction());
3237 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3238 default_audio_track_needed, audio_desc->type(),
3239 new_streams);
3240 }
deadbeeffaac4972015-11-12 15:33:07 -08003241 }
deadbeefab9b2d12015-10-14 11:33:11 -07003242
Steve Antondcc3c022017-12-22 16:02:54 -08003243 // Find all video rtp streams and create corresponding remote VideoTracks
3244 // and MediaStreams.
3245 if (video_content) {
3246 if (video_content->rejected) {
3247 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3248 } else {
3249 bool default_video_track_needed =
3250 !remote_peer_supports_msid_ &&
3251 RtpTransceiverDirectionHasSend(video_desc->direction());
3252 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3253 default_video_track_needed, video_desc->type(),
3254 new_streams);
3255 }
deadbeeffaac4972015-11-12 15:33:07 -08003256 }
deadbeefab9b2d12015-10-14 11:33:11 -07003257
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003258 // If this is an RTP data transport, update the DataChannels with the
3259 // information from the remote peer.
3260 if (rtp_data_desc) {
3261 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003262 }
deadbeefab9b2d12015-10-14 11:33:11 -07003263
Steve Antondcc3c022017-12-22 16:02:54 -08003264 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003265 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003266 for (size_t i = 0; i < new_streams->count(); ++i) {
3267 MediaStreamInterface* new_stream = new_streams->at(i);
3268 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003269 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003270 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3271 }
deadbeefab9b2d12015-10-14 11:33:11 -07003272
Steve Antondcc3c022017-12-22 16:02:54 -08003273 UpdateEndedRemoteMediaStreams();
3274 }
deadbeefab9b2d12015-10-14 11:33:11 -07003275
Henrik Boström79b69802019-07-18 11:16:56 +02003276 if (type == SdpType::kAnswer &&
3277 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3278 *current_local_description_)) {
3279 local_ice_credentials_to_replace_->ClearIceCredentials();
3280 }
3281
Steve Anton8a006912017-12-04 15:25:56 -08003282 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003283}
3284
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003285void PeerConnection::SetAssociatedRemoteStreams(
3286 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3287 const std::vector<std::string>& stream_ids,
3288 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3289 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3290 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3291 for (const std::string& stream_id : stream_ids) {
3292 rtc::scoped_refptr<MediaStreamInterface> stream =
3293 remote_streams_->find(stream_id);
3294 if (!stream) {
3295 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3296 MediaStream::Create(stream_id));
3297 remote_streams_->AddStream(stream);
3298 added_streams->push_back(stream);
3299 }
3300 media_streams.push_back(stream);
3301 }
3302 // Special case: "a=msid" missing, use random stream ID.
3303 if (media_streams.empty() &&
3304 !(remote_description()->description()->msid_signaling() &
3305 cricket::kMsidSignalingMediaSection)) {
3306 if (!missing_msid_default_stream_) {
3307 missing_msid_default_stream_ = MediaStreamProxy::Create(
3308 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3309 added_streams->push_back(missing_msid_default_stream_);
3310 }
3311 media_streams.push_back(missing_msid_default_stream_);
3312 }
3313 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3314 receiver->streams();
3315 // SetStreams() will add/remove the receiver's track to/from the streams. This
3316 // differs from the spec - the spec uses an "addList" and "removeList" to
3317 // update the stream-track relationships in a later step. We do this earlier,
3318 // changing the order of things, but the end-result is the same.
3319 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3320 // instead. https://crbug.com/webrtc/9480
3321 receiver->SetStreams(media_streams);
3322 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3323}
3324
Steve Anton0f5400a2018-07-17 14:25:36 -07003325void PeerConnection::ProcessRemovalOfRemoteTrack(
3326 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3327 transceiver,
3328 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3329 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3330 RTC_DCHECK(transceiver->mid());
3331 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3332 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003333 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003334 transceiver->internal()->receiver_internal()->streams();
3335 // This will remove the remote track from the streams.
3336 transceiver->internal()->receiver_internal()->set_stream_ids({});
3337 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003338 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3339}
3340
3341void PeerConnection::RemoveRemoteStreamsIfEmpty(
3342 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3343 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3344 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3345 // streams, see if the stream was removed by checking if this was the last
3346 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003347 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003348 if (remote_stream->GetAudioTracks().empty() &&
3349 remote_stream->GetVideoTracks().empty()) {
3350 remote_streams_->RemoveStream(remote_stream);
3351 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003352 }
3353 }
3354}
3355
Steve Antondcc3c022017-12-22 16:02:54 -08003356RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3357 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003358 const SessionDescriptionInterface& new_session,
3359 const SessionDescriptionInterface* old_local_description,
3360 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003361 RTC_DCHECK(IsUnifiedPlan());
3362
Steve Anton7464fca2018-01-19 11:10:37 -08003363 const cricket::ContentGroup* bundle_group = nullptr;
3364 if (new_session.GetType() == SdpType::kOffer) {
3365 auto bundle_group_or_error =
3366 GetEarlyBundleGroup(*new_session.description());
3367 if (!bundle_group_or_error.ok()) {
3368 return bundle_group_or_error.MoveError();
3369 }
3370 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003371 }
Steve Antondcc3c022017-12-22 16:02:54 -08003372
Steve Antondcc3c022017-12-22 16:02:54 -08003373 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003374 for (size_t i = 0; i < new_contents.size(); ++i) {
3375 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003376 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003377 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003378 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3379 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003380 const cricket::ContentInfo* old_local_content = nullptr;
3381 if (old_local_description &&
3382 i < old_local_description->description()->contents().size()) {
3383 old_local_content =
3384 &old_local_description->description()->contents()[i];
3385 }
3386 const cricket::ContentInfo* old_remote_content = nullptr;
3387 if (old_remote_description &&
3388 i < old_remote_description->description()->contents().size()) {
3389 old_remote_content =
3390 &old_remote_description->description()->contents()[i];
3391 }
Steve Antondcc3c022017-12-22 16:02:54 -08003392 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003393 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3394 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003395 if (!transceiver_or_error.ok()) {
3396 return transceiver_or_error.MoveError();
3397 }
3398 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003399 RTCError error =
3400 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3401 if (!error.ok()) {
3402 return error;
3403 }
3404 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003405 if (GetDataMid() && new_content.name != *GetDataMid()) {
3406 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003407 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3408 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003409 continue;
3410 }
3411 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3412 if (!error.ok()) {
3413 return error;
3414 }
Steve Antondcc3c022017-12-22 16:02:54 -08003415 } else {
3416 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3417 "Unknown section type.");
3418 }
3419 }
3420
3421 return RTCError::OK();
3422}
3423
3424RTCError PeerConnection::UpdateTransceiverChannel(
3425 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3426 transceiver,
3427 const cricket::ContentInfo& content,
3428 const cricket::ContentGroup* bundle_group) {
3429 RTC_DCHECK(IsUnifiedPlan());
3430 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003431 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003432 if (content.rejected) {
3433 if (channel) {
3434 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003435 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003436 }
3437 } else {
3438 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003439 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003440 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003441 } else {
Steve Anton69470252018-02-09 11:43:08 -08003442 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003443 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003444 }
3445 if (!channel) {
3446 LOG_AND_RETURN_ERROR(
3447 RTCErrorType::INTERNAL_ERROR,
3448 "Failed to create channel for mid=" + content.name);
3449 }
3450 transceiver->internal()->SetChannel(channel);
3451 }
3452 }
3453 return RTCError::OK();
3454}
3455
Steve Antonfa2260d2017-12-28 16:38:23 -08003456RTCError PeerConnection::UpdateDataChannel(
3457 cricket::ContentSource source,
3458 const cricket::ContentInfo& content,
3459 const cricket::ContentGroup* bundle_group) {
3460 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003461 // If data channels are disabled, ignore this media section. CreateAnswer
3462 // will take care of rejecting it.
3463 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003464 }
3465 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003466 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Steve Antonfa2260d2017-12-28 16:38:23 -08003467 DestroyDataChannel();
3468 } else {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07003469 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003470 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003471 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003472 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3473 "Failed to create data channel.");
3474 }
3475 }
3476 if (source == cricket::CS_REMOTE) {
3477 const MediaContentDescription* data_desc = content.media_description();
3478 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3479 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3480 }
3481 }
3482 }
3483 return RTCError::OK();
3484}
3485
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003486// This method will extract any send encodings that were sent by the remote
3487// connection. This is currently only relevant for Simulcast scenario (where
3488// the number of layers may be communicated by the server).
3489static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3490 const MediaContentDescription& desc) {
3491 if (!desc.HasSimulcast()) {
3492 return {};
3493 }
3494 std::vector<RtpEncodingParameters> result;
3495 const SimulcastDescription& simulcast = desc.simulcast_description();
3496
3497 // This is a remote description, the parameters we are after should appear
3498 // as receive streams.
3499 for (const auto& alternatives : simulcast.receive_layers()) {
3500 RTC_DCHECK(!alternatives.empty());
3501 // There is currently no way to specify or choose from alternatives.
3502 // We will always use the first alternative, which is the most preferred.
3503 const SimulcastLayer& layer = alternatives[0];
3504 RtpEncodingParameters parameters;
3505 parameters.rid = layer.rid;
3506 parameters.active = !layer.is_paused;
3507 result.push_back(parameters);
3508 }
3509
3510 return result;
3511}
3512
3513static RTCError UpdateSimulcastLayerStatusInSender(
3514 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003515 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003516 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003517 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003518 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003519
3520 // The simulcast envelope cannot be changed, only the status of the streams.
3521 // So we will iterate over the send encodings rather than the layers.
3522 for (RtpEncodingParameters& encoding : parameters.encodings) {
3523 auto iter = std::find_if(layers.begin(), layers.end(),
3524 [&encoding](const SimulcastLayer& layer) {
3525 return layer.rid == encoding.rid;
3526 });
3527 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003528 if (iter == layers.end()) {
3529 disabled_layers.push_back(encoding.rid);
3530 continue;
3531 }
3532
3533 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003534 }
3535
Amit Hilbuch619b2942019-02-26 15:55:19 -08003536 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003537 if (result.ok()) {
3538 result = sender->DisableEncodingLayers(disabled_layers);
3539 }
3540
3541 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003542}
3543
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003544static bool SimulcastIsRejected(
3545 const ContentInfo* local_content,
3546 const MediaContentDescription& answer_media_desc) {
3547 bool simulcast_offered = local_content &&
3548 local_content->media_description() &&
3549 local_content->media_description()->HasSimulcast();
3550 bool simulcast_answered = answer_media_desc.HasSimulcast();
3551 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3552 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3553 return simulcast_offered && (!simulcast_answered || !rids_supported);
3554}
3555
Amit Hilbuch2297d332019-02-19 12:49:22 -08003556static RTCError DisableSimulcastInSender(
3557 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003558 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003559 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003560 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003561 return RTCError::OK();
3562 }
3563
Amit Hilbuch2297d332019-02-19 12:49:22 -08003564 std::vector<std::string> disabled_layers;
3565 std::transform(
3566 parameters.encodings.begin() + 1, parameters.encodings.end(),
3567 std::back_inserter(disabled_layers),
3568 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3569 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003570}
3571
Steve Antondcc3c022017-12-22 16:02:54 -08003572RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3573PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003574 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003575 size_t mline_index,
3576 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003577 const ContentInfo* old_local_content,
3578 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003579 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003580 // If this is an offer then the m= section might be recycled. If the m=
3581 // section is being recycled (defined as: rejected in the current local or
3582 // remote description and not rejected in new description), dissociate the
3583 // currently associated RtpTransceiver by setting its mid property to null,
3584 // and discard the mapping between the transceiver and its m= section index.
3585 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3586 old_remote_content)) {
3587 // We want to dissociate the transceiver that has the rejected mid.
3588 const std::string& old_mid =
3589 (old_local_content && old_local_content->rejected)
3590 ? old_local_content->name
3591 : old_remote_content->name;
3592 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003593 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003594 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3595 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003596 old_transceiver->internal()->set_mid(absl::nullopt);
3597 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003598 }
3599 }
3600 const MediaContentDescription* media_desc = content.media_description();
3601 auto transceiver = GetAssociatedTransceiver(content.name);
3602 if (source == cricket::CS_LOCAL) {
3603 // Find the RtpTransceiver that corresponds to this m= section, using the
3604 // mapping between transceivers and m= section indices established when
3605 // creating the offer.
3606 if (!transceiver) {
3607 transceiver = GetTransceiverByMLineIndex(mline_index);
3608 }
3609 if (!transceiver) {
3610 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3611 "Unknown transceiver");
3612 }
3613 } else {
3614 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3615 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3616 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003617 // When simulcast is requested, a transceiver cannot be associated because
3618 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003619 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003620 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3621 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003622 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3623 }
3624 // If no RtpTransceiver was found in the previous step, create one with a
3625 // recvonly direction.
3626 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003627 RTC_LOG(LS_INFO) << "Adding "
3628 << cricket::MediaTypeToString(media_desc->type())
3629 << " transceiver for MID=" << content.name
3630 << " at i=" << mline_index
3631 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003632 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003633 std::vector<RtpEncodingParameters> send_encodings =
3634 GetSendEncodingsFromRemoteDescription(*media_desc);
3635 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3636 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003637 std::string receiver_id;
3638 if (!media_desc->streams().empty()) {
3639 receiver_id = media_desc->streams()[0].id;
3640 } else {
3641 receiver_id = rtc::CreateRandomUuid();
3642 }
3643 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003644 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003645 transceiver->internal()->set_direction(
3646 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003647 if (type == SdpType::kOffer) {
3648 transceiver_stable_states_by_transceivers_[transceiver] =
3649 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3650 absl::nullopt, absl::nullopt, true);
3651 }
Steve Antondcc3c022017-12-22 16:02:54 -08003652 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003653 // Check if the offer indicated simulcast but the answer rejected it.
3654 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003655 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003656 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003657 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003658 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003659 if (!error.ok()) {
3660 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3661 return std::move(error);
3662 }
3663 }
Steve Antondcc3c022017-12-22 16:02:54 -08003664 }
3665 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003666 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003667 LOG_AND_RETURN_ERROR(
3668 RTCErrorType::INVALID_PARAMETER,
3669 "Transceiver type does not match media description type.");
3670 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003671 if (media_desc->HasSimulcast()) {
3672 std::vector<SimulcastLayer> layers =
3673 source == cricket::CS_LOCAL
3674 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3675 : media_desc->simulcast_description()
3676 .receive_layers()
3677 .GetAllLayers();
3678 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003679 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003680 if (!error.ok()) {
3681 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3682 return std::move(error);
3683 }
3684 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003685 if (type == SdpType::kOffer) {
3686 // Make sure we don't overwrite existing stable states and that the
3687 // state is really going to change when adding new record to the map.
3688 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3689 if (it == transceiver_stable_states_by_transceivers_.end() &&
3690 (transceiver->internal()->mid() != content.name ||
3691 transceiver->internal()->mline_index() != mline_index)) {
3692 transceiver_stable_states_by_transceivers_[transceiver] =
3693 TransceiverStableState(transceiver->internal()->direction(),
3694 transceiver->internal()->mid(),
3695 transceiver->internal()->mline_index(), false);
3696 }
3697 }
3698
Steve Antondcc3c022017-12-22 16:02:54 -08003699 // Associate the found or created RtpTransceiver with the m= section by
3700 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3701 // section, and establish a mapping between the transceiver and the index of
3702 // the m= section.
3703 transceiver->internal()->set_mid(content.name);
3704 transceiver->internal()->set_mline_index(mline_index);
3705 return std::move(transceiver);
3706}
3707
3708rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3709PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3710 RTC_DCHECK(IsUnifiedPlan());
3711 for (auto transceiver : transceivers_) {
3712 if (transceiver->mid() == mid) {
3713 return transceiver;
3714 }
3715 }
3716 return nullptr;
3717}
3718
3719rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3720PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3721 RTC_DCHECK(IsUnifiedPlan());
3722 for (auto transceiver : transceivers_) {
3723 if (transceiver->internal()->mline_index() == mline_index) {
3724 return transceiver;
3725 }
3726 }
3727 return nullptr;
3728}
3729
3730rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3731PeerConnection::FindAvailableTransceiverToReceive(
3732 cricket::MediaType media_type) const {
3733 RTC_DCHECK(IsUnifiedPlan());
3734 // From JSEP section 5.10 (Applying a Remote Description):
3735 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3736 // the same type that were added to the PeerConnection by addTrack and are not
3737 // associated with any m= section and are not stopped, find the first such
3738 // RtpTransceiver.
3739 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003740 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003741 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3742 !transceiver->stopped()) {
3743 return transceiver;
3744 }
3745 }
3746 return nullptr;
3747}
3748
Steve Antoned10bd92017-12-05 10:52:59 -08003749const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3750 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3751 transceiver,
3752 const SessionDescriptionInterface* sdesc) const {
3753 RTC_DCHECK(transceiver);
3754 RTC_DCHECK(sdesc);
3755 if (IsUnifiedPlan()) {
3756 if (!transceiver->internal()->mid()) {
3757 // This transceiver is not associated with a media section yet.
3758 return nullptr;
3759 }
3760 return sdesc->description()->GetContentByName(
3761 *transceiver->internal()->mid());
3762 } else {
3763 // Plan B only allows at most one audio and one video section, so use the
3764 // first media section of that type.
3765 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003766 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003767 }
3768}
3769
deadbeef46c73892016-11-16 19:42:04 -08003770PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003771 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003772 return configuration_;
3773}
3774
Niels Möller2579f0c2019-08-19 09:58:17 +02003775RTCError PeerConnection::SetConfiguration(
3776 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003777 RTC_DCHECK_RUN_ON(signaling_thread());
3778 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003779 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003780 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003781 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3782 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003783 }
3784
Qingsi Wanga2d60672018-04-11 16:57:45 -07003785 // According to JSEP, after setLocalDescription, changing the candidate pool
3786 // size is not allowed, and changing the set of ICE servers will not result
3787 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003788 if (local_description() && configuration.ice_candidate_pool_size !=
3789 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003790 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3791 "Can't change candidate pool size after calling "
3792 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003793 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003794
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003795 if (local_description() &&
3796 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3798 "Can't change media_transport after calling "
3799 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003800 }
3801
3802 if (remote_description() &&
3803 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003804 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3805 "Can't change media_transport after calling "
3806 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003807 }
3808
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003809 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003810 configuration.use_media_transport_for_data_channels !=
3811 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003812 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3813 "Can't change media_transport_for_data_channels "
3814 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003815 }
3816
3817 if (remote_description() &&
3818 configuration.use_media_transport_for_data_channels !=
3819 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003820 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3821 "Can't change media_transport_for_data_channels "
3822 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003823 }
3824
3825 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003826 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003827 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3828 "Can't change crypto_options after calling "
3829 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003830 }
3831
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003832 if (local_description() && configuration.use_datagram_transport !=
3833 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003834 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3835 "Can't change use_datagram_transport "
3836 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003837 }
3838
3839 if (remote_description() && configuration.use_datagram_transport !=
3840 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003841 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3842 "Can't change use_datagram_transport "
3843 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003844 }
3845
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003846 if (local_description() &&
3847 configuration.use_datagram_transport_for_data_channels !=
3848 configuration_.use_datagram_transport_for_data_channels) {
3849 LOG_AND_RETURN_ERROR(
3850 RTCErrorType::INVALID_MODIFICATION,
3851 "Can't change use_datagram_transport_for_data_channels "
3852 "after calling SetLocalDescription.");
3853 }
3854
3855 if (remote_description() &&
3856 configuration.use_datagram_transport_for_data_channels !=
3857 configuration_.use_datagram_transport_for_data_channels) {
3858 LOG_AND_RETURN_ERROR(
3859 RTCErrorType::INVALID_MODIFICATION,
3860 "Can't change use_datagram_transport_for_data_channels "
3861 "after calling SetRemoteDescription.");
3862 }
3863
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003864 if (local_description() &&
3865 configuration.use_datagram_transport_for_data_channels_receive_only !=
3866 configuration_
3867 .use_datagram_transport_for_data_channels_receive_only) {
3868 LOG_AND_RETURN_ERROR(
3869 RTCErrorType::INVALID_MODIFICATION,
3870 "Can't change use_datagram_transport_for_data_channels_receive_only "
3871 "after calling SetLocalDescription.");
3872 }
3873
3874 if (remote_description() &&
3875 configuration.use_datagram_transport_for_data_channels_receive_only !=
3876 configuration_
3877 .use_datagram_transport_for_data_channels_receive_only) {
3878 LOG_AND_RETURN_ERROR(
3879 RTCErrorType::INVALID_MODIFICATION,
3880 "Can't change use_datagram_transport_for_data_channels_receive_only "
3881 "after calling SetRemoteDescription.");
3882 }
3883
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003884 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003885 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003886 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003887 *configuration.use_datagram_transport) ||
3888 (configuration.use_datagram_transport_for_data_channels &&
3889 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003890 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3891 << "Media transport requires MaxBundle policy.";
3892 }
3893
deadbeef293e9262017-01-11 12:28:30 -08003894 // The simplest (and most future-compatible) way to tell if the config was
3895 // modified in an invalid way is to copy each property we do support
3896 // modifying, then use operator==. There are far more properties we don't
3897 // support modifying than those we do, and more could be added.
3898 RTCConfiguration modified_config = configuration_;
3899 modified_config.servers = configuration.servers;
3900 modified_config.type = configuration.type;
3901 modified_config.ice_candidate_pool_size =
3902 configuration.ice_candidate_pool_size;
3903 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003904 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07003905 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3906 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003907 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003908 modified_config.ice_check_interval_strong_connectivity =
3909 configuration.ice_check_interval_strong_connectivity;
3910 modified_config.ice_check_interval_weak_connectivity =
3911 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003912 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3913 modified_config.ice_unwritable_min_checks =
3914 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003915 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003916 modified_config.stun_candidate_keepalive_interval =
3917 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003918 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003919 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003920 modified_config.active_reset_srtp_params =
3921 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003922 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003923 modified_config.use_media_transport_for_data_channels =
3924 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003925 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003926 modified_config.use_datagram_transport_for_data_channels =
3927 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003928 modified_config.use_datagram_transport_for_data_channels_receive_only =
3929 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02003930 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 12:23:02 +02003931 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -08003932 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003933 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3934 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08003935 }
3936
Steve Anton038834f2017-07-14 15:59:59 -07003937 // Validate the modified configuration.
3938 RTCError validate_error = ValidateConfiguration(modified_config);
3939 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003940 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07003941 }
3942
deadbeef293e9262017-01-11 12:28:30 -08003943 // Note that this isn't possible through chromium, since it's an unsigned
3944 // short in WebIDL.
3945 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003946 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003947 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08003948 }
3949
3950 // Parse ICE servers before hopping to network thread.
3951 cricket::ServerAddresses stun_servers;
3952 std::vector<cricket::RelayServerConfig> turn_servers;
3953 RTCErrorType parse_error =
3954 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3955 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003956 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08003957 }
Jonas Oreland3c028422019-08-22 16:16:35 +02003958 // Add the turn logging id to all turn servers
3959 for (cricket::RelayServerConfig& turn_server : turn_servers) {
3960 turn_server.turn_logging_id = configuration.turn_logging_id;
3961 }
3962
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003963 // Note if STUN or TURN servers were supplied.
3964 if (!stun_servers.empty()) {
3965 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3966 }
3967 if (!turn_servers.empty()) {
3968 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3969 }
deadbeef293e9262017-01-11 12:28:30 -08003970
3971 // In theory this shouldn't fail.
3972 if (!network_thread()->Invoke<bool>(
3973 RTC_FROM_HERE,
3974 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3975 stun_servers, turn_servers, modified_config.type,
3976 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003977 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003978 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003979 modified_config.stun_candidate_keepalive_interval,
3980 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003981 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3982 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08003983 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003984
deadbeefd1a38b52016-12-10 13:15:33 -08003985 // As described in JSEP, calling setConfiguration with new ICE servers or
3986 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3987 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003988 if (modified_config.servers != configuration_.servers ||
3989 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07003990 modified_config.GetTurnPortPrunePolicy() !=
3991 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08003992 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003993 }
skvladd1f5fda2017-02-03 16:54:05 -08003994
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003995 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003996
3997 use_datagram_transport_ = datagram_transport_config_.enabled &&
3998 modified_config.use_datagram_transport.value_or(
3999 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004000 use_datagram_transport_for_data_channels_ =
4001 datagram_transport_data_channel_config_.enabled &&
4002 modified_config.use_datagram_transport_for_data_channels.value_or(
4003 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004004 use_datagram_transport_for_data_channels_receive_only_ =
4005 modified_config.use_datagram_transport_for_data_channels_receive_only
4006 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08004007 transport_controller_->SetMediaTransportSettings(
4008 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07004009 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004010 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4011 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08004012
Zhi Huangb57e1692018-06-12 11:41:11 -07004013 if (configuration_.active_reset_srtp_params !=
4014 modified_config.active_reset_srtp_params) {
4015 transport_controller_->SetActiveResetSrtpParams(
4016 modified_config.active_reset_srtp_params);
4017 }
4018
philipel16cec3b2019-10-25 12:23:02 +02004019 if (modified_config.allow_codec_switching.has_value()) {
4020 video_media_channel()->SetVideoCodecSwitchingEnabled(
4021 *modified_config.allow_codec_switching);
4022 }
4023
deadbeef293e9262017-01-11 12:28:30 -08004024 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01004025 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 09:58:17 +02004026 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00004027}
4028
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004029bool PeerConnection::AddIceCandidate(
4030 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004031 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004032 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07004033 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004034 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004035 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07004036 return false;
4037 }
Steve Antond25da372017-11-06 14:50:29 -08004038
4039 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004040 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004041 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004042 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08004043 return false;
4044 }
4045
4046 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07004047 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004048 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08004049 return false;
4050 }
4051
4052 bool valid = false;
4053 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4054 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004055 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08004056 return false;
4057 }
4058
4059 // Add this candidate to the remote session description.
4060 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07004061 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004062 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08004063 return false;
4064 }
4065
4066 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004067 bool result = UseCandidate(ice_candidate);
4068 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004069 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02004070 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4071 } else {
4072 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4073 }
4074 return result;
Steve Antond25da372017-11-06 14:50:29 -08004075 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07004076 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004077 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08004078 return true;
4079 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004080}
4081
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004082bool PeerConnection::RemoveIceCandidates(
4083 const std::vector<cricket::Candidate>& candidates) {
4084 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004085 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07004086 if (IsClosed()) {
4087 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4088 return false;
4089 }
4090
Steve Antond25da372017-11-06 14:50:29 -08004091 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004092 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4093 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08004094 return false;
4095 }
4096
4097 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004098 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08004099 return false;
4100 }
4101
4102 size_t number_removed =
4103 mutable_remote_description()->RemoveCandidates(candidates);
4104 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004105 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07004106 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004107 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01004108 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08004109 }
4110
4111 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07004112 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4113 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004114 RTC_LOG(LS_ERROR)
4115 << "RemoveIceCandidates: Error when removing remote candidates: "
4116 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08004117 }
4118 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004119}
4120
Niels Möller0c4f7be2018-05-07 14:01:37 +02004121RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07004122 if (!worker_thread()->IsCurrent()) {
4123 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02004124 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07004125 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01004126 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07004127
Niels Möller0c4f7be2018-05-07 14:01:37 +02004128 const bool has_min = bitrate.min_bitrate_bps.has_value();
4129 const bool has_start = bitrate.start_bitrate_bps.has_value();
4130 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07004131 if (has_min && *bitrate.min_bitrate_bps < 0) {
4132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4133 "min_bitrate_bps <= 0");
4134 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02004135 if (has_start) {
4136 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004137 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004138 "start_bitrate_bps < min_bitrate_bps");
4139 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07004140 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4141 "curent_bitrate_bps < 0");
4142 }
4143 }
4144 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02004145 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004146 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004147 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07004148 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4150 "max_bitrate_bps < min_bitrate_bps");
4151 } else if (*bitrate.max_bitrate_bps < 0) {
4152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4153 "max_bitrate_bps < 0");
4154 }
4155 }
4156
zstein4b979802017-06-02 14:37:37 -07004157 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07004158 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07004159
4160 return RTCError::OK();
4161}
4162
henrika5f6bf242017-11-01 11:06:56 +01004163void PeerConnection::SetAudioPlayout(bool playout) {
4164 if (!worker_thread()->IsCurrent()) {
4165 worker_thread()->Invoke<void>(
4166 RTC_FROM_HERE,
4167 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4168 return;
4169 }
4170 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004171 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004172 audio_state->SetPlayout(playout);
4173}
4174
4175void PeerConnection::SetAudioRecording(bool recording) {
4176 if (!worker_thread()->IsCurrent()) {
4177 worker_thread()->Invoke<void>(
4178 RTC_FROM_HERE,
4179 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4180 return;
4181 }
4182 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004183 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004184 audio_state->SetRecording(recording);
4185}
4186
Steve Anton8c0f7a72017-10-03 10:03:10 -07004187std::unique_ptr<rtc::SSLCertificate>
4188PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004189 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4190 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07004191 return nullptr;
4192 }
Steve Antonf25303e2018-10-16 15:23:31 -07004193 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07004194}
4195
Zhi Huang70b820f2018-01-27 14:16:15 -08004196std::unique_ptr<rtc::SSLCertChain>
4197PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01004198 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08004199 auto audio_transceiver = GetFirstAudioTransceiver();
4200 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08004201 return nullptr;
4202 }
Zhi Huang70b820f2018-01-27 14:16:15 -08004203 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08004204 audio_transceiver->internal()->channel()->transport_name());
4205}
4206
4207rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4208PeerConnection::GetFirstAudioTransceiver() const {
4209 for (auto transceiver : transceivers_) {
4210 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4211 return transceiver;
4212 }
4213 }
4214 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08004215}
4216
Bjorn Tereliusde939432017-11-20 17:38:14 +01004217bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4218 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01004219 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02004220 RTC_FROM_HERE,
4221 [this, output = std::move(output), output_period_ms]() mutable {
4222 return StartRtcEventLog_w(std::move(output), output_period_ms);
4223 });
ivoc14d5dbe2016-07-04 07:06:55 -07004224}
4225
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004226bool PeerConnection::StartRtcEventLog(
4227 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004228 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4229 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4230 output_period_ms = 5000;
4231 }
4232 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004233}
4234
ivoc14d5dbe2016-07-04 07:06:55 -07004235void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004236 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004237 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4238}
4239
Harald Alvestrandad88c882018-11-28 16:47:46 +01004240rtc::scoped_refptr<DtlsTransportInterface>
4241PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004242 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004243 return transport_controller_->LookupDtlsTransportByMid(mid);
4244}
4245
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004246rtc::scoped_refptr<DtlsTransport>
4247PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004248 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004249 return transport_controller_->LookupDtlsTransportByMid(mid);
4250}
4251
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004252rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4253 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004254 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004255 if (!sctp_mid_) {
4256 return nullptr;
4257 }
4258 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004259}
4260
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004261const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004262 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004263 return pending_local_description_ ? pending_local_description_.get()
4264 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004265}
4266
4267const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004268 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004269 return pending_remote_description_ ? pending_remote_description_.get()
4270 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004271}
4272
deadbeeffe4a8a42016-12-20 17:56:17 -08004273const SessionDescriptionInterface* PeerConnection::current_local_description()
4274 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004276 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004277}
4278
4279const SessionDescriptionInterface* PeerConnection::current_remote_description()
4280 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004281 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004282 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004283}
4284
4285const SessionDescriptionInterface* PeerConnection::pending_local_description()
4286 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004287 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004288 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004289}
4290
4291const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4292 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004293 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004294 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004295}
4296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004297void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004298 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004299 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004300 // Update stats here so that we have the most recent stats for tracks and
4301 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004302 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004303
Steve Anton75737c02017-11-06 10:37:17 -08004304 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004305 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004306
Mirko Bonadei739baf02019-01-27 17:29:42 +01004307 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004308 transceiver->Stop();
4309 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004310
4311 // Ensure that all asynchronous stats requests are completed before destroying
4312 // the transport controller below.
4313 if (stats_collector_) {
4314 stats_collector_->WaitForPendingRequest();
4315 }
4316
4317 // Don't destroy BaseChannels until after stats has been cleaned up so that
4318 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004319 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004320
Qingsi Wang93a84392018-01-30 17:13:09 -08004321 // The event log is used in the transport controller, which must be outlived
4322 // by the former. CreateOffer by the peer connection is implemented
4323 // asynchronously and if the peer connection is closed without resetting the
4324 // WebRTC session description factory, the session description factory would
4325 // call the transport controller.
4326 webrtc_session_desc_factory_.reset();
4327 transport_controller_.reset();
4328
deadbeef42a42632017-03-10 15:18:00 -08004329 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004330 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4331 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004332
Steve Anton978b8762017-09-29 12:15:02 -07004333 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004334 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004335 call_.reset();
4336 // The event log must outlive call (and any other object that uses it).
4337 event_log_.reset();
4338 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004339 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004340 // The .h file says that observer can be discarded after close() returns.
4341 // Make sure this is true.
4342 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004343}
4344
Steve Antonad182762018-09-05 20:22:40 +00004345void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004346 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004347 switch (msg->message_id) {
4348 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4349 SetSessionDescriptionMsg* param =
4350 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4351 param->observer->OnSuccess();
4352 delete param;
4353 break;
4354 }
4355 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4356 SetSessionDescriptionMsg* param =
4357 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4358 param->observer->OnFailure(std::move(param->error));
4359 delete param;
4360 break;
4361 }
4362 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4363 CreateSessionDescriptionMsg* param =
4364 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4365 param->observer->OnFailure(std::move(param->error));
4366 delete param;
4367 break;
4368 }
4369 case MSG_GETSTATS: {
4370 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4371 StatsReports reports;
4372 stats_->GetStats(param->track, &reports);
4373 param->observer->OnComplete(reports);
4374 delete param;
4375 break;
4376 }
4377 case MSG_FREE_DATACHANNELS: {
4378 sctp_data_channels_to_free_.clear();
4379 break;
4380 }
4381 case MSG_REPORT_USAGE_PATTERN: {
4382 ReportUsagePattern();
4383 break;
4384 }
4385 default:
4386 RTC_NOTREACHED() << "Not implemented";
4387 break;
4388 }
4389}
4390
Steve Antonafb0bb72018-02-20 11:35:37 -08004391cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4392 RTC_DCHECK(!IsUnifiedPlan());
4393 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4394 GetAudioTransceiver()->internal()->channel());
4395 if (voice_channel) {
4396 return voice_channel->media_channel();
4397 } else {
4398 return nullptr;
4399 }
4400}
4401
4402cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4403 RTC_DCHECK(!IsUnifiedPlan());
4404 auto* video_channel = static_cast<cricket::VideoChannel*>(
4405 GetVideoTransceiver()->internal()->channel());
4406 if (video_channel) {
4407 return video_channel->media_channel();
4408 } else {
4409 return nullptr;
4410 }
4411}
4412
Steve Anton4171afb2017-11-20 10:20:22 -08004413void PeerConnection::CreateAudioReceiver(
4414 MediaStreamInterface* stream,
4415 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004416 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4417 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004418 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4419 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004420 auto* audio_receiver = new AudioRtpReceiver(
4421 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004422 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004423 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4424 audio_receiver->SetupUnsignaledMediaChannel();
4425 } else {
4426 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4427 }
Steve Antond3679212018-01-17 17:41:02 -08004428 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4429 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004430 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004431 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004432 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004433}
4434
Steve Anton4171afb2017-11-20 10:20:22 -08004435void PeerConnection::CreateVideoReceiver(
4436 MediaStreamInterface* stream,
4437 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004438 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4439 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004440 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4441 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004442 auto* video_receiver = new VideoRtpReceiver(
4443 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004444 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004445 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4446 video_receiver->SetupUnsignaledMediaChannel();
4447 } else {
4448 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4449 }
Steve Antond3679212018-01-17 17:41:02 -08004450 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4451 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004452 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004453 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004454 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004455}
4456
deadbeef70ab1a12015-09-28 16:53:55 -07004457// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4458// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004459rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004460 const RtpSenderInfo& remote_sender_info) {
4461 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4462 if (!receiver) {
4463 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4464 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004465 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004466 }
Steve Anton4171afb2017-11-20 10:20:22 -08004467 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4468 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4469 } else {
4470 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4471 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004472 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004473}
4474
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004475void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4476 MediaStreamInterface* stream) {
4477 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004478 RTC_DCHECK(track);
4479 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004480 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004481 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004482 // We already have a sender for this track, so just change the stream_id
4483 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004484 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004485 return;
4486 }
4487
4488 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004489 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004490 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004491 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004492 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004493 // If the sender has already been configured in SDP, we call SetSsrc,
4494 // which will connect the sender to the underlying transport. This can
4495 // occur if a local session description that contains the ID of the sender
4496 // is set before AddStream is called. It can also occur if the local
4497 // session description is not changed and RemoveStream is called, and
4498 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004499 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004500 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004501 if (sender_info) {
4502 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004503 }
4504}
4505
4506// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4507// indefinitely, when we have unified plan SDP.
4508void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4509 MediaStreamInterface* stream) {
4510 RTC_DCHECK(!IsClosed());
4511 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004512 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004513 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4514 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004515 return;
4516 }
Steve Anton4171afb2017-11-20 10:20:22 -08004517 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004518}
4519
4520void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4521 MediaStreamInterface* stream) {
4522 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004523 RTC_DCHECK(track);
4524 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004525 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004526 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004527 // We already have a sender for this track, so just change the stream_id
4528 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004529 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004530 return;
4531 }
4532
4533 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004534 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004535 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004536 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004537 GetVideoTransceiver()->internal()->AddSender(new_sender);
4538 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004539 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004540 if (sender_info) {
4541 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004542 }
4543}
4544
4545void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4546 MediaStreamInterface* stream) {
4547 RTC_DCHECK(!IsClosed());
4548 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004549 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004550 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4551 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004552 return;
4553 }
Steve Anton4171afb2017-11-20 10:20:22 -08004554 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004555}
4556
Steve Antonba818672017-11-06 10:21:57 -08004557void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004558 if (ice_connection_state_ == new_state) {
4559 return;
4560 }
4561
deadbeefcbecd352015-09-23 11:50:27 -07004562 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004563 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004564 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004565 return;
4566 }
Steve Antonba818672017-11-06 10:21:57 -08004567
Mirko Bonadei675513b2017-11-09 11:09:25 +01004568 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4569 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004570 RTC_DCHECK(ice_connection_state_ !=
4571 PeerConnectionInterface::kIceConnectionClosed);
4572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004573 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004574 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004575}
4576
Alex Loiko9289eda2018-11-23 16:18:59 +00004577void PeerConnection::SetStandardizedIceConnectionState(
4578 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004579 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004580 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004581 }
4582
4583 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004584 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004585 }
4586
4587 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4588 << standardized_ice_connection_state_ << " => " << new_state;
4589
Alex Loiko9289eda2018-11-23 16:18:59 +00004590 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004591 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004592}
4593
Jonas Olsson635474e2018-10-18 15:58:17 +02004594void PeerConnection::SetConnectionState(
4595 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004596 if (connection_state_ == new_state)
4597 return;
4598 if (IsClosed())
4599 return;
4600 connection_state_ = new_state;
4601 Observer()->OnConnectionChange(new_state);
4602}
4603
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004604void PeerConnection::OnIceGatheringChange(
4605 PeerConnectionInterface::IceGatheringState new_state) {
4606 if (IsClosed()) {
4607 return;
4608 }
4609 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004610 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004611}
4612
jbauch81bf7b02017-03-25 08:31:12 -07004613void PeerConnection::OnIceCandidate(
4614 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004615 if (IsClosed()) {
4616 return;
4617 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004618 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004619 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004620}
4621
Eldar Relloda13ea22019-06-01 12:23:43 +03004622void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4623 const std::string& url,
4624 int error_code,
4625 const std::string& error_text) {
4626 if (IsClosed()) {
4627 return;
4628 }
4629 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4630}
4631
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004632void PeerConnection::OnIceCandidatesRemoved(
4633 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004634 if (IsClosed()) {
4635 return;
4636 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004637 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004638}
4639
Alex Drake00c7ecf2019-08-06 10:54:47 -07004640void PeerConnection::OnSelectedCandidatePairChanged(
4641 const cricket::CandidatePairChangeEvent& event) {
4642 if (IsClosed()) {
4643 return;
4644 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004645
Qingsi Wangcc46b102019-09-12 11:19:01 -07004646 if (event.selected_candidate_pair.local_candidate().type() ==
4647 LOCAL_PORT_TYPE &&
4648 event.selected_candidate_pair.remote_candidate().type() ==
4649 LOCAL_PORT_TYPE) {
4650 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4651 }
4652
Alex Drake00c7ecf2019-08-06 10:54:47 -07004653 Observer()->OnIceSelectedCandidatePairChanged(event);
4654}
4655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004656void PeerConnection::ChangeSignalingState(
4657 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004658 if (signaling_state_ == signaling_state) {
4659 return;
4660 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004661 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4662 << GetSignalingStateString(signaling_state_)
4663 << " New state: "
4664 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004665 signaling_state_ = signaling_state;
4666 if (signaling_state == kClosed) {
4667 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004668 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004669 standardized_ice_connection_state_ =
4670 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004671 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4672 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004673 if (ice_gathering_state_ != kIceGatheringComplete) {
4674 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004675 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004676 }
4677 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004678 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004679}
4680
deadbeefeb459812015-12-15 19:24:43 -08004681void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4682 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004683 if (IsClosed()) {
4684 return;
4685 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004686 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004687 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004688}
4689
deadbeefeb459812015-12-15 19:24:43 -08004690void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4691 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004692 if (IsClosed()) {
4693 return;
4694 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004695 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004696 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004697}
4698
4699void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4700 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004701 if (IsClosed()) {
4702 return;
4703 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004704 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004705 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004706}
4707
4708void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4709 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004710 if (IsClosed()) {
4711 return;
4712 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004713 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004714 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004715}
4716
Henrik Boström31638672017-11-23 17:48:32 +01004717void PeerConnection::PostSetSessionDescriptionSuccess(
4718 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004719 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4720 signaling_thread()->Post(RTC_FROM_HERE, this,
4721 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004722}
4723
deadbeefab9b2d12015-10-14 11:33:11 -07004724void PeerConnection::PostSetSessionDescriptionFailure(
4725 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004726 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004727 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004728 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4729 msg->error = std::move(error);
4730 signaling_thread()->Post(RTC_FROM_HERE, this,
4731 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004732}
4733
4734void PeerConnection::PostCreateSessionDescriptionFailure(
4735 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004736 RTCError error) {
4737 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004738 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4739 msg->error = std::move(error);
4740 signaling_thread()->Post(RTC_FROM_HERE, this,
4741 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004742}
4743
zhihuang1c378ed2017-08-17 14:10:50 -07004744void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004745 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004746 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004747 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004748
Steve Antondcc3c022017-12-22 16:02:54 -08004749 if (IsUnifiedPlan()) {
4750 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4751 } else {
4752 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4753 }
4754
Steve Antonfa2260d2017-12-28 16:38:23 -08004755 // Intentionally unset the data channel type for RTP data channel with the
4756 // second condition. Otherwise the RTP data channels would be successfully
4757 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4758 // when building with chromium. We want to leave RTP data channels broken, so
4759 // people won't try to use them.
4760 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4761 session_options->data_channel_type = data_channel_type();
4762 }
4763
Steve Antondcc3c022017-12-22 16:02:54 -08004764 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004765 bool ice_restart = offer_answer_options.ice_restart ||
4766 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004767 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004768 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004769 options.transport_options.enable_ice_renomination =
4770 configuration_.enable_ice_renomination;
4771 }
4772
4773 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004774 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004775 session_options->pooled_ice_credentials =
4776 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4777 RTC_FROM_HERE,
4778 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4779 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004780 session_options->offer_extmap_allow_mixed =
4781 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004782
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004783 if (configuration_.use_media_transport ||
4784 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004785 session_options->media_transport_settings =
4786 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4787 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004788
4789 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004790 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004791 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004792 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004793 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004794 if (!params) {
4795 continue;
4796 }
4797 options.transport_options.opaque_parameters = params;
4798 if ((use_datagram_transport_ &&
4799 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4800 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4801 (use_datagram_transport_for_data_channels_ &&
4802 options.type == cricket::MEDIA_TYPE_DATA)) {
4803 options.alt_protocol = params->protocol;
4804 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004805 }
4806 }
4807
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004808 // Allow fallback for using obsolete SCTP syntax.
4809 // Note that the default in |session_options| is true, while
4810 // the default in |options| is false.
4811 session_options->use_obsolete_sctp_sdp =
4812 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004813}
4814
4815void PeerConnection::GetOptionsForPlanBOffer(
4816 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4817 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004818 // Figure out transceiver directional preferences.
4819 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4820 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4821
4822 // By default, generate sendrecv/recvonly m= sections.
4823 bool recv_audio = true;
4824 bool recv_video = true;
4825
4826 // By default, only offer a new m= section if we have media to send with it.
4827 bool offer_new_audio_description = send_audio;
4828 bool offer_new_video_description = send_video;
4829 bool offer_new_data_description = HasDataChannels();
4830
4831 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004832 if (offer_answer_options.offer_to_receive_audio !=
4833 RTCOfferAnswerOptions::kUndefined) {
4834 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004835 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004836 offer_new_audio_description ||
4837 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004838 }
Steve Antondcc3c022017-12-22 16:02:54 -08004839 if (offer_answer_options.offer_to_receive_video !=
4840 RTCOfferAnswerOptions::kUndefined) {
4841 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004842 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004843 offer_new_video_description ||
4844 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004845 }
4846
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004847 absl::optional<size_t> audio_index;
4848 absl::optional<size_t> video_index;
4849 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004850 // If a current description exists, generate m= sections in the same order,
4851 // using the first audio/video/data section that appears and rejecting
4852 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004853 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004854 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004855 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004856 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4857 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4858 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004859 }
4860
zhihuang1c378ed2017-08-17 14:10:50 -07004861 // Add audio/video/data m= sections to the end if needed.
4862 if (!audio_index && offer_new_audio_description) {
4863 session_options->media_description_options.push_back(
4864 cricket::MediaDescriptionOptions(
4865 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004866 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4867 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004868 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004869 }
zhihuang1c378ed2017-08-17 14:10:50 -07004870 if (!video_index && offer_new_video_description) {
4871 session_options->media_description_options.push_back(
4872 cricket::MediaDescriptionOptions(
4873 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004874 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4875 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004876 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004877 }
zhihuang1c378ed2017-08-17 14:10:50 -07004878 if (!data_index && offer_new_data_description) {
4879 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004880 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004881 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004882 }
4883
4884 cricket::MediaDescriptionOptions* audio_media_description_options =
4885 !audio_index ? nullptr
4886 : &session_options->media_description_options[*audio_index];
4887 cricket::MediaDescriptionOptions* video_media_description_options =
4888 !video_index ? nullptr
4889 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004890
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004891 AddPlanBRtpSenderOptions(GetSendersInternal(),
4892 audio_media_description_options,
4893 video_media_description_options,
4894 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004895}
4896
Steve Antondcc3c022017-12-22 16:02:54 -08004897static cricket::MediaDescriptionOptions
4898GetMediaDescriptionOptionsForTransceiver(
4899 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4900 transceiver,
4901 const std::string& mid) {
4902 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004903 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004904 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004905 media_description_options.codec_preferences =
4906 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004907 // This behavior is specified in JSEP. The gist is that:
4908 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4909 // sendrecv.
4910 // 2. If the MSID is included, then it must be included in any subsequent
4911 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004912 if (transceiver->stopped() ||
4913 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4914 !transceiver->internal()->has_ever_been_used_to_send())) {
4915 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004916 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004917
4918 cricket::SenderOptions sender_options;
4919 sender_options.track_id = transceiver->sender()->id();
4920 sender_options.stream_ids = transceiver->sender()->stream_ids();
4921
4922 // The following sets up RIDs and Simulcast.
4923 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004924 RtpParameters send_parameters =
4925 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004926 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4927 send_parameters.encodings.end(),
4928 [](const RtpEncodingParameters& encoding) {
4929 return !encoding.rid.empty();
4930 });
4931
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004932 std::vector<RidDescription> send_rids;
4933 SimulcastLayerList send_layers;
4934 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4935 if (encoding.rid.empty()) {
4936 continue;
4937 }
4938 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4939 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4940 }
4941
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004942 if (has_rids) {
4943 sender_options.rids = send_rids;
4944 }
4945
4946 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004947 // When RIDs are configured, we must set num_sim_layers to 0 to.
4948 // Otherwise, num_sim_layers must be 1 because either there is no
4949 // simulcast, or simulcast is acheived by munging the SDP.
4950 sender_options.num_sim_layers = has_rids ? 0 : 1;
4951 media_description_options.sender_options.push_back(sender_options);
4952
Steve Antondcc3c022017-12-22 16:02:54 -08004953 return media_description_options;
4954}
4955
Steve Anton5c72e712018-12-10 14:25:30 -08004956// Returns the ContentInfo at mline index |i|, or null if none exists.
4957static const ContentInfo* GetContentByIndex(
4958 const SessionDescriptionInterface* sdesc,
4959 size_t i) {
4960 if (!sdesc) {
4961 return nullptr;
4962 }
4963 const ContentInfos& contents = sdesc->description()->contents();
4964 return (i < contents.size() ? &contents[i] : nullptr);
4965}
4966
Steve Antondcc3c022017-12-22 16:02:54 -08004967void PeerConnection::GetOptionsForUnifiedPlanOffer(
4968 const RTCOfferAnswerOptions& offer_answer_options,
4969 cricket::MediaSessionOptions* session_options) {
4970 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4971 // Offers) and 5.2.2 (Subsequent Offers).
4972 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004973 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004974 const ContentInfos& local_contents =
4975 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004976 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004977 const ContentInfos& remote_contents =
4978 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004979 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004980 // The mline indices that can be recycled. New transceivers should reuse these
4981 // slots first.
4982 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004983 // First, go through each media section that exists in either the local or
4984 // remote description and generate a media section in this offer for the
4985 // associated transceiver. If a media section can be recycled, generate a
4986 // default, rejected media section here that can be later overwritten.
4987 for (size_t i = 0;
4988 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4989 // Either |local_content| or |remote_content| is non-null.
4990 const ContentInfo* local_content =
4991 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004992 const ContentInfo* current_local_content =
4993 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004994 const ContentInfo* remote_content =
4995 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004996 const ContentInfo* current_remote_content =
4997 GetContentByIndex(current_remote_description(), i);
4998 bool had_been_rejected =
4999 (current_local_content && current_local_content->rejected) ||
5000 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08005001 const std::string& mid =
5002 (local_content ? local_content->name : remote_content->name);
5003 cricket::MediaType media_type =
5004 (local_content ? local_content->media_description()->type()
5005 : remote_content->media_description()->type());
5006 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5007 media_type == cricket::MEDIA_TYPE_VIDEO) {
5008 auto transceiver = GetAssociatedTransceiver(mid);
5009 RTC_CHECK(transceiver);
5010 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08005011 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005012 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08005013 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08005014 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5015 RtpTransceiverDirection::kInactive,
5016 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08005017 recycleable_mline_indices.push(i);
5018 } else {
5019 session_options->media_description_options.push_back(
5020 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5021 // CreateOffer shouldn't really cause any state changes in
5022 // PeerConnection, but we need a way to match new transceivers to new
5023 // media sections in SetLocalDescription and JSEP specifies this is done
5024 // by recording the index of the media section generated for the
5025 // transceiver in the offer.
5026 transceiver->internal()->set_mline_index(i);
5027 }
5028 } else {
5029 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08005030 RTC_CHECK(GetDataMid());
5031 if (had_been_rejected || mid != *GetDataMid()) {
5032 session_options->media_description_options.push_back(
5033 GetMediaDescriptionOptionsForRejectedData(mid));
5034 } else {
5035 session_options->media_description_options.push_back(
5036 GetMediaDescriptionOptionsForActiveData(mid));
5037 }
Steve Antondcc3c022017-12-22 16:02:54 -08005038 }
5039 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08005040
Steve Antondcc3c022017-12-22 16:02:54 -08005041 // Next, look for transceivers that are newly added (that is, are not stopped
5042 // and not associated). Reuse media sections marked as recyclable first,
5043 // otherwise append to the end of the offer. New media sections should be
5044 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005045 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08005046 if (transceiver->mid() || transceiver->stopped()) {
5047 continue;
5048 }
5049 size_t mline_index;
5050 if (!recycleable_mline_indices.empty()) {
5051 mline_index = recycleable_mline_indices.front();
5052 recycleable_mline_indices.pop();
5053 session_options->media_description_options[mline_index] =
5054 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005055 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08005056 } else {
5057 mline_index = session_options->media_description_options.size();
5058 session_options->media_description_options.push_back(
5059 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005060 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08005061 }
5062 // See comment above for why CreateOffer changes the transceiver's state.
5063 transceiver->internal()->set_mline_index(mline_index);
5064 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005065 // Lastly, add a m-section if we have local data channels and an m section
5066 // does not already exist.
5067 if (!GetDataMid() && HasDataChannels()) {
5068 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08005069 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08005070 }
Steve Antondcc3c022017-12-22 16:02:54 -08005071}
5072
5073void PeerConnection::GetOptionsForAnswer(
5074 const RTCOfferAnswerOptions& offer_answer_options,
5075 cricket::MediaSessionOptions* session_options) {
5076 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5077
5078 if (IsUnifiedPlan()) {
5079 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5080 } else {
5081 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5082 }
5083
Steve Antonfa2260d2017-12-28 16:38:23 -08005084 // Intentionally unset the data channel type for RTP data channel. Otherwise
5085 // the RTP data channels would be successfully negotiated by default and the
5086 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5087 // We want to leave RTP data channels broken, so people won't try to use them.
5088 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
5089 session_options->data_channel_type = data_channel_type();
5090 }
5091
Steve Antondcc3c022017-12-22 16:02:54 -08005092 // Apply ICE renomination flag.
5093 for (auto& options : session_options->media_description_options) {
5094 options.transport_options.enable_ice_renomination =
5095 configuration_.enable_ice_renomination;
5096 }
zhihuang8f65cdf2016-05-06 18:40:30 -07005097
5098 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005099 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02005100 session_options->pooled_ice_credentials =
5101 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5102 RTC_FROM_HERE,
5103 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5104 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005105
5106 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005107 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005108 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005109 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005110 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005111 if (!params) {
5112 continue;
5113 }
5114 options.transport_options.opaque_parameters = params;
5115 if ((use_datagram_transport_ &&
5116 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5117 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5118 (use_datagram_transport_for_data_channels_ &&
5119 options.type == cricket::MEDIA_TYPE_DATA)) {
5120 options.alt_protocol = params->protocol;
5121 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005122 }
5123 }
deadbeefab9b2d12015-10-14 11:33:11 -07005124}
5125
Steve Antondcc3c022017-12-22 16:02:54 -08005126void PeerConnection::GetOptionsForPlanBAnswer(
5127 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07005128 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005129 // Figure out transceiver directional preferences.
5130 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5131 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5132
5133 // By default, generate sendrecv/recvonly m= sections. The direction is also
5134 // restricted by the direction in the offer.
5135 bool recv_audio = true;
5136 bool recv_video = true;
5137
5138 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08005139 if (offer_answer_options.offer_to_receive_audio !=
5140 RTCOfferAnswerOptions::kUndefined) {
5141 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08005142 }
Steve Antondcc3c022017-12-22 16:02:54 -08005143 if (offer_answer_options.offer_to_receive_video !=
5144 RTCOfferAnswerOptions::kUndefined) {
5145 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005146 }
5147
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005148 absl::optional<size_t> audio_index;
5149 absl::optional<size_t> video_index;
5150 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08005151
5152 // Generate m= sections that match those in the offer.
5153 // Note that mediasession.cc will handle intersection our preferred
5154 // direction with the offered direction.
5155 GenerateMediaDescriptionOptions(
5156 remote_description(),
5157 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5158 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5159 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07005160
5161 cricket::MediaDescriptionOptions* audio_media_description_options =
5162 !audio_index ? nullptr
5163 : &session_options->media_description_options[*audio_index];
5164 cricket::MediaDescriptionOptions* video_media_description_options =
5165 !video_index ? nullptr
5166 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005167
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005168 AddPlanBRtpSenderOptions(GetSendersInternal(),
5169 audio_media_description_options,
5170 video_media_description_options,
5171 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005172}
zhihuangaf388472016-11-02 16:49:48 -07005173
Steve Antondcc3c022017-12-22 16:02:54 -08005174void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5175 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5176 cricket::MediaSessionOptions* session_options) {
5177 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5178 // Answers) and 5.3.2 (Subsequent Answers).
5179 RTC_DCHECK(remote_description());
5180 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5181 for (const ContentInfo& content :
5182 remote_description()->description()->contents()) {
5183 cricket::MediaType media_type = content.media_description()->type();
5184 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5185 media_type == cricket::MEDIA_TYPE_VIDEO) {
5186 auto transceiver = GetAssociatedTransceiver(content.name);
5187 RTC_CHECK(transceiver);
5188 session_options->media_description_options.push_back(
5189 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5190 } else {
5191 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08005192 // Reject all data sections if data channels are disabled.
5193 // Reject a data section if it has already been rejected.
5194 // Reject all data sections except for the first one.
5195 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
5196 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005197 session_options->media_description_options.push_back(
5198 GetMediaDescriptionOptionsForRejectedData(content.name));
5199 } else {
5200 session_options->media_description_options.push_back(
5201 GetMediaDescriptionOptionsForActiveData(content.name));
5202 }
Steve Antondcc3c022017-12-22 16:02:54 -08005203 }
5204 }
htaa2a49d92016-03-04 02:51:39 -08005205}
5206
zhihuang1c378ed2017-08-17 14:10:50 -07005207void PeerConnection::GenerateMediaDescriptionOptions(
5208 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08005209 RtpTransceiverDirection audio_direction,
5210 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005211 absl::optional<size_t>* audio_index,
5212 absl::optional<size_t>* video_index,
5213 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08005214 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005215 for (const cricket::ContentInfo& content :
5216 session_desc->description()->contents()) {
5217 if (IsAudioContent(&content)) {
5218 // If we already have an audio m= section, reject this extra one.
5219 if (*audio_index) {
5220 session_options->media_description_options.push_back(
5221 cricket::MediaDescriptionOptions(
5222 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005223 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005224 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005225 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005226 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005227 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5228 content.name, audio_direction,
5229 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005230 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005231 }
5232 } else if (IsVideoContent(&content)) {
5233 // If we already have an video m= section, reject this extra one.
5234 if (*video_index) {
5235 session_options->media_description_options.push_back(
5236 cricket::MediaDescriptionOptions(
5237 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005238 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005239 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005240 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005241 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005242 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5243 content.name, video_direction,
5244 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005245 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005246 }
5247 } else {
5248 RTC_DCHECK(IsDataContent(&content));
5249 // If we already have an data m= section, reject this extra one.
5250 if (*data_index) {
5251 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005252 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005253 } else {
5254 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005255 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005256 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005257 }
5258 }
htaa2a49d92016-03-04 02:51:39 -08005259 }
deadbeefab9b2d12015-10-14 11:33:11 -07005260}
5261
Steve Antonfa2260d2017-12-28 16:38:23 -08005262cricket::MediaDescriptionOptions
5263PeerConnection::GetMediaDescriptionOptionsForActiveData(
5264 const std::string& mid) const {
5265 // Direction for data sections is meaningless, but legacy endpoints might
5266 // expect sendrecv.
5267 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5268 RtpTransceiverDirection::kSendRecv,
5269 /*stopped=*/false);
5270 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5271 return options;
5272}
5273
5274cricket::MediaDescriptionOptions
5275PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5276 const std::string& mid) const {
5277 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5278 RtpTransceiverDirection::kInactive,
5279 /*stopped=*/true);
5280 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5281 return options;
5282}
5283
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005284absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08005285 switch (data_channel_type_) {
5286 case cricket::DCT_RTP:
5287 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005288 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005289 }
5290 return rtp_data_channel_->content_name();
5291 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005292 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005293 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5294 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5295 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005296 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005297 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005298 }
5299}
5300
Steve Anton4171afb2017-11-20 10:20:22 -08005301void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5302 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5303 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005304 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005305}
5306
Steve Anton4171afb2017-11-20 10:20:22 -08005307void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005308 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005309 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005310 cricket::MediaType media_type,
5311 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005312 RTC_DCHECK(!IsUnifiedPlan());
5313
Steve Anton4171afb2017-11-20 10:20:22 -08005314 std::vector<RtpSenderInfo>* current_senders =
5315 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005316
Steve Anton4171afb2017-11-20 10:20:22 -08005317 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005318 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005319 for (auto sender_it = current_senders->begin();
5320 sender_it != current_senders->end();
5321 /* incremented manually */) {
5322 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005323 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005324 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005325 std::string params_stream_id;
5326 if (params) {
5327 params_stream_id =
5328 (!params->first_stream_id().empty() ? params->first_stream_id()
5329 : kDefaultStreamId);
5330 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005331 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005332 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005333 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005334 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005335 sender_exists) {
5336 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005337 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005338 OnRemoteSenderRemoved(info, media_type);
5339 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005340 }
5341 }
5342
Steve Anton4171afb2017-11-20 10:20:22 -08005343 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005344 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005345 if (!params.has_ssrcs()) {
5346 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5347 // sender, this means it is coming from a Unified Plan endpoint,so we just
5348 // create a default.
5349 default_sender_needed = true;
5350 break;
5351 }
5352
Seth Hampson845e8782018-03-02 11:34:10 -08005353 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005354 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005355 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5356 // not supported in Plan B, we just take the first here and create the
5357 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005358 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005359 (!params.first_stream_id().empty() ? params.first_stream_id()
5360 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005361 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005362 uint32_t ssrc = params.first_ssrc();
5363
5364 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005365 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005366 if (!stream) {
5367 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005368 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005369 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005370 remote_streams_->AddStream(stream);
5371 new_streams->AddStream(stream);
5372 }
5373
Steve Anton4171afb2017-11-20 10:20:22 -08005374 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005375 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005376 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005377 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005378 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005379 }
5380 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005381
Steve Anton4171afb2017-11-20 10:20:22 -08005382 // Add default sender if necessary.
5383 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005384 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005385 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005386 if (!default_stream) {
5387 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005388 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005389 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005390 remote_streams_->AddStream(default_stream);
5391 new_streams->AddStream(default_stream);
5392 }
Steve Anton4171afb2017-11-20 10:20:22 -08005393 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5394 ? kDefaultAudioSenderId
5395 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005396 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005397 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005398 if (!default_sender_info) {
5399 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005400 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005401 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005402 }
5403 }
deadbeefab9b2d12015-10-14 11:33:11 -07005404}
5405
Steve Anton4171afb2017-11-20 10:20:22 -08005406void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5407 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005408 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5409 << " receiver for track_id=" << sender_info.sender_id
5410 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005411
Steve Anton3d954a62018-04-02 11:27:23 -07005412 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005413 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005414 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005415 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005416 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005417 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005418 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005419 }
5420}
5421
Steve Anton4171afb2017-11-20 10:20:22 -08005422void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5423 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005424 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5425 << " receiver for track_id=" << sender_info.sender_id
5426 << " and stream_id=" << sender_info.stream_id;
5427
Seth Hampson845e8782018-03-02 11:34:10 -08005428 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005429
Henrik Boström933d8b02017-10-10 10:05:16 -07005430 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005431 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005432 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5433 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005434 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005435 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005436 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005437 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005438 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005439 }
5440 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005441 // Stopping or destroying a VideoRtpReceiver will end the
5442 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005443 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005444 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005445 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005446 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005447 // There's no guarantee the track is still available, e.g. the track may
5448 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005449 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005450 }
5451 } else {
nisseede5da42017-01-12 05:15:36 -08005452 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005453 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005454 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005455 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005456 }
deadbeefab9b2d12015-10-14 11:33:11 -07005457}
5458
5459void PeerConnection::UpdateEndedRemoteMediaStreams() {
5460 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5461 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5462 MediaStreamInterface* stream = remote_streams_->at(i);
5463 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5464 streams_to_remove.push_back(stream);
5465 }
5466 }
5467
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005468 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005469 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005470 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005471 }
5472}
5473
Steve Anton4171afb2017-11-20 10:20:22 -08005474void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005475 const std::vector<cricket::StreamParams>& streams,
5476 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005477 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005478
Seth Hampson845e8782018-03-02 11:34:10 -08005479 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005480 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005481 for (auto sender_it = current_senders->begin();
5482 sender_it != current_senders->end();
5483 /* incremented manually */) {
5484 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005485 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005486 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5487 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005488 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005489 OnLocalSenderRemoved(info, media_type);
5490 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005491 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005492 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005493 }
5494 }
5495
Steve Anton4171afb2017-11-20 10:20:22 -08005496 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005497 for (const cricket::StreamParams& params : streams) {
5498 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005499 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005500 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005501 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005502 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005503 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005504 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005505 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005506 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005507 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005508 }
5509 }
5510}
5511
Steve Anton4171afb2017-11-20 10:20:22 -08005512void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5513 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005514 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005515 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005516 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005517 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5518 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005519 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005520 return;
5521 }
5522
deadbeeffac06552015-11-25 11:26:01 -08005523 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005524 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005525 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005526 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005527 }
deadbeeffac06552015-11-25 11:26:01 -08005528
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005529 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005530 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005531}
5532
Steve Anton4171afb2017-11-20 10:20:22 -08005533void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5534 cricket::MediaType media_type) {
5535 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005536 if (!sender) {
5537 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005538 // SessionDescriptions has been renegotiated.
5539 return;
5540 }
deadbeeffac06552015-11-25 11:26:01 -08005541
5542 // A sender has been removed from the SessionDescription but it's still
5543 // associated with the PeerConnection. This only occurs if the SDP doesn't
5544 // match with the calls to CreateSender, AddStream and RemoveStream.
5545 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005546 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005547 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005548 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005549 }
deadbeeffac06552015-11-25 11:26:01 -08005550
Steve Anton4171afb2017-11-20 10:20:22 -08005551 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005552}
5553
5554void PeerConnection::UpdateLocalRtpDataChannels(
5555 const cricket::StreamParamsVec& streams) {
5556 std::vector<std::string> existing_channels;
5557
5558 // Find new and active data channels.
5559 for (const cricket::StreamParams& params : streams) {
5560 // |it->sync_label| is actually the data channel label. The reason is that
5561 // we use the same naming of data channels as we do for
5562 // MediaStreams and Tracks.
5563 // For MediaStreams, the sync_label is the MediaStream label and the
5564 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005565 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005566 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005567 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005568 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005569 continue;
5570 }
5571 // Set the SSRC the data channel should use for sending.
5572 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5573 existing_channels.push_back(data_channel_it->first);
5574 }
5575
5576 UpdateClosingRtpDataChannels(existing_channels, true);
5577}
5578
5579void PeerConnection::UpdateRemoteRtpDataChannels(
5580 const cricket::StreamParamsVec& streams) {
5581 std::vector<std::string> existing_channels;
5582
5583 // Find new and active data channels.
5584 for (const cricket::StreamParams& params : streams) {
5585 // The data channel label is either the mslabel or the SSRC if the mslabel
5586 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005587 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005588 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005589 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005590 auto data_channel_it = rtp_data_channels_.find(label);
5591 if (data_channel_it == rtp_data_channels_.end()) {
5592 // This is a new data channel.
5593 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5594 } else {
5595 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5596 }
5597 existing_channels.push_back(label);
5598 }
5599
5600 UpdateClosingRtpDataChannels(existing_channels, false);
5601}
5602
5603void PeerConnection::UpdateClosingRtpDataChannels(
5604 const std::vector<std::string>& active_channels,
5605 bool is_local_update) {
5606 auto it = rtp_data_channels_.begin();
5607 while (it != rtp_data_channels_.end()) {
5608 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005609 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005610 ++it;
5611 continue;
5612 }
5613
5614 if (is_local_update) {
5615 data_channel->SetSendSsrc(0);
5616 } else {
5617 data_channel->RemotePeerRequestClose();
5618 }
5619
5620 if (data_channel->state() == DataChannel::kClosed) {
5621 rtp_data_channels_.erase(it);
5622 it = rtp_data_channels_.begin();
5623 } else {
5624 ++it;
5625 }
5626 }
5627}
5628
5629void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5630 uint32_t remote_ssrc) {
5631 rtc::scoped_refptr<DataChannel> channel(
5632 InternalCreateDataChannel(label, nullptr));
5633 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005634 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005635 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005636 return;
5637 }
5638 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005639 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5640 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005641 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005642}
5643
5644rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5645 const std::string& label,
5646 const InternalDataChannelInit* config) {
5647 if (IsClosed()) {
5648 return nullptr;
5649 }
Steve Anton75737c02017-11-06 10:37:17 -08005650 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005651 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005652 << "InternalCreateDataChannel: Data is not supported in this call.";
5653 return nullptr;
5654 }
5655 InternalDataChannelInit new_config =
5656 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005657 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005658 if (new_config.id < 0) {
5659 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005660 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005661 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005662 RTC_LOG(LS_ERROR)
5663 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005664 return nullptr;
5665 }
5666 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005667 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005668 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005669 return nullptr;
5670 }
5671 }
5672
Steve Anton75737c02017-11-06 10:37:17 -08005673 rtc::scoped_refptr<DataChannel> channel(
5674 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005675 if (!channel) {
5676 sid_allocator_.ReleaseSid(new_config.id);
5677 return nullptr;
5678 }
5679
5680 if (channel->data_channel_type() == cricket::DCT_RTP) {
5681 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005682 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5683 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005684 return nullptr;
5685 }
5686 rtp_data_channels_[channel->label()] = channel;
5687 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005688 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005689 sctp_data_channels_.push_back(channel);
5690 channel->SignalClosed.connect(this,
5691 &PeerConnection::OnSctpDataChannelClosed);
5692 }
5693
Steve Anton2d8609c2018-01-23 16:38:46 -08005694 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005695 return channel;
5696}
5697
5698bool PeerConnection::HasDataChannels() const {
5699 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5700}
5701
5702void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005703 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005704 for (const auto& channel : sctp_data_channels_) {
5705 if (channel->id() < 0) {
5706 int sid;
5707 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005708 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5709 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005710 continue;
5711 }
5712 channel->SetSctpSid(sid);
5713 }
5714 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005715 // Since closing modifies the list of channels, we have to do the actual
5716 // closing outside the loop.
5717 for (const auto& channel : channels_to_close) {
5718 channel->CloseAbruptly();
5719 }
deadbeefab9b2d12015-10-14 11:33:11 -07005720}
5721
5722void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005723 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005724 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5725 ++it) {
5726 if (it->get() == channel) {
5727 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005728 // After the closing procedure is done, it's safe to use this ID for
5729 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005730 sid_allocator_.ReleaseSid(channel->id());
5731 }
deadbeefbd292462015-12-14 18:15:29 -08005732 // Since this method is triggered by a signal from the DataChannel,
5733 // we can't free it directly here; we need to free it asynchronously.
5734 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005735 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005736 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5737 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005738 return;
5739 }
5740 }
5741}
5742
deadbeefab9b2d12015-10-14 11:33:11 -07005743void PeerConnection::OnDataChannelDestroyed() {
5744 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5745 // DataChannel may callback to us and try to modify the list.
5746 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5747 temp_rtp_dcs.swap(rtp_data_channels_);
5748 for (const auto& kv : temp_rtp_dcs) {
5749 kv.second->OnTransportChannelDestroyed();
5750 }
5751
5752 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5753 temp_sctp_dcs.swap(sctp_data_channels_);
5754 for (const auto& channel : temp_sctp_dcs) {
5755 channel->OnTransportChannelDestroyed();
5756 }
5757}
5758
5759void PeerConnection::OnDataChannelOpenMessage(
5760 const std::string& label,
5761 const InternalDataChannelInit& config) {
5762 rtc::scoped_refptr<DataChannel> channel(
5763 InternalCreateDataChannel(label, &config));
5764 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005765 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005766 return;
5767 }
5768
deadbeefa601f5c2016-06-06 14:27:39 -07005769 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5770 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005771 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005772 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005773}
5774
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005775bool PeerConnection::HandleOpenMessage_s(
5776 const cricket::ReceiveDataParams& params,
5777 const rtc::CopyOnWriteBuffer& buffer) {
5778 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5779 // Received OPEN message; parse and signal that a new data channel should
5780 // be created.
5781 std::string label;
5782 InternalDataChannelInit config;
5783 config.id = params.ssrc;
5784 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5785 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5786 << params.ssrc;
5787 return true;
5788 }
5789 config.open_handshake_role = InternalDataChannelInit::kAcker;
5790 OnDataChannelOpenMessage(label, config);
5791 return true;
5792 }
5793 return false;
5794}
5795
Steve Anton4171afb2017-11-20 10:20:22 -08005796rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5797PeerConnection::GetAudioTransceiver() const {
5798 // This method only works with Plan B SDP, where there is a single
5799 // audio/video transceiver.
5800 RTC_DCHECK(!IsUnifiedPlan());
5801 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005802 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005803 return transceiver;
5804 }
5805 }
5806 RTC_NOTREACHED();
5807 return nullptr;
5808}
5809
5810rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5811PeerConnection::GetVideoTransceiver() const {
5812 // This method only works with Plan B SDP, where there is a single
5813 // audio/video transceiver.
5814 RTC_DCHECK(!IsUnifiedPlan());
5815 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005816 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005817 return transceiver;
5818 }
5819 }
5820 RTC_NOTREACHED();
5821 return nullptr;
5822}
5823
5824// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5825// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005826bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005827 switch (type) {
5828 case cricket::MEDIA_TYPE_AUDIO:
5829 return !GetAudioTransceiver()->internal()->senders().empty();
5830 case cricket::MEDIA_TYPE_VIDEO:
5831 return !GetVideoTransceiver()->internal()->senders().empty();
5832 case cricket::MEDIA_TYPE_DATA:
5833 return false;
5834 }
5835 RTC_NOTREACHED();
5836 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005837}
5838
Steve Anton4171afb2017-11-20 10:20:22 -08005839rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5840PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005841 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005842 for (auto sender : transceiver->internal()->senders()) {
5843 if (sender->track() == track) {
5844 return sender;
5845 }
5846 }
5847 }
5848 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005849}
5850
Steve Anton4171afb2017-11-20 10:20:22 -08005851rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5852PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005853 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005854 for (auto sender : transceiver->internal()->senders()) {
5855 if (sender->id() == sender_id) {
5856 return sender;
5857 }
5858 }
5859 }
5860 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005861}
5862
Steve Anton4171afb2017-11-20 10:20:22 -08005863rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5864PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005865 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005866 for (auto receiver : transceiver->internal()->receivers()) {
5867 if (receiver->id() == receiver_id) {
5868 return receiver;
5869 }
5870 }
5871 }
5872 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005873}
5874
Steve Anton4171afb2017-11-20 10:20:22 -08005875std::vector<PeerConnection::RtpSenderInfo>*
5876PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5877 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5878 media_type == cricket::MEDIA_TYPE_VIDEO);
5879 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5880 ? &remote_audio_sender_infos_
5881 : &remote_video_sender_infos_;
5882}
5883
5884std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005885 cricket::MediaType media_type) {
5886 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5887 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005888 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5889 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005890}
5891
Steve Anton4171afb2017-11-20 10:20:22 -08005892const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5893 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005894 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005895 const std::string sender_id) const {
5896 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005897 if (sender_info.stream_id == stream_id &&
5898 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005899 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005900 }
5901 }
5902 return nullptr;
5903}
5904
5905DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5906 for (const auto& channel : sctp_data_channels_) {
5907 if (channel->id() == sid) {
5908 return channel;
5909 }
5910 }
5911 return nullptr;
5912}
5913
Karl Wibergfb3be392019-03-22 14:13:22 +01005914PeerConnection::InitializePortAllocatorResult
5915PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005916 const cricket::ServerAddresses& stun_servers,
5917 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005918 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005919 RTC_DCHECK_RUN_ON(network_thread());
5920
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005921 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005922 // To handle both internal and externally created port allocator, we will
5923 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005924 int port_allocator_flags = port_allocator_->flags();
5925 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5926 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5927 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005928 // If the disable-IPv6 flag was specified, we'll not override it
5929 // by experiment.
5930 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005931 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005932 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5933 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005934 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005935 }
5936
zhihuangb09b3f92017-03-07 14:40:51 -08005937 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005938 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005939 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005940 }
5941
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005942 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005943 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005944 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005945 }
5946
honghaiz60347052016-05-31 18:29:12 -07005947 if (configuration.candidate_network_policy ==
5948 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005949 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005950 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005951 }
5952
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005953 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005954 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005955 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5956 }
5957
Karl Wibergfb3be392019-03-22 14:13:22 +01005958 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005959 // No step delay is used while allocating ports.
5960 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005961 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005962 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005963 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005964
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005965 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005966 for (auto& turn_server : turn_servers_copy) {
5967 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005968 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005969 // Call this last since it may create pooled allocator sessions using the
5970 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005971 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005972 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005973 configuration.ice_candidate_pool_size,
5974 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005975 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005976
5977 InitializePortAllocatorResult res;
5978 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5979 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005980}
5981
deadbeef91dd5672016-05-18 16:55:30 -07005982bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005983 const cricket::ServerAddresses& stun_servers,
5984 const std::vector<cricket::RelayServerConfig>& turn_servers,
5985 IceTransportsType type,
5986 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005987 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005988 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005989 absl::optional<int> stun_candidate_keepalive_interval,
5990 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005991 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005992 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005993 // According to JSEP, after setLocalDescription, changing the candidate pool
5994 // size is not allowed, and changing the set of ICE servers will not result
5995 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005996 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005997 port_allocator_->FreezeCandidatePool();
5998 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005999 // Add the custom tls turn servers if they exist.
6000 auto turn_servers_copy = turn_servers;
6001 for (auto& turn_server : turn_servers_copy) {
6002 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
6003 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006004 // Call this last since it may create pooled allocator sessions using the
6005 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08006006 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07006007 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07006008 turn_port_prune_policy, turn_customizer,
6009 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07006010}
6011
Steve Antonba818672017-11-06 10:21:57 -08006012cricket::ChannelManager* PeerConnection::channel_manager() const {
6013 return factory_->channel_manager();
6014}
6015
Elad Alon99c3fe52017-10-13 16:29:40 +02006016bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01006017 std::unique_ptr<RtcEventLogOutput> output,
6018 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01006019 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006020 if (!event_log_) {
6021 return false;
6022 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01006023 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07006024}
6025
6026void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01006027 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08006028 if (event_log_) {
6029 event_log_->StopLogging();
6030 }
ivoc14d5dbe2016-07-04 07:06:55 -07006031}
nisseeaabdf62017-05-05 02:23:02 -07006032
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006033cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08006034 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006035 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006036 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08006037 if (channel && channel->content_name() == content_name) {
6038 return channel;
6039 }
Steve Anton75737c02017-11-06 10:37:17 -08006040 }
6041 if (rtp_data_channel() &&
6042 rtp_data_channel()->content_name() == content_name) {
6043 return rtp_data_channel();
6044 }
6045 return nullptr;
6046}
6047
6048bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006049 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006050 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006051 RTC_LOG(LS_INFO)
6052 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006053 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006054 return false;
6055 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006056 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006057 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006058 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08006059 return false;
6060 }
6061
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006062 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006063 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006064 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006065 if (!dtls_role && is_caller_.has_value()) {
6066 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
6067 }
Zhi Huange830e682018-03-30 10:48:35 -07006068 *role = *dtls_role;
6069 return true;
6070 }
6071 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006072}
6073
6074bool PeerConnection::GetSslRole(const std::string& content_name,
6075 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006076 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006077 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006078 RTC_LOG(LS_INFO)
6079 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006080 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08006081 return false;
6082 }
6083
Zhi Huange830e682018-03-30 10:48:35 -07006084 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6085 if (dtls_role) {
6086 *role = *dtls_role;
6087 return true;
6088 }
6089 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006090}
6091
Steve Antonf8470812017-12-04 10:46:21 -08006092void PeerConnection::SetSessionError(SessionError error,
6093 const std::string& error_desc) {
6094 RTC_DCHECK_RUN_ON(signaling_thread());
6095 if (error != session_error_) {
6096 session_error_ = error;
6097 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08006098 }
6099}
6100
Zhi Huange830e682018-03-30 10:48:35 -07006101RTCError PeerConnection::UpdateSessionState(
6102 SdpType type,
6103 cricket::ContentSource source,
6104 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08006105 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006106
6107 // If there's already a pending error then no state transition should happen.
6108 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08006109 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006110
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006111 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08006112 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08006113 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006114 }
6115
6116 // Update the signaling state according to the specified state machine (see
6117 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08006118 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006119 ChangeSignalingState(source == cricket::CS_LOCAL
6120 ? PeerConnectionInterface::kHaveLocalOffer
6121 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08006122 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006123 ChangeSignalingState(source == cricket::CS_LOCAL
6124 ? PeerConnectionInterface::kHaveLocalPrAnswer
6125 : PeerConnectionInterface::kHaveRemotePrAnswer);
6126 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006127 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006128 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03006129 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006130 }
6131
6132 // Update internal objects according to the session description's media
6133 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07006134 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006135 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08006136 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006137 }
6138
Steve Anton8a006912017-12-04 15:25:56 -08006139 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006140}
6141
Steve Anton8a006912017-12-04 15:25:56 -08006142RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08006143 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08006144 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08006145 const SessionDescriptionInterface* sdesc =
6146 (source == cricket::CS_LOCAL ? local_description()
6147 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08006148 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08006149
6150 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01006151 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08006152 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08006153 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006154 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006155 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08006156 continue;
6157 }
6158 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006159 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006160 if (!content_desc) {
6161 continue;
6162 }
6163 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02006164 bool success = (source == cricket::CS_LOCAL)
6165 ? channel->SetLocalContent(content_desc, type, &error)
6166 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006167 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006169 }
6170 }
6171
6172 // If using the RtpDataChannel, push down the new SDP section for it too.
6173 if (rtp_data_channel_) {
6174 const ContentInfo* data_content =
6175 cricket::GetFirstDataContent(sdesc->description());
6176 if (data_content && !data_content->rejected) {
6177 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006178 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006179 if (data_desc) {
6180 std::string error;
6181 bool success =
6182 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08006183 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02006184 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006185 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006186 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006187 }
Steve Anton75737c02017-11-06 10:37:17 -08006188 }
6189 }
6190 }
Steve Antoned10bd92017-12-05 10:52:59 -08006191
Steve Anton75737c02017-11-06 10:37:17 -08006192 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6193 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006194 if (sctp_mid_ && local_description() && remote_description()) {
6195 rtc::scoped_refptr<SctpTransport> sctp_transport =
6196 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006197 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6198 local_description()->description());
6199 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6200 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006201 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02006202 int max_message_size;
6203 // A remote max message size of zero means "any size supported".
6204 // We configure the connection with our own max message size.
6205 if (remote_sctp_description->max_message_size() == 0) {
6206 max_message_size = local_sctp_description->max_message_size();
6207 } else {
6208 max_message_size =
6209 std::min(local_sctp_description->max_message_size(),
6210 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006211 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006212 sctp_transport->Start(local_sctp_description->port(),
6213 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08006214 }
Steve Anton75737c02017-11-06 10:37:17 -08006215 }
Steve Antoned10bd92017-12-05 10:52:59 -08006216
Steve Anton8a006912017-12-04 15:25:56 -08006217 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006218}
6219
Steve Anton8a006912017-12-04 15:25:56 -08006220RTCError PeerConnection::PushdownTransportDescription(
6221 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006222 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006223 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006224
Zhi Huange830e682018-03-30 10:48:35 -07006225 if (source == cricket::CS_LOCAL) {
6226 const SessionDescriptionInterface* sdesc = local_description();
6227 RTC_DCHECK(sdesc);
6228 return transport_controller_->SetLocalDescription(type,
6229 sdesc->description());
6230 } else {
6231 const SessionDescriptionInterface* sdesc = remote_description();
6232 RTC_DCHECK(sdesc);
6233 return transport_controller_->SetRemoteDescription(type,
6234 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006235 }
Steve Anton75737c02017-11-06 10:37:17 -08006236}
6237
6238bool PeerConnection::GetTransportDescription(
6239 const SessionDescription* description,
6240 const std::string& content_name,
6241 cricket::TransportDescription* tdesc) {
6242 if (!description || !tdesc) {
6243 return false;
6244 }
6245 const TransportInfo* transport_info =
6246 description->GetTransportInfoByName(content_name);
6247 if (!transport_info) {
6248 return false;
6249 }
6250 *tdesc = transport_info->description;
6251 return true;
6252}
6253
Steve Anton75737c02017-11-06 10:37:17 -08006254cricket::IceConfig PeerConnection::ParseIceConfig(
6255 const PeerConnectionInterface::RTCConfiguration& config) const {
6256 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006257 switch (config.continual_gathering_policy) {
6258 case PeerConnectionInterface::GATHER_ONCE:
6259 gathering_policy = cricket::GATHER_ONCE;
6260 break;
6261 case PeerConnectionInterface::GATHER_CONTINUALLY:
6262 gathering_policy = cricket::GATHER_CONTINUALLY;
6263 break;
6264 default:
6265 RTC_NOTREACHED();
6266 gathering_policy = cricket::GATHER_ONCE;
6267 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006268
Steve Anton75737c02017-11-06 10:37:17 -08006269 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006270 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6271 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006272 ice_config.prioritize_most_likely_candidate_pairs =
6273 config.prioritize_most_likely_ice_candidate_pairs;
6274 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006275 RTCConfigurationToIceConfigOptionalInt(
6276 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006277 ice_config.continual_gathering_policy = gathering_policy;
6278 ice_config.presume_writable_when_fully_relayed =
6279 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006280 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6281 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006282 ice_config.ice_check_interval_strong_connectivity =
6283 config.ice_check_interval_strong_connectivity;
6284 ice_config.ice_check_interval_weak_connectivity =
6285 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006286 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006287 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6288 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006289 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006290 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08006291 ice_config.regather_all_networks_interval_range =
6292 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006293 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006294 return ice_config;
6295}
6296
Steve Anton75737c02017-11-06 10:37:17 -08006297bool PeerConnection::SendData(const cricket::SendDataParams& params,
6298 const rtc::CopyOnWriteBuffer& payload,
6299 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006300 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006301 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006302 SendDataParams send_params;
6303 send_params.type = ToWebrtcDataMessageType(params.type);
6304 send_params.ordered = params.ordered;
6305 if (params.max_rtx_count >= 0) {
6306 send_params.max_rtx_count = params.max_rtx_count;
6307 } else if (params.max_rtx_ms >= 0) {
6308 send_params.max_rtx_ms = params.max_rtx_ms;
6309 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006310
6311 RTCError error = network_thread()->Invoke<RTCError>(
6312 RTC_FROM_HERE, [this, params, send_params, payload] {
6313 return data_channel_transport_->SendData(params.sid, send_params,
6314 payload);
6315 });
6316
6317 if (error.ok()) {
6318 *result = cricket::SendDataResult::SDR_SUCCESS;
6319 return true;
6320 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6321 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6322 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6323 *result = cricket::SendDataResult::SDR_BLOCK;
6324 return false;
6325 }
6326 *result = cricket::SendDataResult::SDR_ERROR;
6327 return false;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006328 } else if (rtp_data_channel_) {
6329 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006330 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006331 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6332 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006333}
6334
6335bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006336 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006337 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08006338 // Don't log an error here, because DataChannels are expected to call
6339 // ConnectDataChannel in this state. It's the only way to initially tell
6340 // whether or not the underlying transport is ready.
6341 return false;
6342 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006343 if (data_channel_transport_) {
6344 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6345 &DataChannel::OnChannelReady);
6346 SignalDataChannelTransportReceivedData_s.connect(
6347 webrtc_data_channel, &DataChannel::OnDataReceived);
6348 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006349 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006350 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006351 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006352 }
6353 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006354 rtp_data_channel_->SignalReadyToSendData.connect(
6355 webrtc_data_channel, &DataChannel::OnChannelReady);
6356 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6357 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006358 }
Steve Anton75737c02017-11-06 10:37:17 -08006359 return true;
6360}
6361
6362void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006363 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006364 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006365 RTC_LOG(LS_ERROR)
6366 << "DisconnectDataChannel called when rtp_data_channel_ and "
6367 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006368 return;
6369 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006370 if (data_channel_transport_) {
6371 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6372 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6373 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6374 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6375 }
6376 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08006377 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6378 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006379 }
Steve Anton75737c02017-11-06 10:37:17 -08006380}
6381
6382void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006383 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006384 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6385 if (data_channel_transport_) {
6386 data_channel_transport_->OpenChannel(sid);
6387 }
6388 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006389 }
Steve Anton75737c02017-11-06 10:37:17 -08006390}
6391
6392void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006393 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006394 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6395 if (data_channel_transport_) {
6396 data_channel_transport_->CloseChannel(sid);
6397 }
6398 });
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006399 }
Steve Anton75737c02017-11-06 10:37:17 -08006400}
6401
6402bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006403 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006404 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006405 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 10:37:17 -08006406}
6407
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006408void PeerConnection::OnDataReceived(int channel_id,
6409 DataMessageType type,
6410 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006411 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006412 cricket::ReceiveDataParams params;
6413 params.sid = channel_id;
6414 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006415 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006416 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6417 RTC_DCHECK_RUN_ON(signaling_thread());
6418 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006419 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006420 }
6421 });
6422}
6423
6424void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006425 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006426 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006427 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6428 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006429 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006430 });
6431}
6432
6433void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006434 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006435 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006436 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6437 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006438 SignalDataChannelTransportChannelClosed_s(channel_id);
6439 });
6440}
6441
6442void PeerConnection::OnReadyToSend() {
6443 RTC_DCHECK_RUN_ON(network_thread());
6444 data_channel_transport_invoker_->AsyncInvoke<void>(
6445 RTC_FROM_HERE, signaling_thread(), [this] {
6446 RTC_DCHECK_RUN_ON(signaling_thread());
6447 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006448 SignalDataChannelTransportWritable_s(
6449 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006450 });
6451}
6452
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006453absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006454 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006455 if (sctp_mid_ && transport_controller_) {
6456 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6457 if (dtls_transport) {
6458 return dtls_transport->transport_name();
6459 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006460 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006461 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006462 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006463}
6464
Qingsi Wang72a43a12018-02-20 16:03:18 -08006465cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6466 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006467 network_thread()->Invoke<void>(
6468 RTC_FROM_HERE,
6469 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6470 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006471 return candidate_states_list;
6472}
6473
Steve Anton5dfde182018-02-06 10:34:40 -08006474std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6475 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006476 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006477 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006478 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006479 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006480 if (channel) {
6481 transport_names_by_mid[channel->content_name()] =
6482 channel->transport_name();
6483 }
Steve Anton75737c02017-11-06 10:37:17 -08006484 }
Steve Anton5dfde182018-02-06 10:34:40 -08006485 if (rtp_data_channel_) {
6486 transport_names_by_mid[rtp_data_channel_->content_name()] =
6487 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006489 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006490 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006491 RTC_DCHECK(transport_name);
6492 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006493 }
Steve Anton5dfde182018-02-06 10:34:40 -08006494 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006495}
6496
Steve Anton5dfde182018-02-06 10:34:40 -08006497std::map<std::string, cricket::TransportStats>
6498PeerConnection::GetTransportStatsByNames(
6499 const std::set<std::string>& transport_names) {
6500 if (!network_thread()->IsCurrent()) {
6501 return network_thread()
6502 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6503 RTC_FROM_HERE,
6504 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006505 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006506 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006507 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6508 for (const std::string& transport_name : transport_names) {
6509 cricket::TransportStats transport_stats;
6510 bool success =
6511 transport_controller_->GetStats(transport_name, &transport_stats);
6512 if (success) {
6513 transport_stats_by_name[transport_name] = std::move(transport_stats);
6514 } else {
6515 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6516 << transport_name;
6517 }
6518 }
6519 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006520}
6521
6522bool PeerConnection::GetLocalCertificate(
6523 const std::string& transport_name,
6524 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006525 if (!certificate) {
6526 return false;
6527 }
6528 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6529 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006530}
6531
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006532std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006533 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006534 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006535}
6536
6537cricket::DataChannelType PeerConnection::data_channel_type() const {
6538 return data_channel_type_;
6539}
6540
6541bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006542 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006543 return pending_ice_restarts_.find(content_name) !=
6544 pending_ice_restarts_.end();
6545}
6546
Steve Anton75737c02017-11-06 10:37:17 -08006547bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6548 return transport_controller_->NeedsIceRestart(content_name);
6549}
6550
6551void PeerConnection::OnCertificateReady(
6552 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6553 transport_controller_->SetLocalCertificate(certificate);
6554}
6555
6556void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006557 SetSessionError(SessionError::kTransport,
6558 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006559}
6560
Alex Loiko9289eda2018-11-23 16:18:59 +00006561void PeerConnection::OnTransportControllerConnectionState(
6562 cricket::IceConnectionState state) {
6563 switch (state) {
6564 case cricket::kIceConnectionConnecting:
6565 // If the current state is Connected or Completed, then there were
6566 // writable channels but now there are not, so the next state must
6567 // be Disconnected.
6568 // kIceConnectionConnecting is currently used as the default,
6569 // un-connected state by the TransportController, so its only use is
6570 // detecting disconnections.
6571 if (ice_connection_state_ ==
6572 PeerConnectionInterface::kIceConnectionConnected ||
6573 ice_connection_state_ ==
6574 PeerConnectionInterface::kIceConnectionCompleted) {
6575 SetIceConnectionState(
6576 PeerConnectionInterface::kIceConnectionDisconnected);
6577 }
6578 break;
6579 case cricket::kIceConnectionFailed:
6580 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6581 break;
6582 case cricket::kIceConnectionConnected:
6583 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6584 "all transports are writable.";
6585 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6586 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6587 break;
6588 case cricket::kIceConnectionCompleted:
6589 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6590 "all transports are complete.";
6591 if (ice_connection_state_ !=
6592 PeerConnectionInterface::kIceConnectionConnected) {
6593 // If jumping directly from "checking" to "connected",
6594 // signal "connected" first.
6595 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6596 }
6597 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6598 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6599 ReportTransportStats();
6600 break;
6601 default:
6602 RTC_NOTREACHED();
6603 }
6604}
6605
Steve Anton75737c02017-11-06 10:37:17 -08006606void PeerConnection::OnTransportControllerCandidatesGathered(
6607 const std::string& transport_name,
6608 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006609 int sdp_mline_index;
6610 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006611 RTC_LOG(LS_ERROR)
6612 << "OnTransportControllerCandidatesGathered: content name "
6613 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006614 return;
6615 }
6616
6617 for (cricket::Candidates::const_iterator citer = candidates.begin();
6618 citer != candidates.end(); ++citer) {
6619 // Use transport_name as the candidate media id.
6620 std::unique_ptr<JsepIceCandidate> candidate(
6621 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6622 if (local_description()) {
6623 mutable_local_description()->AddCandidate(candidate.get());
6624 }
6625 OnIceCandidate(std::move(candidate));
6626 }
6627}
6628
Eldar Relloda13ea22019-06-01 12:23:43 +03006629void PeerConnection::OnTransportControllerCandidateError(
6630 const cricket::IceCandidateErrorEvent& event) {
6631 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6632 event.error_text);
6633}
6634
Steve Anton75737c02017-11-06 10:37:17 -08006635void PeerConnection::OnTransportControllerCandidatesRemoved(
6636 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006637 // Sanity check.
6638 for (const cricket::Candidate& candidate : candidates) {
6639 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006640 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006641 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006642 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006643 return;
6644 }
6645 }
6646
6647 if (local_description()) {
6648 mutable_local_description()->RemoveCandidates(candidates);
6649 }
6650 OnIceCandidatesRemoved(candidates);
6651}
6652
Alex Drake00c7ecf2019-08-06 10:54:47 -07006653void PeerConnection::OnTransportControllerCandidateChanged(
6654 const cricket::CandidatePairChangeEvent& event) {
6655 OnSelectedCandidatePairChanged(event);
6656}
6657
Steve Anton75737c02017-11-06 10:37:17 -08006658void PeerConnection::OnTransportControllerDtlsHandshakeError(
6659 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006660 RTC_HISTOGRAM_ENUMERATION(
6661 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6662 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006663}
6664
Steve Antoned10bd92017-12-05 10:52:59 -08006665void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006666 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006667 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006668 if (channel && !channel->enabled()) {
6669 channel->Enable(true);
6670 }
Steve Anton75737c02017-11-06 10:37:17 -08006671 }
6672
Steve Anton4171afb2017-11-20 10:20:22 -08006673 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006674 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006675 }
Steve Anton75737c02017-11-06 10:37:17 -08006676}
6677
6678// Returns the media index for a local ice candidate given the content name.
6679bool PeerConnection::GetLocalCandidateMediaIndex(
6680 const std::string& content_name,
6681 int* sdp_mline_index) {
6682 if (!local_description() || !sdp_mline_index) {
6683 return false;
6684 }
6685
6686 bool content_found = false;
6687 const ContentInfos& contents = local_description()->description()->contents();
6688 for (size_t index = 0; index < contents.size(); ++index) {
6689 if (contents[index].name == content_name) {
6690 *sdp_mline_index = static_cast<int>(index);
6691 content_found = true;
6692 break;
6693 }
6694 }
6695 return content_found;
6696}
6697
6698bool PeerConnection::UseCandidatesInSessionDescription(
6699 const SessionDescriptionInterface* remote_desc) {
6700 if (!remote_desc) {
6701 return true;
6702 }
6703 bool ret = true;
6704
6705 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6706 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6707 for (size_t n = 0; n < candidates->count(); ++n) {
6708 const IceCandidateInterface* candidate = candidates->at(n);
6709 bool valid = false;
6710 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6711 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006712 RTC_LOG(LS_INFO)
6713 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006714 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006715 }
6716 continue;
6717 }
6718 ret = UseCandidate(candidate);
6719 if (!ret) {
6720 break;
6721 }
6722 }
6723 }
6724 return ret;
6725}
6726
6727bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006728 RTCErrorOr<const cricket::ContentInfo*> result =
6729 FindContentInfo(remote_description(), candidate);
6730 if (!result.ok()) {
6731 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6732 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006733 return false;
6734 }
Steve Anton75737c02017-11-06 10:37:17 -08006735 std::vector<cricket::Candidate> candidates;
6736 candidates.push_back(candidate->candidate());
6737 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006738 RTCError error = transport_controller_->AddRemoteCandidates(
6739 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006740 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006741 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006742 // Candidates successfully submitted for checking.
6743 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6744 ice_connection_state_ ==
6745 PeerConnectionInterface::kIceConnectionDisconnected) {
6746 // If state is New, then the session has just gotten its first remote ICE
6747 // candidates, so go to Checking.
6748 // If state is Disconnected, the session is re-using old candidates or
6749 // receiving additional ones, so go to Checking.
6750 // If state is Connected, stay Connected.
6751 // TODO(bemasc): If state is Connected, and the new candidates are for a
6752 // newly added transport, then the state actually _should_ move to
6753 // checking. Add a way to distinguish that case.
6754 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6755 }
6756 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006757 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006758 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006759 }
6760 return true;
6761}
6762
Guido Urdaneta41633172019-05-23 20:12:29 +02006763RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6764 const SessionDescriptionInterface* description,
6765 const IceCandidateInterface* candidate) {
6766 if (candidate->sdp_mline_index() >= 0) {
6767 size_t mediacontent_index =
6768 static_cast<size_t>(candidate->sdp_mline_index());
6769 size_t content_size = description->description()->contents().size();
6770 if (mediacontent_index < content_size) {
6771 return &description->description()->contents()[mediacontent_index];
6772 } else {
6773 return RTCError(RTCErrorType::INVALID_RANGE,
6774 "Media line index (" +
6775 rtc::ToString(candidate->sdp_mline_index()) +
6776 ") out of range (number of mlines: " +
6777 rtc::ToString(content_size) + ").");
6778 }
6779 } else if (!candidate->sdp_mid().empty()) {
6780 auto& contents = description->description()->contents();
6781 auto it = absl::c_find_if(
6782 contents, [candidate](const cricket::ContentInfo& content_info) {
6783 return content_info.mid() == candidate->sdp_mid();
6784 });
6785 if (it == contents.end()) {
6786 return RTCError(
6787 RTCErrorType::INVALID_PARAMETER,
6788 "Mid " + candidate->sdp_mid() +
6789 " specified but no media section with that mid found.");
6790 } else {
6791 return &*it;
6792 }
6793 }
6794
6795 return RTCError(RTCErrorType::INVALID_PARAMETER,
6796 "Neither sdp_mline_index nor sdp_mid specified.");
6797}
6798
Steve Anton75737c02017-11-06 10:37:17 -08006799void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006800 // Destroy video channel first since it may have a pointer to the
6801 // voice channel.
6802 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006803 if (!video_info || video_info->rejected) {
6804 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006805 }
6806
Steve Anton6fec8802017-12-04 10:37:29 -08006807 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6808 if (!audio_info || audio_info->rejected) {
6809 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006810 }
6811
6812 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6813 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006814 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006815 }
6816}
6817
Steve Antondcc3c022017-12-22 16:02:54 -08006818RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6819 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006820 const cricket::ContentGroup* bundle_group = nullptr;
6821 if (configuration_.bundle_policy ==
6822 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006823 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006824 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006825 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6826 "max-bundle configured but session description "
6827 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006828 }
6829 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006830 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006831}
6832
6833RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006834 // Creating the media channels. Transports should already have been created
6835 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006836 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006837 if (voice && !voice->rejected &&
6838 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006839 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006840 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006841 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6842 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006843 }
6844 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6845 }
6846
Steve Antondcc3c022017-12-22 16:02:54 -08006847 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006848 if (video && !video->rejected &&
6849 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006850 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006851 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006852 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6853 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006854 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006855 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006856 }
6857
Steve Antondcc3c022017-12-22 16:02:54 -08006858 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006859 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006860 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006861 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006862 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6863 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006864 }
6865 }
6866
Steve Anton8a006912017-12-04 15:25:56 -08006867 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006868}
6869
Steve Anton4171afb2017-11-20 10:20:22 -08006870// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006871cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006872 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006873 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006874 MediaTransportConfig media_transport_config =
6875 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006876
Steve Anton75737c02017-11-06 10:37:17 -08006877 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006878 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006879 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6880 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006881 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006882 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006883 }
Steve Anton75737c02017-11-06 10:37:17 -08006884 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6885 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006886 voice_channel->SignalSentPacket.connect(this,
6887 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006888 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006889
Steve Antoneda6ccd2017-12-04 10:21:55 -08006890 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006891}
6892
Steve Anton4171afb2017-11-20 10:20:22 -08006893// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006894cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006895 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006896 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006897 MediaTransportConfig media_transport_config =
6898 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006899
Steve Anton75737c02017-11-06 10:37:17 -08006900 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006901 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006902 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6903 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006904 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006905 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006906 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006907 }
Steve Anton75737c02017-11-06 10:37:17 -08006908 video_channel->SignalDtlsSrtpSetupFailure.connect(
6909 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006910 video_channel->SignalSentPacket.connect(this,
6911 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006912 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006913
Steve Antoneda6ccd2017-12-04 10:21:55 -08006914 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006915}
6916
Zhi Huange830e682018-03-30 10:48:35 -07006917bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006918 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006919 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006920 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006921 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
6922 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006923 if (!network_thread()->Invoke<bool>(
6924 RTC_FROM_HERE,
6925 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6926 mid))) {
Qingsi Wang437077d2019-09-10 17:52:26 +00006927 return false;
6928 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006929
6930 // All non-RTP data channels must initialize |sctp_data_channels_|.
6931 for (const auto& channel : sctp_data_channels_) {
6932 channel->OnTransportChannelCreated();
6933 }
6934 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006935 case cricket::DCT_RTP:
6936 default:
6937 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6938 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6939 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006940 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006941 if (!rtp_data_channel_) {
6942 return false;
6943 }
6944 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6945 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6946 rtp_data_channel_->SignalSentPacket.connect(
6947 this, &PeerConnection::OnSentPacket_w);
6948 rtp_data_channel_->SetRtpTransport(rtp_transport);
6949 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006950 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006951 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006952}
6953
6954Call::Stats PeerConnection::GetCallStats() {
6955 if (!worker_thread()->IsCurrent()) {
6956 return worker_thread()->Invoke<Call::Stats>(
6957 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6958 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006959 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006960 if (call_) {
6961 return call_->GetStats();
6962 } else {
6963 return Call::Stats();
6964 }
6965}
6966
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006967bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006968 DataChannelTransportInterface* transport =
6969 transport_controller_->GetDataChannelTransport(mid);
6970 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006971 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006972 << "Data channel transport is not available for data channels, mid="
6973 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006974 return false;
6975 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006976 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006977
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006978 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 17:06:18 +02006979 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006980 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006981
6982 // Note: setting the data sink and checking initial state must be done last,
6983 // after setting up the data channel. Setting the data sink may trigger
6984 // callbacks to PeerConnection which require the transport to be completely
6985 // set up (eg. OnReadyToSend()).
6986 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006987 return true;
6988}
6989
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006990void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006991 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006992 return;
6993 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006994 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
6995 << *sctp_mid_;
6996
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006997 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6998 // it.
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006999 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:26 +00007000 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007001 if (data_channel_transport_) {
7002 data_channel_transport_->SetDataSink(nullptr);
7003 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007004 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007005}
7006
Steve Anton75737c02017-11-06 10:37:17 -08007007// Returns false if bundle is enabled and rtcp_mux is disabled.
7008bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
7009 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
7010 if (!bundle_enabled)
7011 return true;
7012
7013 const cricket::ContentGroup* bundle_group =
7014 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
7015 RTC_DCHECK(bundle_group != NULL);
7016
7017 const cricket::ContentInfos& contents = desc->contents();
7018 for (cricket::ContentInfos::const_iterator citer = contents.begin();
7019 citer != contents.end(); ++citer) {
7020 const cricket::ContentInfo* content = (&*citer);
7021 RTC_DCHECK(content != NULL);
7022 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08007023 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08007024 if (!HasRtcpMuxEnabled(content))
7025 return false;
7026 }
7027 }
7028 // RTCP-MUX is enabled in all the contents.
7029 return true;
7030}
7031
7032bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08007033 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08007034}
7035
Steve Anton06817cd2018-12-18 15:55:30 -08007036static RTCError ValidateMids(const cricket::SessionDescription& description) {
7037 std::set<std::string> mids;
7038 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08007039 if (content.name.empty()) {
7040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7041 "A media section is missing a MID attribute.");
7042 }
Steve Anton06817cd2018-12-18 15:55:30 -08007043 if (!mids.insert(content.name).second) {
7044 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7045 "Duplicate a=mid value '" + content.name + "'.");
7046 }
7047 }
7048 return RTCError::OK();
7049}
7050
Steve Anton8a006912017-12-04 15:25:56 -08007051RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08007052 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08007053 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08007054 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08007055 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08007056 }
7057
7058 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08007059 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08007060 }
7061
Steve Anton3828c062017-12-06 10:34:51 -08007062 SdpType type = sdesc->GetType();
7063 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
7064 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08007065 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01007066 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08007067 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08007068 }
7069
Steve Anton06817cd2018-12-18 15:55:30 -08007070 RTCError error = ValidateMids(*sdesc->description());
7071 if (!error.ok()) {
7072 return error;
7073 }
7074
Steve Anton75737c02017-11-06 10:37:17 -08007075 // Verify crypto settings.
7076 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08007077 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
7078 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007079 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08007080 if (!crypto_error.ok()) {
7081 return crypto_error;
7082 }
Steve Anton75737c02017-11-06 10:37:17 -08007083 }
7084
7085 // Verify ice-ufrag and ice-pwd.
7086 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007087 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7088 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08007089 }
7090
7091 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08007092 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7093 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08007094 }
7095
7096 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
7097 // m-lines that do not rtcp-mux enabled.
7098
7099 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08007100 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007101 // With an answer we want to compare the new answer session description with
7102 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08007103 const cricket::SessionDescription* offer_desc =
7104 (source == cricket::CS_LOCAL) ? remote_description()->description()
7105 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007106 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
7107 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
7108 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7110 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007111 }
7112 } else {
Steve Anton75737c02017-11-06 10:37:17 -08007113 // The re-offers should respect the order of m= sections in current
7114 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007115 // With a re-offer, either the current local or current remote descriptions
7116 // could be the most up to date, so we would like to check against both of
7117 // them if they exist. It could be the case that one of them has a 0 port
7118 // for a media section, but the other does not. This is important to check
7119 // against in the case that we are recycling an m= section.
7120 const cricket::SessionDescription* current_desc = nullptr;
7121 const cricket::SessionDescription* secondary_current_desc = nullptr;
7122 if (local_description()) {
7123 current_desc = local_description()->description();
7124 if (remote_description()) {
7125 secondary_current_desc = remote_description()->description();
7126 }
7127 } else if (remote_description()) {
7128 current_desc = remote_description()->description();
7129 }
Steve Anton75737c02017-11-06 10:37:17 -08007130 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08007131 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7132 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08007133 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7134 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08007135 }
7136 }
7137
Steve Antonba42e992018-04-09 14:10:01 -07007138 if (IsUnifiedPlan()) {
7139 // Ensure that each audio and video media section has at most one
7140 // "StreamParams". This will return an error if receiving a session
7141 // description from a "Plan B" endpoint which adds multiple tracks of the
7142 // same type. With Unified Plan, there can only be at most one track per
7143 // media section.
7144 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02007145 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07007146 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7147 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7148 desc.streams().size() > 1u) {
7149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7150 "Media section has more than one track specified "
7151 "with a=ssrc lines which is not supported with "
7152 "Unified Plan.");
7153 }
7154 }
7155 }
7156
Steve Anton8a006912017-12-04 15:25:56 -08007157 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08007158}
7159
Steve Anton3828c062017-12-06 10:34:51 -08007160bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007161 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007162 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007163 return (state == PeerConnectionInterface::kStable) ||
7164 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08007165 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007166 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007167 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7168 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7169 }
7170}
7171
Steve Anton3828c062017-12-06 10:34:51 -08007172bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08007173 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08007174 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08007175 return (state == PeerConnectionInterface::kStable) ||
7176 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08007177 } else {
Steve Anton3828c062017-12-06 10:34:51 -08007178 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08007179 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7180 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7181 }
7182}
7183
Steve Antonf8470812017-12-04 10:46:21 -08007184const char* PeerConnection::SessionErrorToString(SessionError error) const {
7185 switch (error) {
7186 case SessionError::kNone:
7187 return "ERROR_NONE";
7188 case SessionError::kContent:
7189 return "ERROR_CONTENT";
7190 case SessionError::kTransport:
7191 return "ERROR_TRANSPORT";
7192 }
7193 RTC_NOTREACHED();
7194 return "";
7195}
7196
Steve Anton75737c02017-11-06 10:37:17 -08007197std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02007198 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08007199 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7200 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02007201 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08007202}
7203
Steve Anton8e20f172018-03-06 10:55:04 -08007204void PeerConnection::ReportSdpFormatReceived(
7205 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08007206 int num_audio_mlines = 0;
7207 int num_video_mlines = 0;
7208 int num_audio_tracks = 0;
7209 int num_video_tracks = 0;
7210 for (const ContentInfo& content : remote_offer.description()->contents()) {
7211 cricket::MediaType media_type = content.media_description()->type();
7212 int num_tracks = std::max(
7213 1, static_cast<int>(content.media_description()->streams().size()));
7214 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7215 num_audio_mlines += 1;
7216 num_audio_tracks += num_tracks;
7217 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7218 num_video_mlines += 1;
7219 num_video_tracks += num_tracks;
7220 }
7221 }
7222 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7223 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7224 format = kSdpFormatReceivedComplexUnifiedPlan;
7225 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7226 format = kSdpFormatReceivedComplexPlanB;
7227 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7228 format = kSdpFormatReceivedSimple;
7229 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007230 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7231 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08007232}
7233
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007234void PeerConnection::ReportIceCandidateCollected(
7235 const cricket::Candidate& candidate) {
7236 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7237 if (candidate.address().IsPrivateIP()) {
7238 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7239 }
7240 if (candidate.address().IsUnresolvedIP()) {
7241 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7242 }
7243 if (candidate.address().family() == AF_INET6) {
7244 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7245 }
7246}
7247
7248void PeerConnection::ReportRemoteIceCandidateAdded(
7249 const cricket::Candidate& candidate) {
7250 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7251 if (candidate.address().IsPrivateIP()) {
7252 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7253 }
7254 if (candidate.address().IsUnresolvedIP()) {
7255 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7256 }
7257 if (candidate.address().family() == AF_INET6) {
7258 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7259 }
7260}
7261
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007262void PeerConnection::NoteUsageEvent(UsageEvent event) {
7263 RTC_DCHECK_RUN_ON(signaling_thread());
7264 usage_event_accumulator_ |= static_cast<int>(event);
7265}
7266
7267void PeerConnection::ReportUsagePattern() const {
7268 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007269 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7270 usage_event_accumulator_,
7271 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007272 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007273 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007274 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7275 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007276 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007277 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7278 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7279 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7280 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007281 // If called after close(), we can't report, because observer may have
7282 // been deallocated, and therefore pointer is null. Write to log instead.
7283 if (observer_) {
7284 Observer()->OnInterestingUsage(usage_event_accumulator_);
7285 } else {
7286 RTC_LOG(LS_INFO) << "Interesting usage signature "
7287 << usage_event_accumulator_
7288 << " observed after observer shutdown";
7289 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007290 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007291}
7292
Steve Anton0ffaaa22018-02-23 10:31:30 -08007293void PeerConnection::ReportNegotiatedSdpSemantics(
7294 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007295 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007296 switch (answer.description()->msid_signaling()) {
7297 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007298 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007299 break;
7300 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007301 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007302 break;
7303 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007304 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007305 break;
7306 case cricket::kMsidSignalingMediaSection |
7307 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007308 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007309 break;
7310 default:
7311 RTC_NOTREACHED();
7312 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007313 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7314 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007315}
7316
Steve Anton75737c02017-11-06 10:37:17 -08007317// We need to check the local/remote description for the Transport instead of
7318// the session, because a new Transport added during renegotiation may have
7319// them unset while the session has them set from the previous negotiation.
7320// Not doing so may trigger the auto generation of transport description and
7321// mess up DTLS identity information, ICE credential, etc.
7322bool PeerConnection::ReadyToUseRemoteCandidate(
7323 const IceCandidateInterface* candidate,
7324 const SessionDescriptionInterface* remote_desc,
7325 bool* valid) {
7326 *valid = true;
7327
7328 const SessionDescriptionInterface* current_remote_desc =
7329 remote_desc ? remote_desc : remote_description();
7330
7331 if (!current_remote_desc) {
7332 return false;
7333 }
7334
Guido Urdaneta41633172019-05-23 20:12:29 +02007335 RTCErrorOr<const cricket::ContentInfo*> result =
7336 FindContentInfo(current_remote_desc, candidate);
7337 if (!result.ok()) {
7338 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7339 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007340
7341 *valid = false;
7342 return false;
7343 }
7344
Guido Urdaneta41633172019-05-23 20:12:29 +02007345 std::string transport_name = GetTransportName(result.value()->name);
7346 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007347}
7348
7349bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007350 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007351 (dtls_enabled_ ||
7352 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007353}
7354
7355void PeerConnection::OnTransportControllerGatheringState(
7356 cricket::IceGatheringState state) {
7357 RTC_DCHECK(signaling_thread()->IsCurrent());
7358 if (state == cricket::kIceGatheringGathering) {
7359 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7360 } else if (state == cricket::kIceGatheringComplete) {
7361 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7362 }
7363}
7364
7365void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007366 std::map<std::string, std::set<cricket::MediaType>>
7367 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007368 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007369 if (transceiver->internal()->channel()) {
7370 const std::string& transport_name =
7371 transceiver->internal()->channel()->transport_name();
7372 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007373 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007374 }
Steve Anton75737c02017-11-06 10:37:17 -08007375 }
7376 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007377 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7378 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007379 }
Zhi Huange830e682018-03-30 10:48:35 -07007380
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007381 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007382 if (transport_name) {
7383 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007384 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007385 }
Zhi Huange830e682018-03-30 10:48:35 -07007386
Steve Antonc7b964c2018-02-01 14:39:45 -08007387 for (const auto& entry : media_types_by_transport_name) {
7388 const std::string& transport_name = entry.first;
7389 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007390 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007391 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007392 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007393 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007394 }
7395 }
7396}
7397// Walk through the ConnectionInfos to gather best connection usage
7398// for IPv4 and IPv6.
7399void PeerConnection::ReportBestConnectionState(
7400 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007401 for (const cricket::TransportChannelStats& channel_stats :
7402 stats.channel_stats) {
7403 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007404 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007405 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007406 continue;
7407 }
7408
Steve Antonc7b964c2018-02-01 14:39:45 -08007409 const cricket::Candidate& local = connection_info.local_candidate;
7410 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007411
7412 // Increment the counter for IceCandidatePairType.
7413 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7414 (local.type() == RELAY_PORT_TYPE &&
7415 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007416 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7417 GetIceCandidatePairCounter(local, remote),
7418 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007419 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7421 GetIceCandidatePairCounter(local, remote),
7422 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007423 } else {
7424 RTC_CHECK(0);
7425 }
Steve Anton75737c02017-11-06 10:37:17 -08007426
7427 // Increment the counter for IP type.
7428 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007429 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7430 kBestConnections_IPv4,
7431 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007432 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007433 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7434 kBestConnections_IPv6,
7435 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007436 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007437 RTC_CHECK(!local.address().hostname().empty() &&
7438 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007439 }
7440
7441 return;
7442 }
7443 }
7444}
7445
7446void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007447 const cricket::TransportStats& stats,
7448 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007449 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7450 return;
7451 }
7452
7453 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7454 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7455 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7456 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7457 return;
7458 }
7459
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007460 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7461 for (cricket::MediaType media_type : media_types) {
7462 switch (media_type) {
7463 case cricket::MEDIA_TYPE_AUDIO:
7464 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7465 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7466 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7467 break;
7468 case cricket::MEDIA_TYPE_VIDEO:
7469 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7470 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7471 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7472 break;
7473 case cricket::MEDIA_TYPE_DATA:
7474 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7475 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7476 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7477 break;
7478 default:
7479 RTC_NOTREACHED();
7480 continue;
7481 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007482 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007483 }
7484
7485 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7486 for (cricket::MediaType media_type : media_types) {
7487 switch (media_type) {
7488 case cricket::MEDIA_TYPE_AUDIO:
7489 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7490 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7491 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7492 break;
7493 case cricket::MEDIA_TYPE_VIDEO:
7494 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7495 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7496 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7497 break;
7498 case cricket::MEDIA_TYPE_DATA:
7499 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7500 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7501 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7502 break;
7503 default:
7504 RTC_NOTREACHED();
7505 continue;
7506 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007507 }
Steve Anton75737c02017-11-06 10:37:17 -08007508 }
7509}
7510
7511void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007512 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007513 RTC_DCHECK(call_);
7514 call_->OnSentPacket(sent_packet);
7515}
7516
7517const std::string PeerConnection::GetTransportName(
7518 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007519 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007520 if (channel) {
7521 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007522 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007523 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007524 RTC_DCHECK(sctp_mid_);
7525 if (content_name == *sctp_mid_) {
7526 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007527 }
7528 }
7529 // Return an empty string if failed to retrieve the transport name.
7530 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007531}
7532
Steve Anton6fec8802017-12-04 10:37:29 -08007533void PeerConnection::DestroyTransceiverChannel(
7534 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7535 transceiver) {
7536 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007537
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007538 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007539 if (channel) {
7540 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007541 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007542 }
7543}
7544
7545void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007546 if (rtp_data_channel_) {
7547 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007548 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007549 rtp_data_channel_ = nullptr;
7550 }
7551
7552 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7553 // grab a reference to this PeerConnection. If this is called from the
7554 // PeerConnection destructor, the RefCountedObject vtable will have already
7555 // been destroyed (since it is a subclass of PeerConnection) and using
7556 // rtc::Bind will cause "Pure virtual function called" error to appear.
7557
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007558 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007559 OnDataChannelDestroyed();
7560 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7561 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007562 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007563 });
7564 }
Steve Anton6fec8802017-12-04 10:37:29 -08007565}
7566
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007567void PeerConnection::DestroyChannelInterface(
7568 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007569 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007570 switch (channel->media_type()) {
7571 case cricket::MEDIA_TYPE_AUDIO:
7572 channel_manager()->DestroyVoiceChannel(
7573 static_cast<cricket::VoiceChannel*>(channel));
7574 break;
7575 case cricket::MEDIA_TYPE_VIDEO:
7576 channel_manager()->DestroyVideoChannel(
7577 static_cast<cricket::VideoChannel*>(channel));
7578 break;
7579 case cricket::MEDIA_TYPE_DATA:
7580 channel_manager()->DestroyRtpDataChannel(
7581 static_cast<cricket::RtpDataChannel*>(channel));
7582 break;
7583 default:
7584 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7585 break;
7586 }
Zhi Huange830e682018-03-30 10:48:35 -07007587}
Steve Anton6fec8802017-12-04 10:37:29 -08007588
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007589bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007590 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007591 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007592 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007593 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007594 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007595 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007596 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007597 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007598 auto base_channel = GetChannel(mid);
7599 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007600 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007601 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007602
Karl Wiberg5966c502019-02-21 23:55:09 +01007603 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007604 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007605 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007606
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007607 if (data_channel_transport_ && mid == sctp_mid_ &&
7608 data_channel_transport_ != data_channel_transport) {
7609 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7610 // it's bundled).
7611 data_channel_transport_->SetDataSink(nullptr);
7612 data_channel_transport_ = data_channel_transport;
7613 if (data_channel_transport) {
7614 data_channel_transport->SetDataSink(this);
7615
7616 // There's a new data channel transport. This needs to be signaled to the
7617 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7618 // necessary when bundling is applied.
7619 data_channel_transport_invoker_->AsyncInvoke<void>(
7620 RTC_FROM_HERE, signaling_thread(), [this] {
7621 RTC_DCHECK_RUN_ON(signaling_thread());
7622 for (auto channel : sctp_data_channels_) {
7623 channel->OnTransportChannelCreated();
7624 }
7625 });
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007626 }
7627 }
7628
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007629 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007630}
7631
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007632void PeerConnection::OnSetStreams() {
7633 RTC_DCHECK_RUN_ON(signaling_thread());
7634 if (IsUnifiedPlan())
7635 UpdateNegotiationNeeded();
7636}
7637
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007638PeerConnectionObserver* PeerConnection::Observer() const {
7639 // In earlier production code, the pointer was not cleared on close,
7640 // which might have led to undefined behavior if the observer was not
7641 // deallocated, or strange crashes if it was.
7642 // We use CHECK in order to catch such behavior if it exists.
7643 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7644 RTC_CHECK(observer_);
7645 return observer_;
7646}
7647
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007648CryptoOptions PeerConnection::GetCryptoOptions() {
7649 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7650 // after it has been removed.
7651 return configuration_.crypto_options.has_value()
7652 ? *configuration_.crypto_options
7653 : factory_->options().crypto_options;
7654}
7655
Harald Alvestrand89061872018-01-02 14:08:34 +01007656void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007657 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007658 if (stats_collector_) {
7659 stats_collector_->ClearCachedStatsReport();
7660 }
7661}
7662
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007663void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007664 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7665 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007666}
7667
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007668void PeerConnection::UpdateNegotiationNeeded() {
7669 RTC_DCHECK_RUN_ON(signaling_thread());
7670 if (!IsUnifiedPlan()) {
7671 Observer()->OnRenegotiationNeeded();
7672 return;
7673 }
7674
7675 // If connection's [[IsClosed]] slot is true, abort these steps.
7676 if (IsClosed())
7677 return;
7678
7679 // If connection's signaling state is not "stable", abort these steps.
7680 if (signaling_state() != kStable)
7681 return;
7682
7683 // NOTE
7684 // The negotiation-needed flag will be updated once the state transitions to
7685 // "stable", as part of the steps for setting an RTCSessionDescription.
7686
7687 // If the result of checking if negotiation is needed is false, clear the
7688 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7689 // to false, and abort these steps.
7690 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7691 if (!is_negotiation_needed) {
7692 is_negotiation_needed_ = false;
7693 return;
7694 }
7695
7696 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7697 // steps.
7698 if (is_negotiation_needed_)
7699 return;
7700
7701 // Set connection's [[NegotiationNeeded]] slot to true.
7702 is_negotiation_needed_ = true;
7703
7704 // Queue a task that runs the following steps:
7705 // If connection's [[IsClosed]] slot is true, abort these steps.
7706 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7707 // Fire an event named negotiationneeded at connection.
7708 Observer()->OnRenegotiationNeeded();
7709}
7710
7711bool PeerConnection::CheckIfNegotiationIsNeeded() {
7712 RTC_DCHECK_RUN_ON(signaling_thread());
7713 // 1. If any implementation-specific negotiation is required, as described at
7714 // the start of this section, return true.
7715
Henrik Boström79b69802019-07-18 11:16:56 +02007716 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7717 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7718 return true;
7719 }
7720
7721 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007722 const SessionDescriptionInterface* description = current_local_description();
7723 if (!description)
7724 return true;
7725
Henrik Boström79b69802019-07-18 11:16:56 +02007726 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007727 // description has been negotiated yet for data, return true.
7728 if (!sctp_data_channels_.empty()) {
7729 if (!cricket::GetFirstDataContent(description->description()->contents()))
7730 return true;
7731 }
7732
Henrik Boström79b69802019-07-18 11:16:56 +02007733 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007734 // following checks:
7735 for (const auto& transceiver : transceivers_) {
7736 const ContentInfo* current_local_msection =
7737 FindTransceiverMSection(transceiver.get(), description);
7738
7739 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7740 transceiver.get(), current_remote_description());
7741
Henrik Boström79b69802019-07-18 11:16:56 +02007742 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007743 // but the associated m= section is not yet rejected in
7744 // connection.[[CurrentLocalDescription]] or
7745 // connection.[[CurrentRemoteDescription]], return true.
7746 if (transceiver->stopped()) {
7747 if (current_local_msection && !current_local_msection->rejected &&
7748 ((current_remote_msection && !current_remote_msection->rejected) ||
7749 !current_remote_msection)) {
7750 return true;
7751 }
7752 continue;
7753 }
7754
Henrik Boström79b69802019-07-18 11:16:56 +02007755 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007756 // section in description, return true.
7757 if (!current_local_msection)
7758 return true;
7759
7760 const MediaContentDescription* current_local_media_description =
7761 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007762 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007763 // in description then perform the following checks:
7764
Henrik Boström79b69802019-07-18 11:16:56 +02007765 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007766 // associated m= section in description either doesn't contain a single
7767 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7768 // m= section, or the MSID values themselves, differ from what is in
7769 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7770 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7771 if (current_local_media_description->streams().size() == 0)
7772 return true;
7773
7774 std::vector<std::string> msection_msids;
7775 for (const auto& stream : current_local_media_description->streams()) {
7776 for (const std::string& msid : stream.stream_ids())
7777 msection_msids.push_back(msid);
7778 }
7779
7780 std::vector<std::string> transceiver_msids =
7781 transceiver->sender()->stream_ids();
7782 if (msection_msids.size() != transceiver_msids.size())
7783 return true;
7784
7785 absl::c_sort(transceiver_msids);
7786 absl::c_sort(msection_msids);
7787 if (transceiver_msids != msection_msids)
7788 return true;
7789 }
7790
Henrik Boström79b69802019-07-18 11:16:56 +02007791 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007792 // associated m= section in neither connection.[[CurrentLocalDescription]]
7793 // nor connection.[[CurrentRemoteDescription]] matches
7794 // transceiver.[[Direction]], return true.
7795 if (description->GetType() == SdpType::kOffer) {
7796 if (!current_remote_description())
7797 return true;
7798
7799 if (!current_remote_msection)
7800 return true;
7801
7802 RtpTransceiverDirection current_local_direction =
7803 current_local_media_description->direction();
7804 RtpTransceiverDirection current_remote_direction =
7805 current_remote_msection->media_description()->direction();
7806 if (transceiver->direction() != current_local_direction &&
7807 transceiver->direction() !=
7808 RtpTransceiverDirectionReversed(current_remote_direction)) {
7809 return true;
7810 }
7811 }
7812
Henrik Boström79b69802019-07-18 11:16:56 +02007813 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007814 // associated m= section in the description does not match
7815 // transceiver.[[Direction]] intersected with the offered direction (as
7816 // described in [JSEP] (section 5.3.1.)), return true.
7817 if (description->GetType() == SdpType::kAnswer) {
7818 if (!remote_description())
7819 return true;
7820
7821 const ContentInfo* offered_remote_msection =
7822 FindTransceiverMSection(transceiver.get(), remote_description());
7823
7824 RtpTransceiverDirection offered_direction =
7825 offered_remote_msection
7826 ? offered_remote_msection->media_description()->direction()
7827 : RtpTransceiverDirection::kInactive;
7828
7829 if (current_local_media_description->direction() !=
7830 (RtpTransceiverDirectionIntersection(
7831 transceiver->direction(),
7832 RtpTransceiverDirectionReversed(offered_direction)))) {
7833 return true;
7834 }
7835 }
7836 }
7837
7838 // If all the preceding checks were performed and true was not returned,
7839 // nothing remains to be negotiated; return false.
7840 return false;
7841}
7842
Eldar Relloead0ec92019-10-21 23:01:31 +03007843RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007844 auto state = signaling_state();
7845 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7846 state != PeerConnectionInterface::kHaveRemoteOffer) {
7847 return RTCError(RTCErrorType::INVALID_STATE,
7848 "Called in wrong signalingState: " +
7849 GetSignalingStateString(signaling_state()));
7850 }
7851 RTC_DCHECK_RUN_ON(signaling_thread());
7852 RTC_DCHECK(IsUnifiedPlan());
7853
7854 for (auto&& transceivers_stable_state_pair :
7855 transceiver_stable_states_by_transceivers_) {
7856 auto transceiver = transceivers_stable_state_pair.first;
7857 auto state = transceivers_stable_state_pair.second;
7858 RTC_DCHECK(transceiver->internal()->mid().has_value());
7859 std::string mid = transceiver->internal()->mid().value();
7860 transport_controller_->RollbackTransportForMid(mid);
7861 DestroyTransceiverChannel(transceiver);
7862
Eldar Relloead0ec92019-10-21 23:01:31 +03007863 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7864 transceiver->receiver()) {
7865 Observer()->OnRemoveTrack(transceiver->receiver());
7866 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007867 if (state.newly_created()) {
7868 // Remove added transceivers with no added track.
7869 if (transceiver->internal()->sender()->track()) {
7870 transceiver->internal()->set_created_by_addtrack(true);
7871 } else {
7872 int remaining_transceiver_count = 0;
7873 for (auto&& t : transceivers_) {
7874 if (t != transceiver) {
7875 transceivers_[remaining_transceiver_count++] = t;
7876 }
7877 }
7878 transceivers_.resize(remaining_transceiver_count);
7879 }
7880 }
7881 transceiver->internal()->sender_internal()->set_transport(nullptr);
7882 transceiver->internal()->receiver_internal()->set_transport(nullptr);
7883 transceiver->internal()->set_direction(state.direction());
7884 transceiver->internal()->set_mid(state.mid());
7885 transceiver->internal()->set_mline_index(state.mline_index());
7886 }
7887 transceiver_stable_states_by_transceivers_.clear();
7888 pending_local_description_.reset();
7889 pending_remote_description_.reset();
7890 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03007891
7892 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
7893 // gets called in SetRemoteDescription.
7894 if (sdp_type == SdpType::kRollback) {
7895 UpdateNegotiationNeeded();
7896 if (is_negotiation_needed_) {
7897 Observer()->OnRenegotiationNeeded();
7898 }
7899 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007900 return RTCError::OK();
7901}
7902
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007903} // namespace webrtc