blob: 9fac7485ca602d1a6bbabece076ed581a0effebf [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * 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:369 */
10
Steve Anton10542f22019-01-11 17:11:0011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Harald Alvestrand8ebba742018-05-31 12:00:3414#include <limits>
Mirko Bonadei317a1f02019-09-17 15:06:1815#include <memory>
Steve Antondcc3c022017-12-23 00:02:5416#include <queue>
Steve Anton75737c02017-11-06 18:37:1717#include <set>
kwiberg0eb15ed2015-12-17 11:04:1518#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3620
Steve Anton64b626b2019-01-29 01:25:2621#include "absl/algorithm/container.h"
Fredrik Solenberg41f3a432018-12-17 20:02:2222#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 17:11:0023#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 21:11:5727#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 10:24:5328#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 11:53:5129#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 21:11:5730#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 17:11:0031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 05:38:4032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3133#include "call/call.h"
Steve Anton10542f22019-01-11 17:11:0034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 21:11:5735#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 17:11:0036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 09:29:1937#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 17:11:0038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 18:37:1739#include "pc/channel.h"
Steve Anton10542f22019-01-11 17:11:0040#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 06:51:0048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 17:11:0049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 09:29:1952#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 17:11:0053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3154#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 11:41:3058#include "rtc_base/strings/string_builder.h"
Bjorn A Mellemb689af42019-08-21 17:44:5959#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3160#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 19:54:5363#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3664
Steve Anton75737c02017-11-06 18:37:1765using cricket::ContentInfo;
66using cricket::ContentInfos;
67using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-21 00:34:0068using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-26 01:13:5669using cricket::RidDescription;
70using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 18:13:5871using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-26 01:13:5672using cricket::SimulcastDescription;
73using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 18:13:5874using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-26 01:13:5675using cricket::StreamParams;
Steve Anton75737c02017-11-06 18:37:1776using cricket::TransportInfo;
77
78using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 18:37:1779using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 20:13:4880using cricket::RELAY_PORT_TYPE;
81using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 18:37:1782
Steve Antonba818672017-11-06 18:21:5783namespace webrtc {
84
Steve Anton75737c02017-11-06 18:37:1785// Error messages
86const char kBundleWithoutRtcpMux[] =
87 "rtcp-mux must be enabled when BUNDLE "
88 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1789const 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 18:37:1797const 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:36108
Steve Anton75737c02017-11-06 18:37:17109namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36110
Bjorn A Mellem5985a042019-06-28 21:19:38111// Field trials.
112// Controls datagram transport support.
113const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 17:44:59114// Controls datagram transport data channel support.
115const char kDatagramTransportDataChannelFieldTrial[] =
116 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 21:19:38117
Amit Hilbuche2a284d2019-03-05 20:36:31118// 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 19:34:10127static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:22128static const char kDefaultAudioSenderId[] = "defaulta0";
129static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11130
zhihuang8f65cdf2016-05-07 01:40:30131// The length of RTCP CNAMEs.
132static const int kRtcpCnameLength = 16;
133
Steve Antonad182762018-09-05 20:22:40134enum {
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 10:03:50143static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
144
Steve Antonad182762018-09-05 20:22:40145struct 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 18:33:11171// 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 23:05:28177 if (current_streams->find(new_stream->id()) != nullptr) {
178 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25179 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11180 return false;
181 }
182 return true;
183}
184
deadbeef5e97fb52015-10-15 19:49:08185// 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 22:57:10190 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08191 ? desc->streams()
192 : std::vector<cricket::StreamParams>();
193}
194
deadbeefab9b2d12015-10-14 18:33:11195bool IsValidOfferToReceiveMedia(int value) {
196 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
197 return (value >= Options::kUndefined) &&
198 (value <= Options::kMaxOfferToReceiveMedia);
199}
200
zhihuang1c378ed2017-08-17 21:10:50201// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 18:13:58202void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39203 const std::vector<rtc::scoped_refptr<
204 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50205 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37206 cricket::MediaDescriptionOptions* video_media_description_options,
207 int num_sim_layers) {
olka3c747662017-08-17 13:50:32208 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50209 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
210 if (audio_media_description_options) {
211 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38212 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50213 }
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 18:13:58218 sender->id(), sender->internal()->stream_ids(), {},
219 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50220 }
221 }
zhihuanga77e6bb2017-08-15 01:17:48222 }
zhihuang1c378ed2017-08-17 21:10:50223}
olka3c747662017-08-17 13:50:32224
zhihuang1c378ed2017-08-17 21:10:50225// 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 18:33:11233 // 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 21:10:50238 // 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 18:33:11242 }
243 }
244}
245
Taylor Brandstettera1c30352016-05-13 15:15:11246uint32_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 13:56:46258 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11259 }
260 return cricket::CF_NONE;
261}
262
Steve Antonba818672017-11-06 18:21:57263std::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 18:38:28282
Steve Anton75737c02017-11-06 18:37:17283IceCandidatePairType 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 16:25:54293 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 18:37:17297 bool local_private = IPIsPrivate(local.address().ipaddr());
298 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 16:25:54299 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 18:37:17311 return kIceCandidatePairHostPrivateHostPrivate;
312 } else {
313 return kIceCandidatePairHostPrivateHostPublic;
314 }
315 } else {
Jeroen de Borst833979f2018-12-13 16:25:54316 if (remote_hostname) {
317 return kIceCandidatePairHostPublicHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17319 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 23:33:48356// 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 18:37:17371// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48372// |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 18:37:17385 return false;
386 }
387
Seth Hampsonae8a90a2018-02-13 23:33:48388 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-23 00:02:54399 continue;
400 }
Seth Hampsonae8a90a2018-02-13 23:33:48401 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17402 return false;
403 }
404 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48405 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 18:37:17409 return false;
410 }
411 }
412 return true;
413}
414
Seth Hampsonae8a90a2018-02-13 23:33:48415bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
416 const SessionDescription& desc2) {
417 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17418}
419
Qingsi Wang7fc821d2018-07-12 19:54:53420void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
421 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20422 // 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 19:54:53444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
445 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26446
Mirko Bonadeiab499822018-09-11 08:43:20447 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 13:15:26453 }
454}
455
Harald Alvestrand76829d72018-07-18 21:24:36456void NoteAddIceCandidateResult(int result) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
458 kAddIceCandidateMax);
459}
460
Steve Anton75737c02017-11-06 18:37:17461// 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 19:54:53467RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17468 const cricket::ContentGroup* bundle =
469 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56470 for (const cricket::ContentInfo& content_info : desc->contents()) {
471 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17472 continue;
473 }
Harald Alvestrand2e180612018-03-07 09:56:14474 // 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 19:54:53477 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56478 const std::string& mid = content_info.name;
479 if (bundle && bundle->HasContentName(mid) &&
480 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17481 // 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 23:14:30489 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56490 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17491 if (!media || !tinfo) {
492 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17494 }
495 if (dtls_enabled) {
496 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25497 RTC_LOG(LS_WARNING)
498 << "Session description must have DTLS fingerprint if "
499 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56500 return RTCError(RTCErrorType::INVALID_PARAMETER,
501 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17502 }
503 } else {
504 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25505 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17506 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56507 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17508 }
509 }
510 }
Steve Anton8a006912017-12-04 23:25:56511 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17512}
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 23:25:56520 for (const cricket::ContentInfo& content_info : desc->contents()) {
521 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17522 continue;
523 }
Steve Anton8a006912017-12-04 23:25:56524 const std::string& mid = content_info.name;
525 if (bundle && bundle->HasContentName(mid) &&
526 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17527 // 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 23:25:56535 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17536 if (!tinfo) {
537 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25538 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17539 return false;
540 }
541 if (tinfo->description.ice_ufrag.empty() ||
542 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25543 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17544 return false;
545 }
546 }
547 return true;
548}
549
Steve Anton75737c02017-11-06 18:37:17550// 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 10:09:25575 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
576 << ".";
Steve Anton75737c02017-11-06 18:37:17577 return true;
578 }
579 return false;
580}
581
Steve Anton80dd7b52018-02-17 01:08:42582// 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 11:41:30587 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42588 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
589 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32590 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42591}
592
Seth Hampson5b4f0752018-04-02 23:31:36593std::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 14:47:43604absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23605 int rtc_configuration_parameter) {
606 if (rtc_configuration_parameter ==
607 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43608 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23609 }
610 return rtc_configuration_parameter;
611}
612
Amit Hilbuche2a284d2019-03-05 20:36:31613void 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 18:35:45618 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 20:36:31619 continue;
620 }
Harald Alvestrand1716d392019-06-03 18:35:45621 has_spec_compliant |= content.media_description()->HasSimulcast();
622 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 20:36:31623 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 10:24:14641const 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 11:09:49650// 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 18:37:17695} // namespace
696
Henrik Boström4e196702019-10-30 09:35:50697// Used by parameterless SetLocalDescription() to create an offer or answer.
698// Upon completion of creating the session description, SetLocalDescription() is
699// invoked with the result.
700// For consistency with DoSetLocalDescription(), if the PeerConnection is
701// destroyed midst operation, we DO NOT inform the
702// |set_local_description_observer| that the operation failed.
703// TODO(hbos): If/when we process SLD messages in ~PeerConnection, the
704// consistent thing would be to inform the observer here.
705class PeerConnection::ImplicitCreateSessionDescriptionObserver
706 : public CreateSessionDescriptionObserver {
707 public:
708 ImplicitCreateSessionDescriptionObserver(
709 rtc::WeakPtr<PeerConnection> pc,
710 rtc::scoped_refptr<SetSessionDescriptionObserver>
711 set_local_description_observer)
712 : pc_(std::move(pc)),
713 set_local_description_observer_(
714 std::move(set_local_description_observer)) {}
715 ~ImplicitCreateSessionDescriptionObserver() override {
716 RTC_DCHECK(was_called_);
717 }
718
719 void SetOperationCompleteCallback(
720 std::function<void()> operation_complete_callback) {
721 operation_complete_callback_ = std::move(operation_complete_callback);
722 }
723
724 bool was_called() const { return was_called_; }
725
726 void OnSuccess(SessionDescriptionInterface* desc_ptr) override {
727 RTC_DCHECK(!was_called_);
728 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
729 was_called_ = true;
730
731 // Abort early if |pc_| is no longer valid.
732 if (!pc_) {
733 operation_complete_callback_();
734 return;
735 }
736 // DoSetLocalDescription() is currently implemented as a synchronous
737 // operation but where the |set_local_description_observer_|'s callbacks are
738 // invoked asynchronously in a post to PeerConnection::OnMessage().
739 pc_->DoSetLocalDescription(std::move(desc),
740 std::move(set_local_description_observer_));
741 // For backwards-compatability reasons, we declare the operation as
742 // completed here (rather than in PeerConnection::OnMessage()). This ensures
743 // that subsequent offer/answer operations can start immediately (without
744 // waiting for OnMessage()).
745 operation_complete_callback_();
746 }
747
748 void OnFailure(RTCError error) override {
749 RTC_DCHECK(!was_called_);
750 was_called_ = true;
751
752 // Abort early if |pc_| is no longer valid.
753 if (!pc_) {
754 operation_complete_callback_();
755 return;
756 }
757 // DoSetLocalDescription() reports its failures in a post. We do the
758 // same thing here for consistency.
759 pc_->PostSetSessionDescriptionFailure(
760 set_local_description_observer_,
761 RTCError(error.type(),
762 std::string("SetLocalDescription failed to create "
763 "session description - ") +
764 error.message()));
765 operation_complete_callback_();
766 }
767
768 private:
769 bool was_called_ = false;
770 rtc::WeakPtr<PeerConnection> pc_;
771 rtc::scoped_refptr<SetSessionDescriptionObserver>
772 set_local_description_observer_;
773 std::function<void()> operation_complete_callback_;
774};
775
Henrik Boström79b69802019-07-18 09:16:56776class PeerConnection::LocalIceCredentialsToReplace {
777 public:
778 // Sets the ICE credentials that need restarting to the ICE credentials of
779 // the current and pending descriptions.
780 void SetIceCredentialsFromLocalDescriptions(
781 const SessionDescriptionInterface* current_local_description,
782 const SessionDescriptionInterface* pending_local_description) {
783 ice_credentials_.clear();
784 if (current_local_description) {
785 AppendIceCredentialsFromSessionDescription(*current_local_description);
786 }
787 if (pending_local_description) {
788 AppendIceCredentialsFromSessionDescription(*pending_local_description);
789 }
790 }
791
792 void ClearIceCredentials() { ice_credentials_.clear(); }
793
794 // Returns true if we have ICE credentials that need restarting.
795 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
796
797 // Returns true if |local_description| shares no ICE credentials with the
798 // ICE credentials that need restarting.
799 bool SatisfiesIceRestart(
800 const SessionDescriptionInterface& local_description) const {
801 for (const auto& transport_info :
802 local_description.description()->transport_infos()) {
803 if (ice_credentials_.find(std::make_pair(
804 transport_info.description.ice_ufrag,
805 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
806 return false;
807 }
808 }
809 return true;
810 }
811
812 private:
813 void AppendIceCredentialsFromSessionDescription(
814 const SessionDescriptionInterface& desc) {
815 for (const auto& transport_info : desc.description()->transport_infos()) {
816 ice_credentials_.insert(
817 std::make_pair(transport_info.description.ice_ufrag,
818 transport_info.description.ice_pwd));
819 }
820 }
821
822 std::set<std::pair<std::string, std::string>> ice_credentials_;
823};
824
Henrik Boström31638672017-11-23 16:48:32825// Upon completion, posts a task to execute the callback of the
826// SetSessionDescriptionObserver asynchronously on the same thread. At this
827// point, the state of the peer connection might no longer reflect the effects
828// of the SetRemoteDescription operation, as the peer connection could have been
829// modified during the post.
830// TODO(hbos): Remove this class once we remove the version of
831// PeerConnectionInterface::SetRemoteDescription() that takes a
832// SetSessionDescriptionObserver as an argument.
833class PeerConnection::SetRemoteDescriptionObserverAdapter
834 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
835 public:
836 SetRemoteDescriptionObserverAdapter(
837 rtc::scoped_refptr<PeerConnection> pc,
838 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
839 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
840
841 // SetRemoteDescriptionObserverInterface implementation.
842 void OnSetRemoteDescriptionComplete(RTCError error) override {
843 if (error.ok())
844 pc_->PostSetSessionDescriptionSuccess(wrapper_);
845 else
Harald Alvestrand5081c0c2018-03-09 14:18:03846 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32847 }
848
849 private:
850 rtc::scoped_refptr<PeerConnection> pc_;
851 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
852};
853
deadbeef293e9262017-01-11 20:28:30854bool PeerConnectionInterface::RTCConfiguration::operator==(
855 const PeerConnectionInterface::RTCConfiguration& o) const {
856 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10857 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30858 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56859 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10860 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30861 BundlePolicy bundle_policy;
862 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10863 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
864 int ice_candidate_pool_size;
865 bool disable_ipv6;
866 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11867 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22868 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10869 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43870 absl::optional<int> screencast_min_bitrate;
871 absl::optional<bool> combined_audio_video_bwe;
872 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30873 TcpCandidatePolicy tcp_candidate_policy;
874 CandidateNetworkPolicy candidate_network_policy;
875 int audio_jitter_buffer_max_packets;
876 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 14:45:20877 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 14:58:36878 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 20:28:30879 int ice_connection_receiving_timeout;
880 int ice_backup_candidate_pair_ping_interval;
881 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30882 bool prioritize_most_likely_ice_candidate_pairs;
883 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30884 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 18:27:50885 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 20:28:30886 bool presume_writable_when_fully_relayed;
887 bool enable_ice_renomination;
888 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 23:55:33889 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 14:47:43890 absl::optional<int> ice_check_interval_strong_connectivity;
891 absl::optional<int> ice_check_interval_weak_connectivity;
892 absl::optional<int> ice_check_min_interval;
893 absl::optional<int> ice_unwritable_timeout;
894 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:17895 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 14:47:43896 absl::optional<int> stun_candidate_keepalive_interval;
897 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40898 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56899 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43900 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11901 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21902 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48903 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 21:19:38904 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 17:44:59905 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 18:02:11906 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 17:16:44907 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48908 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 14:16:35909 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 15:29:44910 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 10:23:02911 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 20:28:30912 };
913 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
914 "Did you add something to RTCConfiguration and forget to "
915 "update operator==?");
916 return type == o.type && servers == o.servers &&
917 bundle_policy == o.bundle_policy &&
918 rtcp_mux_policy == o.rtcp_mux_policy &&
919 tcp_candidate_policy == o.tcp_candidate_policy &&
920 candidate_network_policy == o.candidate_network_policy &&
921 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
922 audio_jitter_buffer_fast_accelerate ==
923 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 14:45:20924 audio_jitter_buffer_min_delay_ms ==
925 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 14:58:36926 audio_jitter_buffer_enable_rtx_handling ==
927 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 20:28:30928 ice_connection_receiving_timeout ==
929 o.ice_connection_receiving_timeout &&
930 ice_backup_candidate_pair_ping_interval ==
931 o.ice_backup_candidate_pair_ping_interval &&
932 continual_gathering_policy == o.continual_gathering_policy &&
933 certificates == o.certificates &&
934 prioritize_most_likely_ice_candidate_pairs ==
935 o.prioritize_most_likely_ice_candidate_pairs &&
936 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51937 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11938 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22939 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30940 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30941 screencast_min_bitrate == o.screencast_min_bitrate &&
942 combined_audio_video_bwe == o.combined_audio_video_bwe &&
943 enable_dtls_srtp == o.enable_dtls_srtp &&
944 ice_candidate_pool_size == o.ice_candidate_pool_size &&
945 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 18:27:50946 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 20:28:30947 presume_writable_when_fully_relayed ==
948 o.presume_writable_when_fully_relayed &&
949 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14950 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 23:55:33951 surface_ice_candidates_on_ice_transport_type_changed ==
952 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 22:55:14953 ice_check_interval_strong_connectivity ==
954 o.ice_check_interval_strong_connectivity &&
955 ice_check_interval_weak_connectivity ==
956 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10957 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57958 ice_unwritable_timeout == o.ice_unwritable_timeout &&
959 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-07 07:30:17960 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 22:45:49961 stun_candidate_keepalive_interval ==
962 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40963 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56964 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40965 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11966 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21967 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44968 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48969 use_media_transport_for_data_channels ==
970 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 22:50:38971 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 17:44:59972 use_datagram_transport_for_data_channels ==
973 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 18:02:11974 use_datagram_transport_for_data_channels_receive_only ==
975 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 09:25:48976 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 14:16:35977 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 15:29:44978 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 10:23:02979 enable_implicit_rollback == o.enable_implicit_rollback &&
980 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 20:28:30981}
982
983bool PeerConnectionInterface::RTCConfiguration::operator!=(
984 const PeerConnectionInterface::RTCConfiguration& o) const {
985 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26986}
987
zhihuang8f65cdf2016-05-07 01:40:30988// Generate a RTCP CNAME when a PeerConnection is created.
989std::string GenerateRtcpCname() {
990 std::string cname;
991 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25992 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27993 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30994 }
995 return cname;
996}
997
zhihuang1c378ed2017-08-17 21:10:50998bool ValidateOfferAnswerOptions(
999 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
1000 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
1001 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:321002}
1003
zhihuang1c378ed2017-08-17 21:10:501004// From |rtc_options|, fill parts of |session_options| shared by all generated
1005// m= sections (in other words, nothing that involves a map/array).
1006void ExtractSharedMediaSessionOptions(
1007 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1008 cricket::MediaSessionOptions* session_options) {
1009 session_options->vad_enabled = rtc_options.voice_activity_detection;
1010 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 13:38:501011 session_options->raw_packetization_for_video =
1012 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 21:10:501013}
zhihuanga77e6bb2017-08-15 01:17:481014
zhihuang38ede132017-06-15 19:52:321015PeerConnection::PeerConnection(PeerConnectionFactory* factory,
1016 std::unique_ptr<RtcEventLog> event_log,
1017 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:361018 : factory_(factory),
zhihuang38ede132017-06-15 19:52:321019 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 10:59:571020 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 11:09:491021 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 21:19:381022 datagram_transport_config_(
1023 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 17:44:591024 datagram_transport_data_channel_config_(
1025 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-07 01:40:301026 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:111027 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:321028 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 08:57:011029 call_(std::move(call)),
Henrik Boström79b69802019-07-18 09:16:561030 call_ptr_(call_.get()),
Bjorn A Mellembc3eebc2019-09-23 21:53:541031 data_channel_transport_(nullptr),
Henrik Boströma3728d32019-10-28 11:09:491032 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
1033 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:361034
1035PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:171036 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:221037 RTC_DCHECK_RUN_ON(signaling_thread());
1038
Henrik Boströma3728d32019-10-28 11:09:491039 weak_ptr_factory_.InvalidateWeakPtrs();
1040
Steve Anton8af21862017-12-15 19:20:131041 // Need to stop transceivers before destroying the stats collector because
1042 // AudioRtpSender has a reference to the StatsCollector it will update when
1043 // stopping.
Mirko Bonadei739baf02019-01-27 16:29:421044 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:131045 transceiver->Stop();
1046 }
Steve Anton4171afb2017-11-20 18:20:221047
Taylor Brandstettera1c30352016-05-13 15:15:111048 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:571049 if (stats_collector_) {
1050 stats_collector_->WaitForPendingRequest();
1051 stats_collector_ = nullptr;
1052 }
Steve Anton75737c02017-11-06 18:37:171053
Steve Anton8af21862017-12-15 19:20:131054 // Don't destroy BaseChannels until after stats has been cleaned up so that
1055 // the last stats request can still read from the channels.
1056 DestroyAllChannels();
1057
Mirko Bonadei675513b2017-11-09 10:09:251058 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:171059
1060 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 18:37:171061 sctp_factory_.reset();
Bjorn A Mellemb689af42019-08-21 17:44:591062 data_channel_transport_invoker_.reset();
Steve Anton75737c02017-11-06 18:37:171063 transport_controller_.reset();
1064
deadbeef91dd5672016-05-18 23:55:301065 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 13:13:221066 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1067 RTC_DCHECK_RUN_ON(network_thread());
1068 port_allocator_.reset();
1069 });
eladalon248fd4f2017-09-06 12:18:151070 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:021071 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:571072 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:151073 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:091074 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:151075 event_log_.reset();
1076 });
Henrik Boströma3728d32019-10-28 11:09:491077
1078 // Process all pending notifications in the message queue. If we don't do
1079 // this, requests will linger and not know they succeeded or failed.
1080 rtc::MessageList list;
1081 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1082 for (auto& msg : list) {
1083 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1084 // Processing CreateOffer() and CreateAnswer() messages ensures their
1085 // observers are invoked even if the PeerConnection is destroyed early.
1086 OnMessage(&msg);
1087 } else {
1088 // TODO(hbos): Consider processing all pending messages. This would mean
1089 // that SetLocalDescription() and SetRemoteDescription() observers are
1090 // informed of successes and failures; this is currently NOT the case.
1091 delete msg.pdata;
1092 }
1093 }
henrike@webrtc.org28e20752013-07-10 00:45:361094}
1095
Steve Anton8af21862017-12-15 19:20:131096void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:081097 // Destroy video channels first since they may have a pointer to a voice
1098 // channel.
Mirko Bonadei739baf02019-01-27 16:29:421099 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081100 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:081101 DestroyTransceiverChannel(transceiver);
1102 }
1103 }
Mirko Bonadei739baf02019-01-27 16:29:421104 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081105 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:081106 DestroyTransceiverChannel(transceiver);
1107 }
1108 }
Harald Alvestrand408cb4b2019-11-16 11:09:081109 DestroyDataChannelTransport();
Steve Anton3fe1b152017-12-12 18:20:081110}
1111
henrike@webrtc.org28e20752013-07-10 00:45:361112bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:451113 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:471114 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 09:18:561115 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 22:55:091116 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 21:15:171117 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:591118
1119 RTCError config_error = ValidateConfiguration(configuration);
1120 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:251121 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:591122 return false;
1123 }
1124
Benjamin Wrightcab588882018-05-02 22:12:471125 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:251126 RTC_LOG(LS_ERROR)
1127 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:071128 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:301129 return false;
1130 }
Jonas Orelandbdcee282017-10-10 12:01:401131
Benjamin Wrightcab588882018-05-02 22:12:471132 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:301133 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:251134 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:071135 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:101136 return false;
1137 }
Benjamin Wrightd6f86e82018-05-08 20:12:251138
Benjamin Wrightcab588882018-05-02 22:12:471139 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:151140 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:471141 port_allocator_ = std::move(dependencies.allocator);
Qingsi Wang25ec8882019-11-15 20:33:051142 ice_transport_factory_ = std::move(dependencies.ice_transport_factory);
Benjamin Wrightd6f86e82018-05-08 20:12:251143 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:101144
Harald Alvestrandb2a74782018-06-28 11:54:071145 cricket::ServerAddresses stun_servers;
1146 std::vector<cricket::RelayServerConfig> turn_servers;
1147
1148 RTCErrorType parse_error =
1149 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1150 if (parse_error != RTCErrorType::NONE) {
1151 return false;
1152 }
1153
Jonas Oreland3c028422019-08-22 14:16:351154 // Add the turn logging id to all turn servers
1155 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1156 turn_server.turn_logging_id = configuration.turn_logging_id;
1157 }
1158
deadbeef91dd5672016-05-18 23:55:301159 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:111160 // there.
Karl Wibergfb3be392019-03-22 13:13:221161 const auto pa_result =
1162 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 11:54:071163 RTC_FROM_HERE,
1164 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 13:13:221165 stun_servers, turn_servers, configuration));
1166
Harald Alvestrandb2a74782018-06-28 11:54:071167 // If initialization was successful, note if STUN or TURN servers
1168 // were supplied.
1169 if (!stun_servers.empty()) {
1170 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1171 }
1172 if (!turn_servers.empty()) {
1173 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1174 }
henrike@webrtc.org28e20752013-07-10 00:45:361175
Qingsi Wang7fc821d2018-07-12 19:54:531176 // Send information about IPv4/IPv6 status.
1177 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 13:13:221178 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 19:54:531179 address_family = kPeerConnection_IPv6;
1180 } else {
1181 address_family = kPeerConnection_IPv4;
1182 }
1183 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1184 kPeerConnectionAddressFamilyCounter_Max);
1185
Zhi Huange830e682018-03-30 17:48:351186 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1187
Steve Anton75737c02017-11-06 18:37:171188 // RFC 3264: The numeric value of the session id and version in the
1189 // o line MUST be representable with a "64 bit signed integer".
1190 // Due to this constraint session id |session_id_| is max limited to
1191 // LLONG_MAX.
1192 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:351193 JsepTransportController::Config config;
1194 config.redetermine_role_on_ice_restart =
1195 configuration.redetermine_role_on_ice_restart;
1196 config.ssl_max_version = factory_->options().ssl_max_version;
1197 config.disable_encryption = options.disable_encryption;
1198 config.bundle_policy = configuration.bundle_policy;
1199 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 17:16:441200 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1201 // stub.
1202 config.crypto_options = configuration.crypto_options.has_value()
1203 ? *configuration.crypto_options
1204 : options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:341205 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 16:22:121206 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1207 // since the JsepTransportController instance is owned by this PeerConnection
1208 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1209 // pointer.
1210 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1211 int64_t packet_time_us) {
1212 RTC_DCHECK_RUN_ON(network_thread());
1213 rtcp_invoker_.AsyncInvoke<void>(
1214 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1215 RTC_DCHECK_RUN_ON(worker_thread());
1216 // |call_| is reset on the worker thread in the PeerConnection
1217 // destructor, so we check that it's still valid before propagating
1218 // the packet.
1219 if (call_) {
1220 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1221 packet_time_us);
1222 }
1223 });
1224 };
Karl Wibergb03ab712019-02-14 10:59:571225 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 17:48:351226#if defined(ENABLE_EXTERNAL_AUTH)
1227 config.enable_external_auth = true;
1228#endif
Zhi Huangb57e1692018-06-12 18:41:111229 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:421230
Bjorn A Mellem5985a042019-06-28 21:19:381231 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 18:06:001232 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 21:19:381233 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 17:44:591234 use_datagram_transport_for_data_channels_ =
1235 datagram_transport_data_channel_config_.enabled &&
1236 configuration.use_datagram_transport_for_data_channels.value_or(
1237 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 18:02:111238 use_datagram_transport_for_data_channels_receive_only_ =
1239 configuration.use_datagram_transport_for_data_channels_receive_only
1240 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellemb689af42019-08-21 17:44:591241 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
1242 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 16:07:481243 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 20:15:421244 if (!factory_->media_transport_factory()) {
1245 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 16:07:481246 << "PeerConnecton is initialized with use_media_transport = true or "
1247 << "use_media_transport_for_data_channels = true "
1248 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 20:15:421249 return false;
1250 }
1251
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:051252 if (configuration.use_media_transport ||
1253 configuration.use_media_transport_for_data_channels) {
1254 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1255 // RTP media transport is introduced. But until then, we require SDES to
1256 // be enabled.
1257 if (configuration.enable_dtls_srtp.has_value() &&
1258 configuration.enable_dtls_srtp.value()) {
1259 RTC_LOG(LS_WARNING)
1260 << "When media transport is used, SDES must be enabled. Set "
1261 "configuration.enable_dtls_srtp to false. use_media_transport="
1262 << configuration.use_media_transport
1263 << ", use_media_transport_for_data_channels="
1264 << configuration.use_media_transport_for_data_channels;
1265 return false;
1266 }
1267 }
1268
Piotr (Peter) Slatala55b91b92019-01-25 21:31:151269 config.use_media_transport_for_media = configuration.use_media_transport;
1270 config.use_media_transport_for_data_channels =
1271 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 21:19:381272 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 17:44:591273 config.use_datagram_transport_for_data_channels =
1274 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 18:02:111275 config.use_datagram_transport_for_data_channels_receive_only =
1276 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 20:15:421277 config.media_transport_factory = factory_->media_transport_factory();
1278 }
1279
Bjorn A Mellembc3eebc2019-09-23 21:53:541280 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1281 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1282 if (!configuration.certificates.empty()) {
1283 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1284 // just picking the first one. The decision should be made based on the DTLS
1285 // handshake. The DTLS negotiations need to know about all certificates.
1286 certificate = configuration.certificates[0];
1287 }
1288
1289 if (options.disable_encryption) {
1290 dtls_enabled_ = false;
1291 } else {
1292 // Enable DTLS by default if we have an identity store or a certificate.
1293 dtls_enabled_ = (dependencies.cert_generator || certificate);
1294 // |configuration| can override the default |dtls_enabled_| value.
1295 if (configuration.enable_dtls_srtp) {
1296 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1297 }
1298 }
1299
1300 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1301
1302 if (use_datagram_transport_for_data_channels_) {
1303 if (configuration.enable_rtp_data_channel) {
1304 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1305 "use_datagram_transport_for_data_channels are "
1306 "incompatible and cannot both be set to true";
1307 return false;
1308 }
1309 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1310 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
1311 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
1312 } else {
1313 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
1314 data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
1315 config.sctp_factory = sctp_factory_.get();
1316 }
1317 } else if (configuration.use_media_transport_for_data_channels) {
1318 if (configuration.enable_rtp_data_channel) {
1319 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1320 "use_media_transport_for_data_channels are "
1321 "incompatible and cannot both be set to true";
1322 return false;
1323 }
1324 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1325 } else if (configuration.enable_rtp_data_channel) {
1326 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1327 // set. It takes precendence over the disable_sctp_data_channels
1328 // PeerConnectionFactoryInterface::Options.
1329 data_channel_type_ = cricket::DCT_RTP;
1330 } else {
1331 // DTLS has to be enabled to use SCTP.
1332 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1333 data_channel_type_ = cricket::DCT_SCTP;
1334 config.sctp_factory = sctp_factory_.get();
1335 }
1336 }
1337
Qingsi Wang25ec8882019-11-15 20:33:051338 config.ice_transport_factory = ice_transport_factory_.get();
1339
Zhi Huange830e682018-03-30 17:48:351340 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:151341 signaling_thread(), network_thread(), port_allocator_.get(),
1342 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:351343 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:591344 this, &PeerConnection::OnTransportControllerConnectionState);
1345 transport_controller_->SignalStandardizedIceConnectionState.connect(
1346 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:171347 transport_controller_->SignalConnectionState.connect(
1348 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:351349 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:171350 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:351351 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:171352 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 09:23:431353 transport_controller_->SignalIceCandidateError.connect(
1354 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 17:48:351355 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:171356 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1357 transport_controller_->SignalDtlsHandshakeError.connect(
1358 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 17:54:471359 transport_controller_->SignalIceCandidatePairChanged.connect(
1360 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 18:37:171361
deadbeefab9b2d12015-10-14 18:33:111362 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:011363 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:361364
Steve Antonba818672017-11-06 18:21:571365 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 22:55:091366 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 18:21:571367
Steve Antond25da372017-11-06 22:50:291368 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171369
Steve Anton75737c02017-11-06 18:37:171370 video_options_.screencast_min_bitrate_kbps =
1371 configuration.screencast_min_bitrate;
1372 audio_options_.combined_audio_video_bwe =
1373 configuration.combined_audio_video_bwe;
1374
1375 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301376 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171377
1378 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301379 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171380
Jakob Ivarsson10403ae2018-11-27 14:45:201381 audio_options_.audio_jitter_buffer_min_delay_ms =
1382 configuration.audio_jitter_buffer_min_delay_ms;
1383
Jakob Ivarsson53eae872019-01-10 14:58:361384 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1385 configuration.audio_jitter_buffer_enable_rtx_handling;
1386
Steve Anton75737c02017-11-06 18:37:171387 // Whether the certificate generator/certificate is null or not determines
1388 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1389 // the right instructions by clearing the variables if needed.
1390 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471391 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171392 certificate = nullptr;
1393 } else if (certificate) {
1394 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471395 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171396 }
1397
1398 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1399 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-26 01:13:561400 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 18:37:171401 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1402 this, &PeerConnection::OnCertificateReady);
1403
1404 if (options.disable_encryption) {
1405 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1406 }
1407
1408 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 17:16:441409 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-11 00:08:051410 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:361411
Steve Anton4171afb2017-11-20 18:20:221412 // Add default audio/video transceivers for Plan B SDP.
1413 if (!IsUnifiedPlan()) {
1414 transceivers_.push_back(
1415 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1416 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1417 transceivers_.push_back(
1418 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1419 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1420 }
Harald Alvestrand183e09d2018-06-28 10:04:411421 int delay_ms =
1422 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401423 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1424 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 05:38:401425
1426 if (dependencies.video_bitrate_allocator_factory) {
1427 video_bitrate_allocator_factory_ =
1428 std::move(dependencies.video_bitrate_allocator_factory);
1429 } else {
1430 video_bitrate_allocator_factory_ =
1431 CreateBuiltinVideoBitrateAllocatorFactory();
1432 }
henrike@webrtc.org28e20752013-07-10 00:45:361433 return true;
1434}
1435
Steve Anton038834f2017-07-14 22:59:591436RTCError PeerConnection::ValidateConfiguration(
1437 const RTCConfiguration& config) const {
1438 if (config.ice_regather_interval_range &&
1439 config.continual_gathering_policy == GATHER_ONCE) {
1440 return RTCError(RTCErrorType::INVALID_PARAMETER,
1441 "ice_regather_interval_range specified but continual "
1442 "gathering policy is GATHER_ONCE");
1443 }
Qingsi Wangdea68892018-03-27 17:55:211444 auto result =
1445 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1446 return result;
Steve Anton038834f2017-07-14 22:59:591447}
1448
Yves Gerey665174f2018-06-19 13:03:051449rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 22:55:091450 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581451 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1452 "Plan SdpSemantics. Please use GetSenders "
1453 "instead.";
deadbeefab9b2d12015-10-14 18:33:111454 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361455}
1456
Yves Gerey665174f2018-06-19 13:03:051457rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 22:55:091458 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581459 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1460 "Plan SdpSemantics. Please use GetReceivers "
1461 "instead.";
deadbeefab9b2d12015-10-14 18:33:111462 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361463}
1464
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291465bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561466 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581467 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1468 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171469 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361470 if (IsClosed()) {
1471 return false;
1472 }
deadbeefab9b2d12015-10-14 18:33:111473 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361474 return false;
1475 }
deadbeefab9b2d12015-10-14 18:33:111476
1477 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431478 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1479 observer->SignalAudioTrackAdded.connect(this,
1480 &PeerConnection::OnAudioTrackAdded);
1481 observer->SignalAudioTrackRemoved.connect(
1482 this, &PeerConnection::OnAudioTrackRemoved);
1483 observer->SignalVideoTrackAdded.connect(this,
1484 &PeerConnection::OnVideoTrackAdded);
1485 observer->SignalVideoTrackRemoved.connect(
1486 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291487 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111488
deadbeefab9b2d12015-10-14 18:33:111489 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251490 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111491 }
1492 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251493 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111494 }
1495
tommi@webrtc.org03505bc2014-07-14 20:15:261496 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 10:24:141497 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361498 return true;
1499}
1500
1501void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561502 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581503 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1504 "Plan SdpSemantics. Please use RemoveTrack "
1505 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171506 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251507 if (!IsClosed()) {
1508 for (const auto& track : local_stream->GetAudioTracks()) {
1509 RemoveAudioTrack(track.get(), local_stream);
1510 }
1511 for (const auto& track : local_stream->GetVideoTracks()) {
1512 RemoveVideoTrack(track.get(), local_stream);
1513 }
deadbeefab9b2d12015-10-14 18:33:111514 }
deadbeefab9b2d12015-10-14 18:33:111515 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431516 stream_observers_.erase(
1517 std::remove_if(
1518 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291519 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281520 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431521 }),
1522 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111523
henrike@webrtc.org28e20752013-07-10 00:45:361524 if (IsClosed()) {
1525 return;
1526 }
Guido Urdaneta70c2db12019-04-16 10:24:141527 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361528}
1529
Steve Anton2d6c76a2018-01-06 01:10:521530RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571531 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101532 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 09:18:561533 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-06 01:10:521534 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571535 if (!track) {
1536 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1537 }
1538 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1539 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1540 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1541 "Track has invalid kind: " + track->kind());
1542 }
Steve Antonf9381f02017-12-14 18:23:571543 if (IsClosed()) {
1544 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1545 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421546 }
Steve Anton4171afb2017-11-20 18:20:221547 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571548 LOG_AND_RETURN_ERROR(
1549 RTCErrorType::INVALID_PARAMETER,
1550 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421551 }
Steve Antonf9381f02017-12-14 18:23:571552 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361553 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1554 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571555 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 10:24:141556 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171557 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571558 }
1559 return sender_or_error;
1560}
deadbeefe1f9d832016-01-14 23:35:421561
Steve Antonf9381f02017-12-14 18:23:571562RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1563PeerConnection::AddTrackPlanB(
1564 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101565 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361566 if (stream_ids.size() > 1u) {
1567 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1568 "AddTrack with more than one stream is not "
1569 "supported with Plan B semantics.");
1570 }
1571 std::vector<std::string> adjusted_stream_ids = stream_ids;
1572 if (adjusted_stream_ids.empty()) {
1573 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1574 }
Steve Anton02ee47c2018-01-11 00:26:061575 cricket::MediaType media_type =
1576 (track->kind() == MediaStreamTrackInterface::kAudioKind
1577 ? cricket::MEDIA_TYPE_AUDIO
1578 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361579 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201580 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421581 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051582 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221583 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221584 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181585 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361586 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221587 if (sender_info) {
1588 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421589 }
Steve Antonf9381f02017-12-14 18:23:571590 } else {
1591 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051592 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221593 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221594 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181595 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361596 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221597 if (sender_info) {
1598 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421599 }
deadbeefe1f9d832016-01-14 23:35:421600 }
Steve Anton02ee47c2018-01-11 00:26:061601 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571602}
deadbeefe1f9d832016-01-14 23:35:421603
Steve Antonf9381f02017-12-14 18:23:571604RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1605PeerConnection::AddTrackUnifiedPlan(
1606 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101607 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571608 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1609 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231610 RTC_LOG(LS_INFO) << "Reusing an existing "
1611 << cricket::MediaTypeToString(transceiver->media_type())
1612 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571613 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121614 transceiver->internal()->set_direction(
1615 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571616 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121617 transceiver->internal()->set_direction(
1618 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571619 }
Steve Anton02ee47c2018-01-11 00:26:061620 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:381621 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571622 } else {
1623 cricket::MediaType media_type =
1624 (track->kind() == MediaStreamTrackInterface::kAudioKind
1625 ? cricket::MEDIA_TYPE_AUDIO
1626 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231627 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1628 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501629 std::string sender_id = track->id();
1630 // Avoid creating a sender with an existing ID by generating a random ID.
1631 // This can happen if this is the second time AddTrack has created a sender
1632 // for this track.
1633 if (FindSenderById(sender_id)) {
1634 sender_id = rtc::CreateRandomUuid();
1635 }
Florent Castelli892acf02018-10-01 20:47:201636 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061637 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1638 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571639 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121640 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571641 }
Steve Antonf9381f02017-12-14 18:23:571642 return transceiver->sender();
1643}
1644
1645rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1646PeerConnection::FindFirstTransceiverForAddedTrack(
1647 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1648 RTC_DCHECK(track);
1649 for (auto transceiver : transceivers_) {
1650 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081651 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571652 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421653 !transceiver->internal()->has_ever_been_used_to_send() &&
1654 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571655 return transceiver;
1656 }
1657 }
1658 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421659}
1660
1661bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1662 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331663 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571664}
1665
Steve Anton24db5732018-07-23 17:27:331666RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571667 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 09:18:561668 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 18:23:571669 if (!sender) {
1670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1671 }
deadbeefe1f9d832016-01-14 23:35:421672 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1674 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421675 }
Steve Antonf9381f02017-12-14 18:23:571676 if (IsUnifiedPlan()) {
1677 auto transceiver = FindTransceiverBySender(sender);
1678 if (!transceiver || !sender->track()) {
1679 return RTCError::OK();
1680 }
1681 sender->SetTrack(nullptr);
1682 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121683 transceiver->internal()->set_direction(
1684 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571685 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121686 transceiver->internal()->set_direction(
1687 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571688 }
Steve Anton4171afb2017-11-20 18:20:221689 } else {
Steve Antonf9381f02017-12-14 18:23:571690 bool removed;
1691 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1692 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1693 } else {
1694 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1695 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1696 }
1697 if (!removed) {
1698 LOG_AND_RETURN_ERROR(
1699 RTCErrorType::INVALID_PARAMETER,
1700 "Couldn't find sender " + sender->id() + " to remove.");
1701 }
Steve Anton4171afb2017-11-20 18:20:221702 }
Guido Urdaneta70c2db12019-04-16 10:24:141703 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571704 return RTCError::OK();
1705}
1706
1707rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1708PeerConnection::FindTransceiverBySender(
1709 rtc::scoped_refptr<RtpSenderInterface> sender) {
1710 for (auto transceiver : transceivers_) {
1711 if (transceiver->sender() == sender) {
1712 return transceiver;
1713 }
1714 }
1715 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421716}
1717
Steve Anton9158ef62017-11-27 21:01:521718RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1719PeerConnection::AddTransceiver(
1720 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1721 return AddTransceiver(track, RtpTransceiverInit());
1722}
1723
1724RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1725PeerConnection::AddTransceiver(
1726 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1727 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561728 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581729 RTC_CHECK(IsUnifiedPlan())
1730 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521731 if (!track) {
1732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1733 }
1734 cricket::MediaType media_type;
1735 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1736 media_type = cricket::MEDIA_TYPE_AUDIO;
1737 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1738 media_type = cricket::MEDIA_TYPE_VIDEO;
1739 } else {
1740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1741 "Track kind is not audio or video");
1742 }
1743 return AddTransceiver(media_type, track, init);
1744}
1745
1746RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1747PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1748 return AddTransceiver(media_type, RtpTransceiverInit());
1749}
1750
1751RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1752PeerConnection::AddTransceiver(cricket::MediaType media_type,
1753 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561754 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581755 RTC_CHECK(IsUnifiedPlan())
1756 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521757 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1758 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1759 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1760 "media type is not audio or video");
1761 }
1762 return AddTransceiver(media_type, nullptr, init);
1763}
1764
1765RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1766PeerConnection::AddTransceiver(
1767 cricket::MediaType media_type,
1768 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071769 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 10:24:141770 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 21:01:521771 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1772 media_type == cricket::MEDIA_TYPE_VIDEO));
1773 if (track) {
1774 RTC_DCHECK_EQ(media_type,
1775 (track->kind() == MediaStreamTrackInterface::kAudioKind
1776 ? cricket::MEDIA_TYPE_AUDIO
1777 : cricket::MEDIA_TYPE_VIDEO));
1778 }
1779
Amit Hilbuche2a284d2019-03-05 20:36:311780 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1781 init.send_encodings.size(), 0, 7, 8);
1782
Amit Hilbuchaa584152019-02-07 01:09:521783 size_t num_rids = absl::c_count_if(init.send_encodings,
1784 [](const RtpEncodingParameters& encoding) {
1785 return !encoding.rid.empty();
1786 });
1787 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-07 01:09:521788 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-07 01:09:521789 RTCErrorType::INVALID_PARAMETER,
1790 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:391791 }
1792
Amit Hilbuchf4770402019-04-08 21:11:571793 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1794 [](const RtpEncodingParameters& encoding) {
1795 return !IsLegalRsidName(encoding.rid);
1796 })) {
1797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1798 "Invalid RID value provided.");
1799 }
1800
Amit Hilbuchaa584152019-02-07 01:09:521801 if (absl::c_any_of(init.send_encodings,
1802 [](const RtpEncodingParameters& encoding) {
1803 return encoding.ssrc.has_value();
1804 })) {
1805 LOG_AND_RETURN_ERROR(
1806 RTCErrorType::UNSUPPORTED_PARAMETER,
1807 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 20:47:201808 }
1809
1810 RtpParameters parameters;
1811 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-07 01:09:521812
1813 // Encodings are dropped from the tail if too many are provided.
1814 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1815 parameters.encodings.erase(
1816 parameters.encodings.begin() + kMaxSimulcastStreams,
1817 parameters.encodings.end());
1818 }
1819
1820 // Single RID should be removed.
1821 if (parameters.encodings.size() == 1 &&
1822 !parameters.encodings[0].rid.empty()) {
1823 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1824 parameters.encodings[0].rid.clear();
1825 }
1826
1827 // If RIDs were not provided, they are generated for simulcast scenario.
1828 if (parameters.encodings.size() > 1 && num_rids == 0) {
1829 rtc::UniqueStringGenerator rid_generator;
1830 for (RtpEncodingParameters& encoding : parameters.encodings) {
1831 encoding.rid = rid_generator();
1832 }
1833 }
1834
Florent Castelli892acf02018-10-01 20:47:201835 if (UnimplementedRtpParameterHasValue(parameters)) {
1836 LOG_AND_RETURN_ERROR(
1837 RTCErrorType::UNSUPPORTED_PARAMETER,
1838 "Attempted to set an unimplemented parameter of RtpParameters.");
1839 }
Steve Anton9158ef62017-11-27 21:01:521840
Florent Castellic1a0bcb2019-01-29 13:26:481841 auto result = cricket::CheckRtpParametersValues(parameters);
1842 if (!result.ok()) {
1843 LOG_AND_RETURN_ERROR(result.type(), result.message());
1844 }
1845
Steve Anton3d954a62018-04-02 18:27:231846 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1847 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501848 // Set the sender ID equal to the track ID if the track is specified unless
1849 // that sender ID is already in use.
1850 std::string sender_id =
1851 (track && !FindSenderById(track->id()) ? track->id()
1852 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 20:47:201853 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-07 01:09:521854 parameters.encodings);
Steve Anton02ee47c2018-01-11 00:26:061855 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1856 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1857 transceiver->internal()->set_direction(init.direction);
1858
Guido Urdaneta70c2db12019-04-16 10:24:141859 if (update_negotiation_needed) {
1860 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071861 }
Steve Antonf9381f02017-12-14 18:23:571862
1863 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1864}
1865
Steve Anton02ee47c2018-01-11 00:26:061866rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1867PeerConnection::CreateSender(
1868 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361869 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061870 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201871 const std::vector<std::string>& stream_ids,
1872 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 08:57:011873 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 21:01:521874 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061875 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1876 RTC_DCHECK(!track ||
1877 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1878 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1879 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 17:31:531880 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 12:00:341881 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061882 } else {
1883 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1884 RTC_DCHECK(!track ||
1885 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1886 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 17:31:531887 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 12:00:341888 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061889 }
Steve Anton111fdfd2018-06-25 20:03:361890 bool set_track_succeeded = sender->SetTrack(track);
1891 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:381892 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 20:47:201893 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061894 return sender;
1895}
1896
1897rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1898PeerConnection::CreateReceiver(cricket::MediaType media_type,
1899 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521900 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1901 receiver;
Steve Anton9158ef62017-11-27 21:01:521902 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521903 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531904 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1905 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341906 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521907 } else {
Steve Anton02ee47c2018-01-11 00:26:061908 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521909 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531910 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1911 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341912 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521913 }
Steve Anton02ee47c2018-01-11 00:26:061914 return receiver;
1915}
1916
1917rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1918PeerConnection::CreateAndAddTransceiver(
1919 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1920 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1921 receiver) {
Steve Anton07563732018-06-26 18:13:501922 // Ensure that the new sender does not have an ID that is already in use by
1923 // another sender.
1924 // Allow receiver IDs to conflict since those come from remote SDP (which
1925 // could be invalid, but should not cause a crash).
1926 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061927 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 17:25:511928 signaling_thread(),
1929 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 21:01:521930 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121931 transceiver->internal()->SignalNegotiationNeeded.connect(
1932 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571933 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521934}
1935
Steve Anton52d86772018-02-20 23:48:121936void PeerConnection::OnNegotiationNeeded() {
1937 RTC_DCHECK_RUN_ON(signaling_thread());
1938 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 10:24:141939 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121940}
1941
deadbeeffac06552015-11-25 19:26:011942rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441943 const std::string& kind,
1944 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 22:55:091945 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581946 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1947 "Plan SdpSemantics. Please use AddTransceiver "
1948 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171949 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251950 if (IsClosed()) {
1951 return nullptr;
1952 }
Steve Anton4171afb2017-11-20 18:20:221953
Seth Hampson5b4f0752018-04-02 23:31:361954 // Internally we need to have one stream with Plan B semantics, so we
1955 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101956 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361957 if (stream_id.empty()) {
1958 stream_ids.push_back(rtc::CreateRandomUuid());
1959 RTC_LOG(LS_INFO)
1960 << "No stream_id specified for sender. Generated stream ID: "
1961 << stream_ids[0];
1962 } else {
Seth Hampson845e8782018-03-02 19:34:101963 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061964 }
1965
Steve Anton4171afb2017-11-20 18:20:221966 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391967 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011968 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211969 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 17:31:531970 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-14 00:26:051971 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391972 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061973 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221974 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011975 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211976 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 17:31:531977 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-14 00:26:051978 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391979 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061980 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221981 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011982 } else {
Mirko Bonadei675513b2017-11-09 10:09:251983 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221984 return nullptr;
deadbeeffac06552015-11-25 19:26:011985 }
Henrik Andreasssoncc189172019-05-20 09:01:381986 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221987
deadbeefe1f9d832016-01-14 23:35:421988 return new_sender;
deadbeeffac06552015-11-25 19:26:011989}
1990
deadbeef70ab1a12015-09-28 23:53:551991std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1992 const {
Karl Wiberga58e1692019-03-26 12:33:431993 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:391994 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 16:29:421995 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 18:20:221996 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391997 }
1998 return ret;
deadbeef70ab1a12015-09-28 23:53:551999}
2000
Steve Anton4171afb2017-11-20 18:20:222001std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2002PeerConnection::GetSendersInternal() const {
2003 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2004 all_senders;
Mirko Bonadei739baf02019-01-27 16:29:422005 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:222006 auto senders = transceiver->internal()->senders();
2007 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
2008 }
2009 return all_senders;
2010}
2011
deadbeef70ab1a12015-09-28 23:53:552012std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
2013PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 12:33:432014 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:392015 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:222016 for (const auto& receiver : GetReceiversInternal()) {
2017 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:392018 }
2019 return ret;
deadbeef70ab1a12015-09-28 23:53:552020}
2021
Steve Anton4171afb2017-11-20 18:20:222022std::vector<
2023 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2024PeerConnection::GetReceiversInternal() const {
2025 std::vector<
2026 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2027 all_receivers;
Mirko Bonadei739baf02019-01-27 16:29:422028 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:222029 auto receivers = transceiver->internal()->receivers();
2030 all_receivers.insert(all_receivers.end(), receivers.begin(),
2031 receivers.end());
2032 }
2033 return all_receivers;
2034}
2035
Steve Anton9158ef62017-11-27 21:01:522036std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2037PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 22:55:092038 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:582039 RTC_CHECK(IsUnifiedPlan())
2040 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:522041 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:422042 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 21:01:522043 all_transceivers.push_back(transceiver);
2044 }
2045 return all_transceivers;
2046}
2047
henrike@webrtc.org28e20752013-07-10 00:45:362048bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:492049 MediaStreamTrackInterface* track,
2050 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:172051 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012052 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 08:57:562053 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252054 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362055 return false;
2056 }
2057
tommi@webrtc.org03505bc2014-07-14 20:15:262058 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:152059 // The StatsCollector is used to tell if a track is valid because it may
2060 // remember tracks that the PeerConnection previously removed.
2061 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:252062 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
2063 << track->id();
zhihuange9e94c32016-11-04 18:38:152064 return false;
2065 }
Steve Antonad182762018-09-05 20:22:402066 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
2067 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:362068 return true;
2069}
2070
hbos74e1a4f2016-09-16 06:33:012071void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:202072 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012073 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-16 06:33:012074 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:202075 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:012076 stats_collector_->GetStatsReport(callback);
2077}
2078
Henrik Boström1df1bf82018-03-20 12:24:202079void PeerConnection::GetStats(
2080 rtc::scoped_refptr<RtpSenderInterface> selector,
2081 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2082 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012083 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:202084 RTC_DCHECK(callback);
2085 RTC_DCHECK(stats_collector_);
2086 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2087 if (selector) {
2088 for (const auto& proxy_transceiver : transceivers_) {
2089 for (const auto& proxy_sender :
2090 proxy_transceiver->internal()->senders()) {
2091 if (proxy_sender == selector) {
2092 internal_sender = proxy_sender->internal();
2093 break;
2094 }
2095 }
2096 if (internal_sender)
2097 break;
2098 }
2099 }
Sebastian Jansson6eb8a162018-11-16 10:29:552100 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:202101 // belong to the PeerConnection (in Plan B, senders can be removed from the
2102 // PeerConnection). This means that "all the stats objects representing the
2103 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2104 // produces an empty stats report.
2105 stats_collector_->GetStatsReport(internal_sender, callback);
2106}
2107
2108void PeerConnection::GetStats(
2109 rtc::scoped_refptr<RtpReceiverInterface> selector,
2110 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2111 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012112 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:202113 RTC_DCHECK(callback);
2114 RTC_DCHECK(stats_collector_);
2115 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2116 if (selector) {
2117 for (const auto& proxy_transceiver : transceivers_) {
2118 for (const auto& proxy_receiver :
2119 proxy_transceiver->internal()->receivers()) {
2120 if (proxy_receiver == selector) {
2121 internal_receiver = proxy_receiver->internal();
2122 break;
2123 }
2124 }
2125 if (internal_receiver)
2126 break;
2127 }
2128 }
Sebastian Jansson6eb8a162018-11-16 10:29:552129 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:202130 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2131 // the PeerConnection). This means that "all the stats objects representing
2132 // the selector" is an empty set. Invoking GetStatsReport() with a null
2133 // selector produces an empty stats report.
2134 stats_collector_->GetStatsReport(internal_receiver, callback);
2135}
2136
henrike@webrtc.org28e20752013-07-10 00:45:362137PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072138 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362139 return signaling_state_;
2140}
2141
henrike@webrtc.org28e20752013-07-10 00:45:362142PeerConnectionInterface::IceConnectionState
2143PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072144 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362145 return ice_connection_state_;
2146}
2147
Alex Loiko9289eda2018-11-23 16:18:592148PeerConnectionInterface::IceConnectionState
2149PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072150 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:592151 return standardized_ice_connection_state_;
2152}
2153
Jonas Olsson635474e2018-10-18 13:58:172154PeerConnectionInterface::PeerConnectionState
2155PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072156 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 13:58:172157 return connection_state_;
2158}
2159
henrike@webrtc.org28e20752013-07-10 00:45:362160PeerConnectionInterface::IceGatheringState
2161PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072162 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362163 return ice_gathering_state_;
2164}
2165
Yves Gerey665174f2018-06-19 13:03:052166rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:362167 const std::string& label,
2168 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 09:17:472169 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:172170 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:502171
deadbeefab9b2d12015-10-14 18:33:112172 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:112173
kwibergd1fe2812016-04-27 13:47:292174 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:582175 if (config) {
2176 internal_config.reset(new InternalDataChannelInit(*config));
2177 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:522178 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:112179 InternalCreateDataChannel(label, internal_config.get()));
2180 if (!channel.get()) {
2181 return nullptr;
2182 }
henrike@webrtc.org28e20752013-07-10 00:45:362183
jiayl@webrtc.org001fd2d2014-05-29 15:31:112184 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2185 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:172186 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 10:24:142187 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:112188 }
Harald Alvestrand8ebba742018-05-31 12:00:342189 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:362190 return DataChannelProxy::Create(signaling_thread(), channel.get());
2191}
2192
Henrik Boström79b69802019-07-18 09:16:562193void PeerConnection::RestartIce() {
2194 RTC_DCHECK_RUN_ON(signaling_thread());
2195 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2196 current_local_description_.get(), pending_local_description_.get());
2197 UpdateNegotiationNeeded();
2198}
2199
henrike@webrtc.org28e20752013-07-10 00:45:362200void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:162201 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 22:55:092202 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492203 // Chain this operation. If asynchronous operations are pending on the chain,
2204 // this operation will be queued to be invoked, otherwise the contents of the
2205 // lambda will execute immediately.
2206 operations_chain_->ChainOperation(
2207 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2208 observer_refptr =
2209 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2210 options](std::function<void()> operations_chain_callback) {
2211 // Abort early if |this_weak_ptr| is no longer valid.
2212 if (!this_weak_ptr) {
2213 observer_refptr->OnFailure(
2214 RTCError(RTCErrorType::INTERNAL_ERROR,
2215 "CreateOffer failed because the session was shut down"));
2216 operations_chain_callback();
2217 return;
2218 }
2219 // The operation completes asynchronously when the wrapper is invoked.
2220 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2221 observer_wrapper(new rtc::RefCountedObject<
2222 CreateSessionDescriptionObserverOperationWrapper>(
2223 std::move(observer_refptr),
2224 std::move(operations_chain_callback)));
2225 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2226 });
2227}
2228
2229void PeerConnection::DoCreateOffer(
2230 const RTCOfferAnswerOptions& options,
2231 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2232 RTC_DCHECK_RUN_ON(signaling_thread());
2233 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 22:30:512234
nisse7ce109a2017-01-31 08:57:562235 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252236 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:162237 return;
2238 }
deadbeefab9b2d12015-10-14 18:33:112239
Steve Anton8d3444d2017-10-20 22:30:512240 if (IsClosed()) {
2241 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:252242 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032243 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102244 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:512245 return;
2246 }
2247
Steve Anton25ca0ac2019-06-25 17:40:482248 // If a session error has occurred the PeerConnection is in a possibly
2249 // inconsistent state so fail right away.
2250 if (session_error() != SessionError::kNone) {
2251 std::string error_message = GetSessionErrorMsg();
2252 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2253 PostCreateSessionDescriptionFailure(
2254 observer,
2255 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2256 return;
2257 }
2258
zhihuang1c378ed2017-08-17 21:10:502259 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:112260 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:252261 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032262 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102263 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:112264 return;
2265 }
2266
Steve Anton22da89f2018-01-25 21:58:072267 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2268 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2269 if (IsUnifiedPlan()) {
2270 RTCError error = HandleLegacyOfferOptions(options);
2271 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:032272 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:072273 return;
2274 }
2275 }
2276
zhihuang1c378ed2017-08-17 21:10:502277 cricket::MediaSessionOptions session_options;
2278 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:292279 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362280}
2281
Steve Anton22da89f2018-01-25 21:58:072282RTCError PeerConnection::HandleLegacyOfferOptions(
2283 const RTCOfferAnswerOptions& options) {
2284 RTC_DCHECK(IsUnifiedPlan());
2285
2286 if (options.offer_to_receive_audio == 0) {
2287 RemoveRecvDirectionFromReceivingTransceiversOfType(
2288 cricket::MEDIA_TYPE_AUDIO);
2289 } else if (options.offer_to_receive_audio == 1) {
2290 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2291 } else if (options.offer_to_receive_audio > 1) {
2292 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2293 "offer_to_receive_audio > 1 is not supported.");
2294 }
2295
2296 if (options.offer_to_receive_video == 0) {
2297 RemoveRecvDirectionFromReceivingTransceiversOfType(
2298 cricket::MEDIA_TYPE_VIDEO);
2299 } else if (options.offer_to_receive_video == 1) {
2300 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2301 } else if (options.offer_to_receive_video > 1) {
2302 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2303 "offer_to_receive_video > 1 is not supported.");
2304 }
2305
2306 return RTCError::OK();
2307}
2308
2309void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2310 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 16:29:422311 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:232312 RtpTransceiverDirection new_direction =
2313 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2314 if (new_direction != transceiver->direction()) {
2315 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2316 << " transceiver (MID="
2317 << transceiver->mid().value_or("<not set>") << ") from "
2318 << RtpTransceiverDirectionToString(
2319 transceiver->direction())
2320 << " to "
2321 << RtpTransceiverDirectionToString(new_direction)
2322 << " since CreateOffer specified offer_to_receive=0";
2323 transceiver->internal()->set_direction(new_direction);
2324 }
Steve Anton22da89f2018-01-25 21:58:072325 }
2326}
2327
2328void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2329 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 09:18:562330 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 21:58:072331 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:232332 RTC_LOG(LS_INFO)
2333 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2334 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:072335 RtpTransceiverInit init;
2336 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 10:24:142337 AddTransceiver(media_type, nullptr, init,
2338 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 21:58:072339 }
2340}
2341
2342std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2343PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2344 std::vector<
2345 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2346 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:422347 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082348 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:072349 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2350 receiving_transceivers.push_back(transceiver);
2351 }
2352 }
2353 return receiving_transceivers;
2354}
2355
htaa2a49d92016-03-04 10:51:392356void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2357 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 12:00:072358 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492359 // Chain this operation. If asynchronous operations are pending on the chain,
2360 // this operation will be queued to be invoked, otherwise the contents of the
2361 // lambda will execute immediately.
2362 operations_chain_->ChainOperation(
2363 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2364 observer_refptr =
2365 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2366 options](std::function<void()> operations_chain_callback) {
2367 // Abort early if |this_weak_ptr| is no longer valid.
2368 if (!this_weak_ptr) {
2369 observer_refptr->OnFailure(RTCError(
2370 RTCErrorType::INTERNAL_ERROR,
2371 "CreateAnswer failed because the session was shut down"));
2372 operations_chain_callback();
2373 return;
2374 }
2375 // The operation completes asynchronously when the wrapper is invoked.
2376 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2377 observer_wrapper(new rtc::RefCountedObject<
2378 CreateSessionDescriptionObserverOperationWrapper>(
2379 std::move(observer_refptr),
2380 std::move(operations_chain_callback)));
2381 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2382 });
2383}
2384
2385void PeerConnection::DoCreateAnswer(
2386 const RTCOfferAnswerOptions& options,
2387 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2388 RTC_DCHECK_RUN_ON(signaling_thread());
2389 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 08:57:562390 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252391 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:392392 return;
2393 }
2394
Steve Anton25ca0ac2019-06-25 17:40:482395 // If a session error has occurred the PeerConnection is in a possibly
2396 // inconsistent state so fail right away.
2397 if (session_error() != SessionError::kNone) {
2398 std::string error_message = GetSessionErrorMsg();
2399 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2400 PostCreateSessionDescriptionFailure(
2401 observer,
2402 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2403 return;
2404 }
2405
Steve Antondffead82018-02-06 18:31:292406 if (!(signaling_state_ == kHaveRemoteOffer ||
2407 signaling_state_ == kHaveLocalPrAnswer)) {
2408 std::string error =
2409 "PeerConnection cannot create an answer in a state other than "
2410 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:252411 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032412 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102413 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:512414 return;
2415 }
2416
Steve Antondffead82018-02-06 18:31:292417 // The remote description should be set if we're in the right state.
2418 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:512419
Steve Anton22da89f2018-01-25 21:58:072420 if (IsUnifiedPlan()) {
2421 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2422 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2423 "supported with Unified Plan semantics. Use the "
2424 "RtpTransceiver API instead.";
2425 }
2426 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2427 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2428 "supported with Unified Plan semantics. Use the "
2429 "RtpTransceiver API instead.";
2430 }
2431 }
2432
htaa2a49d92016-03-04 10:51:392433 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:502434 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:392435
Steve Antond25da372017-11-06 22:50:292436 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362437}
2438
2439void PeerConnection::SetLocalDescription(
2440 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:422441 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 22:55:092442 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492443 // Chain this operation. If asynchronous operations are pending on the chain,
2444 // this operation will be queued to be invoked, otherwise the contents of the
2445 // lambda will execute immediately.
2446 operations_chain_->ChainOperation(
2447 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2448 observer_refptr =
2449 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2450 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2451 std::function<void()> operations_chain_callback) mutable {
2452 // Abort early if |this_weak_ptr| is no longer valid.
2453 if (!this_weak_ptr) {
2454 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2455 // |observer_refptr| that the operation failed in this case.
2456 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2457 // the consistent thing would be to inform the observer here.
2458 operations_chain_callback();
2459 return;
2460 }
2461 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2462 std::move(observer_refptr));
2463 // DoSetLocalDescription() is currently implemented as a synchronous
2464 // operation but where the |observer|'s callbacks are invoked
2465 // asynchronously in a post to OnMessage().
2466 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 09:35:502467 // completed here (rather than in OnMessage()). This ensures that
2468 // subsequent offer/answer operations can start immediately (without
2469 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 11:09:492470 operations_chain_callback();
2471 });
2472}
Steve Anton8a006912017-12-04 23:25:562473
Henrik Boström4e196702019-10-30 09:35:502474void PeerConnection::SetLocalDescription(
2475 SetSessionDescriptionObserver* observer) {
2476 RTC_DCHECK_RUN_ON(signaling_thread());
2477 // The |create_sdp_observer| handles performing DoSetLocalDescription() with
2478 // the resulting description as well as completing the operation.
2479 rtc::scoped_refptr<ImplicitCreateSessionDescriptionObserver>
2480 create_sdp_observer(
2481 new rtc::RefCountedObject<ImplicitCreateSessionDescriptionObserver>(
2482 weak_ptr_factory_.GetWeakPtr(),
2483 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer)));
2484 // Chain this operation. If asynchronous operations are pending on the chain,
2485 // this operation will be queued to be invoked, otherwise the contents of the
2486 // lambda will execute immediately.
2487 operations_chain_->ChainOperation(
2488 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2489 create_sdp_observer](std::function<void()> operations_chain_callback) {
2490 // The |create_sdp_observer| is responsible for completing the
2491 // operation.
2492 create_sdp_observer->SetOperationCompleteCallback(
2493 std::move(operations_chain_callback));
2494 // Abort early if |this_weak_ptr| is no longer valid. This triggers the
2495 // same code path as if DoCreateOffer() or DoCreateAnswer() failed.
2496 if (!this_weak_ptr) {
2497 create_sdp_observer->OnFailure(RTCError(
2498 RTCErrorType::INTERNAL_ERROR,
2499 "SetLocalDescription failed because the session was shut down"));
2500 return;
2501 }
2502 switch (this_weak_ptr->signaling_state()) {
2503 case PeerConnectionInterface::kStable:
2504 case PeerConnectionInterface::kHaveLocalOffer:
2505 case PeerConnectionInterface::kHaveRemotePrAnswer:
2506 // TODO(hbos): If [LastCreatedOffer] exists and still represents the
2507 // current state of the system, use that instead of creating another
2508 // offer.
2509 this_weak_ptr->DoCreateOffer(RTCOfferAnswerOptions(),
2510 create_sdp_observer);
2511 break;
2512 case PeerConnectionInterface::kHaveLocalPrAnswer:
2513 case PeerConnectionInterface::kHaveRemoteOffer:
2514 // TODO(hbos): If [LastCreatedAnswer] exists and still represents
2515 // the current state of the system, use that instead of creating
2516 // another answer.
2517 this_weak_ptr->DoCreateAnswer(RTCOfferAnswerOptions(),
2518 create_sdp_observer);
2519 break;
2520 case PeerConnectionInterface::kClosed:
2521 create_sdp_observer->OnFailure(RTCError(
2522 RTCErrorType::INVALID_STATE,
2523 "SetLocalDescription called when PeerConnection is closed."));
2524 break;
2525 }
2526 });
2527}
2528
Henrik Boströma3728d32019-10-28 11:09:492529void PeerConnection::DoSetLocalDescription(
2530 std::unique_ptr<SessionDescriptionInterface> desc,
2531 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2532 RTC_DCHECK_RUN_ON(signaling_thread());
2533 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-17 01:08:422534
nisse7ce109a2017-01-31 08:57:562535 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252536 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362537 return;
2538 }
Steve Anton8a006912017-12-04 23:25:562539
henrike@webrtc.org28e20752013-07-10 00:45:362540 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:032541 PostSetSessionDescriptionFailure(
2542 observer,
2543 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362544 return;
2545 }
Steve Anton8d3444d2017-10-20 22:30:512546
Steve Anton80dd7b52018-02-17 01:08:422547 // If a session error has occurred the PeerConnection is in a possibly
2548 // inconsistent state so fail right away.
2549 if (session_error() != SessionError::kNone) {
2550 std::string error_message = GetSessionErrorMsg();
2551 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032552 PostSetSessionDescriptionFailure(
2553 observer,
2554 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422555 return;
2556 }
Steve Anton8d3444d2017-10-20 22:30:512557
Eldar Rello5ab79e62019-10-09 15:29:442558 // For SLD we support only explicit rollback.
2559 if (desc->GetType() == SdpType::kRollback) {
2560 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 20:01:312561 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 15:29:442562 if (error.ok()) {
2563 PostSetSessionDescriptionSuccess(observer);
2564 } else {
2565 PostSetSessionDescriptionFailure(observer, std::move(error));
2566 }
2567 } else {
2568 PostSetSessionDescriptionFailure(
2569 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2570 "Rollback not supported in Plan B"));
2571 }
2572 return;
2573 }
2574
Steve Anton80dd7b52018-02-17 01:08:422575 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2576 if (!error.ok()) {
2577 std::string error_message = GetSetDescriptionErrorMessage(
2578 cricket::CS_LOCAL, desc->GetType(), error);
2579 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032580 PostSetSessionDescriptionFailure(
2581 observer,
2582 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422583 return;
2584 }
2585
2586 // Grab the description type before moving ownership to ApplyLocalDescription,
2587 // which may destroy it before returning.
2588 const SdpType type = desc->GetType();
2589
2590 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:562591 // |desc| may be destroyed at this point.
2592
2593 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422594 // If ApplyLocalDescription fails, the PeerConnection could be in an
2595 // inconsistent state, so act conservatively here and set the session error
2596 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2597 SetSessionError(SessionError::kContent, error.message());
2598 std::string error_message =
2599 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2600 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032601 PostSetSessionDescriptionFailure(
2602 observer,
2603 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:512604 return;
2605 }
Steve Anton8a006912017-12-04 23:25:562606 RTC_DCHECK(local_description());
2607
2608 PostSetSessionDescriptionSuccess(observer);
2609
Steve Antonad182762018-09-05 20:22:402610 // MaybeStartGathering needs to be called after posting
2611 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2612 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:562613 transport_controller_->MaybeStartGathering();
2614
Steve Antona3a92c22017-12-07 18:27:412615 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562616 // TODO(deadbeef): We already had to hop to the network thread for
2617 // MaybeStartGathering...
2618 network_thread()->Invoke<void>(
2619 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2620 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302621 // Make UMA notes about what was agreed to.
2622 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562623 }
Guido Urdaneta70c2db12019-04-16 10:24:142624
2625 if (IsUnifiedPlan()) {
2626 bool was_negotiation_needed = is_negotiation_needed_;
2627 UpdateNegotiationNeeded();
2628 if (signaling_state() == kStable && was_negotiation_needed &&
2629 is_negotiation_needed_) {
2630 Observer()->OnRenegotiationNeeded();
2631 }
2632 }
2633
Qingsi Wang1ba5dec2019-08-19 18:57:172634 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 23:25:562635}
2636
2637RTCError PeerConnection::ApplyLocalDescription(
2638 std::unique_ptr<SessionDescriptionInterface> desc) {
2639 RTC_DCHECK_RUN_ON(signaling_thread());
2640 RTC_DCHECK(desc);
2641
henrike@webrtc.org28e20752013-07-10 00:45:362642 // Update stats here so that we have the most recent stats for tracks and
2643 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262644 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562645
Steve Antondcc3c022017-12-23 00:02:542646 // Take a reference to the old local description since it's used below to
2647 // compare against the new local description. When setting the new local
2648 // description, grab ownership of the replaced session description in case it
2649 // is the same as |old_local_description|, to keep it alive for the duration
2650 // of the method.
2651 const SessionDescriptionInterface* old_local_description =
2652 local_description();
2653 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352654 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512655 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542656 replaced_local_description = pending_local_description_
2657 ? std::move(pending_local_description_)
2658 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562659 current_local_description_ = std::move(desc);
2660 pending_local_description_ = nullptr;
2661 current_remote_description_ = std::move(pending_remote_description_);
2662 } else {
Steve Antondcc3c022017-12-23 00:02:542663 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562664 pending_local_description_ = std::move(desc);
2665 }
2666 // The session description to apply now must be accessed by
2667 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442668 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112669
Amit Hilbuche2a284d2019-03-05 20:36:312670 // Report statistics about any use of simulcast.
2671 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2672 *local_description()->description());
2673
Bjorn Mellem175aa2e2018-11-08 19:23:222674 if (!is_caller_) {
2675 if (remote_description()) {
2676 // Remote description was applied first, so this PC is the callee.
2677 is_caller_ = false;
2678 } else {
2679 // Local description is applied first, so this PC is the caller.
2680 is_caller_ = true;
2681 }
2682 }
2683
Zhi Huange830e682018-03-30 17:48:352684 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2685 if (!error.ok()) {
2686 return error;
2687 }
2688
Steve Antondcc3c022017-12-23 00:02:542689 if (IsUnifiedPlan()) {
2690 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482691 cricket::CS_LOCAL, *local_description(), old_local_description,
2692 remote_description());
Steve Anton8a006912017-12-04 23:25:562693 if (!error.ok()) {
2694 return error;
2695 }
Steve Anton0f5400a2018-07-17 21:25:362696 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2697 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:422698 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:402699 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2700 // Note that code paths that don't set MID won't be able to use
2701 // information about DTLS transports.
2702 if (transceiver->mid()) {
2703 auto dtls_transport =
2704 LookupDtlsTransportByMidInternal(*transceiver->mid());
2705 transceiver->internal()->sender_internal()->set_transport(
2706 dtls_transport);
2707 transceiver->internal()->receiver_internal()->set_transport(
2708 dtls_transport);
2709 }
2710
Steve Antondcc3c022017-12-23 00:02:542711 const ContentInfo* content =
2712 FindMediaSectionForTransceiver(transceiver, local_description());
2713 if (!content) {
2714 continue;
2715 }
2716 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362717 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2718 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542719 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362720 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2721 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2722 // "recvonly", process the removal of a remote track for the media
2723 // description, given transceiver, removeList, and muteTracks.
2724 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2725 (transceiver->internal()->fired_direction() &&
2726 RtpTransceiverDirectionHasRecv(
2727 *transceiver->internal()->fired_direction()))) {
2728 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2729 &removed_streams);
2730 }
2731 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2732 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542733 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362734 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542735 }
Steve Anton0f5400a2018-07-17 21:25:362736 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162737 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:422738 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162739 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362740 }
Mirko Bonadei739baf02019-01-27 16:29:422741 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162742 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542743 }
2744 } else {
Zhi Huange830e682018-03-30 17:48:352745 // Media channels will be created only when offer is set. These may use new
2746 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542747 if (type == SdpType::kOffer) {
2748 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2749 // description is applied. Restore back to old description.
2750 RTCError error = CreateChannels(*local_description()->description());
2751 if (!error.ok()) {
2752 return error;
2753 }
2754 }
Steve Antondcc3c022017-12-23 00:02:542755 // Remove unused channels if MediaContentDescription is rejected.
2756 RemoveUnusedChannels(local_description()->description());
2757 }
Steve Anton8a006912017-12-04 23:25:562758
Zhi Huange830e682018-03-30 17:48:352759 error = UpdateSessionState(type, cricket::CS_LOCAL,
2760 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562761 if (!error.ok()) {
2762 return error;
2763 }
Steve Antondcc3c022017-12-23 00:02:542764
Steve Anton8a006912017-12-04 23:25:562765 if (remote_description()) {
2766 // Now that we have a local description, we can push down remote candidates.
2767 UseCandidatesInSessionDescription(remote_description());
2768 }
2769
2770 pending_ice_restarts_.clear();
2771 if (session_error() != SessionError::kNone) {
2772 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2773 }
2774
deadbeefab9b2d12015-10-14 18:33:112775 // If setting the description decided our SSL role, allocate any necessary
2776 // SCTP sids.
2777 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222778 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112779 AllocateSctpSids(role);
2780 }
2781
Steve Antond3679212018-01-18 01:41:022782 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 16:29:422783 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-18 01:41:022784 const ContentInfo* content =
2785 FindMediaSectionForTransceiver(transceiver, local_description());
2786 if (!content) {
2787 continue;
2788 }
Amit Hilbuchbcd39d42019-01-26 01:13:562789 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2790 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 18:32:272791 // 0 is a special value meaning "this sender has no associated send
2792 // stream". Need to call this so the sender won't attempt to configure
2793 // a no longer existing stream and run into DCHECKs in the lower
2794 // layers.
2795 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-26 01:13:562796 } else {
2797 // Get the StreamParams from the channel which could generate SSRCs.
2798 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:382799 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-26 01:13:562800 streams[0].stream_ids());
2801 transceiver->internal()->sender_internal()->SetSsrc(
2802 streams[0].first_ssrc());
Steve Antond3679212018-01-18 01:41:022803 }
2804 }
2805 } else {
2806 // Plan B semantics.
2807
Steve Antondcc3c022017-12-23 00:02:542808 // Update state and SSRC of local MediaStreams and DataChannels based on the
2809 // local session description.
2810 const cricket::ContentInfo* audio_content =
2811 GetFirstAudioContent(local_description()->description());
2812 if (audio_content) {
2813 if (audio_content->rejected) {
2814 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2815 } else {
2816 const cricket::AudioContentDescription* audio_desc =
2817 audio_content->media_description()->as_audio();
2818 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2819 }
deadbeeffaac4972015-11-12 23:33:072820 }
deadbeefab9b2d12015-10-14 18:33:112821
Steve Antondcc3c022017-12-23 00:02:542822 const cricket::ContentInfo* video_content =
2823 GetFirstVideoContent(local_description()->description());
2824 if (video_content) {
2825 if (video_content->rejected) {
2826 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2827 } else {
2828 const cricket::VideoContentDescription* video_desc =
2829 video_content->media_description()->as_video();
2830 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2831 }
deadbeeffaac4972015-11-12 23:33:072832 }
deadbeefab9b2d12015-10-14 18:33:112833 }
2834
2835 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442836 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112837 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 11:36:162838 const cricket::RtpDataContentDescription* rtp_data_desc =
2839 data_content->media_description()->as_rtp_data();
2840 // rtp_data_desc will be null if this is an SCTP description.
2841 if (rtp_data_desc) {
2842 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 18:33:112843 }
2844 }
2845
Henrik Boström79b69802019-07-18 09:16:562846 if (type == SdpType::kAnswer &&
2847 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2848 *current_local_description_)) {
2849 local_ice_credentials_to_replace_->ClearIceCredentials();
2850 }
2851
Steve Anton8a006912017-12-04 23:25:562852 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362853}
2854
Steve Anton06817cd2018-12-18 23:55:302855// The SDP parser used to populate these values by default for the 'content
2856// name' if an a=mid line was absent.
2857static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2858 switch (media_type) {
2859 case cricket::MEDIA_TYPE_AUDIO:
2860 return cricket::CN_AUDIO;
2861 case cricket::MEDIA_TYPE_VIDEO:
2862 return cricket::CN_VIDEO;
2863 case cricket::MEDIA_TYPE_DATA:
2864 return cricket::CN_DATA;
2865 }
2866 RTC_NOTREACHED();
2867 return "";
2868}
2869
2870void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 18:44:532871 cricket::SessionDescription* new_remote_description) {
2872 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 18:35:452873 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 23:55:302874 const cricket::ContentInfos& local_contents =
2875 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:452876 : no_infos);
Steve Antond7180cc2019-02-07 18:44:532877 const cricket::ContentInfos& remote_contents =
2878 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:452879 : no_infos);
Steve Antond7180cc2019-02-07 18:44:532880 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2881 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 23:55:302882 if (!content.name.empty()) {
2883 continue;
2884 }
Amit Hilbuchae3df542019-01-07 20:13:082885 std::string new_mid;
Steve Anton06817cd2018-12-18 23:55:302886 absl::string_view source_explanation;
2887 if (IsUnifiedPlan()) {
2888 if (i < local_contents.size()) {
2889 new_mid = local_contents[i].name;
2890 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 18:44:532891 } else if (i < remote_contents.size()) {
2892 new_mid = remote_contents[i].name;
2893 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 23:55:302894 } else {
Amit Hilbuchae3df542019-01-07 20:13:082895 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 23:55:302896 source_explanation = "generated just now";
2897 }
2898 } else {
Amit Hilbuchae3df542019-01-07 20:13:082899 new_mid = std::string(
2900 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 23:55:302901 source_explanation = "to match pre-existing behavior";
2902 }
Steve Antond7180cc2019-02-07 18:44:532903 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 20:13:082904 content.name = new_mid;
Steve Antond7180cc2019-02-07 18:44:532905 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 23:55:302906 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2907 << " is missing an a=mid line. Filling in the value '"
2908 << new_mid << "' " << source_explanation << ".";
2909 }
2910}
2911
henrike@webrtc.org28e20752013-07-10 00:45:362912void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072913 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 11:09:492914 SessionDescriptionInterface* desc_ptr) {
2915 RTC_DCHECK_RUN_ON(signaling_thread());
2916 // Chain this operation. If asynchronous operations are pending on the chain,
2917 // this operation will be queued to be invoked, otherwise the contents of the
2918 // lambda will execute immediately.
2919 operations_chain_->ChainOperation(
2920 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2921 observer_refptr =
2922 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2923 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2924 std::function<void()> operations_chain_callback) mutable {
2925 // Abort early if |this_weak_ptr| is no longer valid.
2926 if (!this_weak_ptr) {
2927 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2928 // inform the |observer_refptr| that the operation failed in this
2929 // case.
2930 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2931 // the consistent thing would be to inform the observer here.
2932 operations_chain_callback();
2933 return;
2934 }
2935 this_weak_ptr->DoSetRemoteDescription(
2936 std::move(desc),
2937 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2938 new SetRemoteDescriptionObserverAdapter(
2939 this_weak_ptr.get(), std::move(observer_refptr))));
2940 // DoSetRemoteDescription() is currently implemented as a synchronous
2941 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2942 // the |observer|'s callbacks are invoked asynchronously in a post to
2943 // OnMessage().
2944 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 09:35:502945 // completed here (rather than in OnMessage()). This ensures that
2946 // subsequent offer/answer operations can start immediately (without
2947 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 11:09:492948 operations_chain_callback();
2949 });
Henrik Boström31638672017-11-23 16:48:322950}
2951
2952void PeerConnection::SetRemoteDescription(
2953 std::unique_ptr<SessionDescriptionInterface> desc,
2954 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 22:55:092955 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492956 // Chain this operation. If asynchronous operations are pending on the chain,
2957 // this operation will be queued to be invoked, otherwise the contents of the
2958 // lambda will execute immediately.
2959 operations_chain_->ChainOperation(
2960 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2961 desc = std::move(desc)](
2962 std::function<void()> operations_chain_callback) mutable {
2963 // Abort early if |this_weak_ptr| is no longer valid.
2964 if (!this_weak_ptr) {
2965 // For consistency with DoSetRemoteDescription(), we DO inform the
2966 // |observer| that the operation failed in this case.
2967 observer->OnSetRemoteDescriptionComplete(RTCError(
2968 RTCErrorType::INVALID_STATE,
2969 "Failed to set remote offer sdp: failed because the session was "
2970 "shut down"));
2971 operations_chain_callback();
2972 return;
2973 }
2974 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
2975 std::move(observer));
2976 // DoSetRemoteDescription() is currently implemented as a synchronous
2977 // operation. The |observer| will already have been informed that it
2978 // completed, and we can mark this operation as complete without any
2979 // loose ends.
2980 operations_chain_callback();
2981 });
2982}
2983
2984void PeerConnection::DoSetRemoteDescription(
2985 std::unique_ptr<SessionDescriptionInterface> desc,
2986 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
2987 RTC_DCHECK_RUN_ON(signaling_thread());
2988 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562989
nisse7ce109a2017-01-31 08:57:562990 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252991 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362992 return;
2993 }
Steve Anton8a006912017-12-04 23:25:562994
henrike@webrtc.org28e20752013-07-10 00:45:362995 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322996 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562997 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362998 return;
2999 }
Steve Anton8d3444d2017-10-20 22:30:513000
Steve Anton80dd7b52018-02-17 01:08:423001 // If a session error has occurred the PeerConnection is in a possibly
3002 // inconsistent state so fail right away.
3003 if (session_error() != SessionError::kNone) {
3004 std::string error_message = GetSessionErrorMsg();
3005 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
3006 observer->OnSetRemoteDescriptionComplete(
3007 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
3008 return;
3009 }
Eldar Rello5ab79e62019-10-09 15:29:443010 if (IsUnifiedPlan()) {
3011 if (configuration_.enable_implicit_rollback) {
3012 if (desc->GetType() == SdpType::kOffer &&
3013 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 20:01:313014 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 15:29:443015 }
3016 }
3017 // Explicit rollback.
3018 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 20:01:313019 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 15:29:443020 return;
3021 }
3022 } else if (desc->GetType() == SdpType::kRollback) {
3023 observer->OnSetRemoteDescriptionComplete(
3024 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
3025 "Rollback not supported in Plan B"));
3026 return;
3027 }
Steve Antonba42e992018-04-09 21:10:013028 if (desc->GetType() == SdpType::kOffer) {
3029 // Report to UMA the format of the received offer.
3030 ReportSdpFormatReceived(*desc);
3031 }
3032
Steve Anton06817cd2018-12-18 23:55:303033 // Handle remote descriptions missing a=mid lines for interop with legacy end
3034 // points.
3035 FillInMissingRemoteMids(desc->description());
3036
Steve Anton80dd7b52018-02-17 01:08:423037 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:063038 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:423039 std::string error_message = GetSetDescriptionErrorMessage(
3040 cricket::CS_REMOTE, desc->GetType(), error);
3041 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:063042 observer->OnSetRemoteDescriptionComplete(
3043 RTCError(error.type(), std::move(error_message)));
3044 return;
3045 }
Steve Anton71439a62018-02-15 19:53:063046
Steve Anton80dd7b52018-02-17 01:08:423047 // Grab the description type before moving ownership to
3048 // ApplyRemoteDescription, which may destroy it before returning.
3049 const SdpType type = desc->GetType();
3050
3051 error = ApplyRemoteDescription(std::move(desc));
3052 // |desc| may be destroyed at this point.
3053
3054 if (!error.ok()) {
3055 // If ApplyRemoteDescription fails, the PeerConnection could be in an
3056 // inconsistent state, so act conservatively here and set the session error
3057 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
3058 SetSessionError(SessionError::kContent, error.message());
3059 std::string error_message =
3060 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
3061 RTC_LOG(LS_ERROR) << error_message;
3062 observer->OnSetRemoteDescriptionComplete(
3063 RTCError(error.type(), std::move(error_message)));
3064 return;
3065 }
3066 RTC_DCHECK(remote_description());
3067
3068 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:563069 // TODO(deadbeef): We already had to hop to the network thread for
3070 // MaybeStartGathering...
3071 network_thread()->Invoke<void>(
3072 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3073 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:003074 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:303075 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:563076 }
3077
Guido Urdaneta70c2db12019-04-16 10:24:143078 if (IsUnifiedPlan()) {
3079 bool was_negotiation_needed = is_negotiation_needed_;
3080 UpdateNegotiationNeeded();
3081 if (signaling_state() == kStable && was_negotiation_needed &&
3082 is_negotiation_needed_) {
3083 Observer()->OnRenegotiationNeeded();
3084 }
3085 }
3086
Steve Anton8a006912017-12-04 23:25:563087 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 18:57:173088 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 23:25:563089}
3090
3091RTCError PeerConnection::ApplyRemoteDescription(
3092 std::unique_ptr<SessionDescriptionInterface> desc) {
3093 RTC_DCHECK_RUN_ON(signaling_thread());
3094 RTC_DCHECK(desc);
3095
henrike@webrtc.org28e20752013-07-10 00:45:363096 // Update stats here so that we have the most recent stats for tracks and
3097 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:263098 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:563099
Steve Antondcc3c022017-12-23 00:02:543100 // Take a reference to the old remote description since it's used below to
3101 // compare against the new remote description. When setting the new remote
3102 // description, grab ownership of the replaced session description in case it
3103 // is the same as |old_remote_description|, to keep it alive for the duration
3104 // of the method.
Steve Anton8a006912017-12-04 23:25:563105 const SessionDescriptionInterface* old_remote_description =
3106 remote_description();
Steve Anton8a006912017-12-04 23:25:563107 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:513108 SdpType type = desc->GetType();
3109 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:563110 replaced_remote_description = pending_remote_description_
3111 ? std::move(pending_remote_description_)
3112 : std::move(current_remote_description_);
3113 current_remote_description_ = std::move(desc);
3114 pending_remote_description_ = nullptr;
3115 current_local_description_ = std::move(pending_local_description_);
3116 } else {
3117 replaced_remote_description = std::move(pending_remote_description_);
3118 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:363119 }
Steve Anton8a006912017-12-04 23:25:563120 // The session description to apply now must be accessed by
3121 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:443122 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:363123
Amit Hilbuche2a284d2019-03-05 20:36:313124 // Report statistics about any use of simulcast.
3125 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
3126 *remote_description()->description());
3127
Zhi Huange830e682018-03-30 17:48:353128 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
3129 if (!error.ok()) {
3130 return error;
3131 }
Steve Anton8a006912017-12-04 23:25:563132 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:543133 if (IsUnifiedPlan()) {
3134 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:483135 cricket::CS_REMOTE, *remote_description(), local_description(),
3136 old_remote_description);
Steve Anton8a006912017-12-04 23:25:563137 if (!error.ok()) {
3138 return error;
3139 }
Steve Antondcc3c022017-12-23 00:02:543140 } else {
Zhi Huange830e682018-03-30 17:48:353141 // Media channels will be created only when offer is set. These may use new
3142 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:543143 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:353144 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:543145 // description is applied. Restore back to old description.
3146 RTCError error = CreateChannels(*remote_description()->description());
3147 if (!error.ok()) {
3148 return error;
3149 }
3150 }
Steve Antondcc3c022017-12-23 00:02:543151 // Remove unused channels if MediaContentDescription is rejected.
3152 RemoveUnusedChannels(remote_description()->description());
3153 }
Steve Anton8a006912017-12-04 23:25:563154
Zhi Huange830e682018-03-30 17:48:353155 // NOTE: Candidates allocation will be initiated only when
3156 // SetLocalDescription is called.
3157 error = UpdateSessionState(type, cricket::CS_REMOTE,
3158 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:563159 if (!error.ok()) {
3160 return error;
3161 }
3162
3163 if (local_description() &&
3164 !UseCandidatesInSessionDescription(remote_description())) {
3165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3166 }
3167
3168 if (old_remote_description) {
3169 for (const cricket::ContentInfo& content :
3170 old_remote_description->description()->contents()) {
3171 // Check if this new SessionDescription contains new ICE ufrag and
3172 // password that indicates the remote peer requests an ICE restart.
3173 // TODO(deadbeef): When we start storing both the current and pending
3174 // remote description, this should reset pending_ice_restarts and compare
3175 // against the current description.
3176 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3177 content.name)) {
Steve Anton3828c062017-12-06 18:34:513178 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:563179 pending_ice_restarts_.insert(content.name);
3180 }
3181 } else {
3182 // We retain all received candidates only if ICE is not restarted.
3183 // When ICE is restarted, all previous candidates belong to an old
3184 // generation and should not be kept.
3185 // TODO(deadbeef): This goes against the W3C spec which says the remote
3186 // description should only contain candidates from the last set remote
3187 // description plus any candidates added since then. We should remove
3188 // this once we're sure it won't break anything.
3189 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3190 old_remote_description, content.name, mutable_remote_description());
3191 }
3192 }
3193 }
3194
3195 if (session_error() != SessionError::kNone) {
3196 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3197 }
3198
3199 // Set the the ICE connection state to connecting since the connection may
3200 // become writable with peer reflexive candidates before any remote candidate
3201 // is signaled.
3202 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3203 // is to have a new signal the indicates a change in checking state from the
3204 // transport and expose a new checking() member from transport that can be
3205 // read to determine the current checking state. The existing SignalConnecting
3206 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:413207 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:173208 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:563209 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3210 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3211 }
3212
deadbeefab9b2d12015-10-14 18:33:113213 // If setting the description decided our SSL role, allocate any necessary
3214 // SCTP sids.
3215 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:223216 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:113217 AllocateSctpSids(role);
3218 }
3219
Steve Antondcc3c022017-12-23 00:02:543220 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:423221 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:183222 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:363223 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:133224 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:183225 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:423226 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:543227 const ContentInfo* content =
3228 FindMediaSectionForTransceiver(transceiver, remote_description());
3229 if (!content) {
3230 continue;
3231 }
3232 const MediaContentDescription* media_desc = content->media_description();
3233 RtpTransceiverDirection local_direction =
3234 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 10:06:023235 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3236 // RTCSessionDescription: Set the associated remote streams given
3237 // transceiver.[[Receiver]], msids, addList, and removeList".
3238 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3239 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3240 std::vector<std::string> stream_ids;
3241 if (!media_desc->streams().empty()) {
3242 // The remote description has signaled the stream IDs.
3243 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-11 01:15:203244 }
Henrik Boströmafa07dd2018-12-20 10:06:023245 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3246 << " (" << GetStreamIdsString(stream_ids) << ").";
3247 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3248 stream_ids, &added_streams,
3249 &removed_streams);
3250 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3251 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3252 // and transceiver's current direction is neither sendrecv nor recvonly,
3253 // process the addition of a remote track for the media description.
3254 if (!transceiver->fired_direction() ||
3255 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3256 RTC_LOG(LS_INFO)
3257 << "Processing the addition of a remote track for MID="
3258 << content->name << ".";
3259 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 10:25:053260 }
Steve Antondcc3c022017-12-23 00:02:543261 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403262 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 21:25:363263 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3264 // removal of a remote track for the media description, given transceiver,
3265 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:543266 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:363267 (transceiver->fired_direction() &&
3268 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3269 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3270 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:543271 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403272 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 21:25:363273 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:403274 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 21:25:363275 // the following steps:
Steve Antondcc3c022017-12-23 00:02:543276 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:403277 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 21:25:363278 // direction.
Steve Antondcc3c022017-12-23 00:02:543279 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:403280 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3281 if (transceiver->mid()) {
3282 auto dtls_transport =
3283 LookupDtlsTransportByMidInternal(*transceiver->mid());
3284 transceiver->internal()->sender_internal()->set_transport(
3285 dtls_transport);
3286 transceiver->internal()->receiver_internal()->set_transport(
3287 dtls_transport);
3288 }
Steve Antondcc3c022017-12-23 00:02:543289 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403290 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 21:25:363291 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:543292 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:233293 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3294 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:543295 transceiver->Stop();
3296 }
Seth Hampson2f0d7022018-02-20 19:54:423297 if (!content->rejected &&
3298 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 18:16:333299 if (!media_desc->streams().empty() &&
3300 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 23:23:053301 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3302 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3303 } else {
3304 transceiver->internal()
3305 ->receiver_internal()
3306 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 19:54:423307 }
Steve Antond3679212018-01-18 01:41:023308 }
Steve Antondcc3c022017-12-23 00:02:543309 }
Steve Antonc49bcd92018-02-14 22:28:133310 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:163311 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:423312 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:163313 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:163314 observer->OnTrack(transceiver);
3315 observer->OnAddTrack(transceiver->receiver(),
3316 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:203317 }
Mirko Bonadei739baf02019-01-27 16:29:423318 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163319 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:133320 }
Mirko Bonadei739baf02019-01-27 16:29:423321 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163322 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:183323 }
Mirko Bonadei739baf02019-01-27 16:29:423324 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163325 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:183326 }
Steve Antondcc3c022017-12-23 00:02:543327 }
3328
Henrik Boströmfdb92012017-11-09 18:55:443329 const cricket::ContentInfo* audio_content =
3330 GetFirstAudioContent(remote_description()->description());
3331 const cricket::ContentInfo* video_content =
3332 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403333 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:443334 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403335 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:443336 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 11:36:163337 const cricket::RtpDataContentDescription* rtp_data_desc =
3338 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403339
3340 // Check if the descriptions include streams, just in case the peer supports
3341 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:443342 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:403343 (audio_desc && !audio_desc->streams().empty()) ||
3344 (video_desc && !video_desc->streams().empty())) {
3345 remote_peer_supports_msid_ = true;
3346 }
deadbeefab9b2d12015-10-14 18:33:113347
3348 // We wait to signal new streams until we finish processing the description,
3349 // since only at that point will new streams have all their tracks.
3350 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3351
Steve Antondcc3c022017-12-23 00:02:543352 if (!IsUnifiedPlan()) {
3353 // TODO(steveanton): When removing RTP senders/receivers in response to a
3354 // rejected media section, there is some cleanup logic that expects the
3355 // voice/ video channel to still be set. But in this method the voice/video
3356 // channel would have been destroyed by the SetRemoteDescription caller
3357 // above so the cleanup that relies on them fails to run. The RemoveSenders
3358 // calls should be moved to right before the DestroyChannel calls to fix
3359 // this.
Steve Anton8d3444d2017-10-20 22:30:513360
Steve Antondcc3c022017-12-23 00:02:543361 // Find all audio rtp streams and create corresponding remote AudioTracks
3362 // and MediaStreams.
3363 if (audio_content) {
3364 if (audio_content->rejected) {
3365 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3366 } else {
3367 bool default_audio_track_needed =
3368 !remote_peer_supports_msid_ &&
3369 RtpTransceiverDirectionHasSend(audio_desc->direction());
3370 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3371 default_audio_track_needed, audio_desc->type(),
3372 new_streams);
3373 }
deadbeeffaac4972015-11-12 23:33:073374 }
deadbeefab9b2d12015-10-14 18:33:113375
Steve Antondcc3c022017-12-23 00:02:543376 // Find all video rtp streams and create corresponding remote VideoTracks
3377 // and MediaStreams.
3378 if (video_content) {
3379 if (video_content->rejected) {
3380 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3381 } else {
3382 bool default_video_track_needed =
3383 !remote_peer_supports_msid_ &&
3384 RtpTransceiverDirectionHasSend(video_desc->direction());
3385 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3386 default_video_track_needed, video_desc->type(),
3387 new_streams);
3388 }
deadbeeffaac4972015-11-12 23:33:073389 }
deadbeefab9b2d12015-10-14 18:33:113390
Harald Alvestrand5fc28b12019-05-13 11:36:163391 // If this is an RTP data transport, update the DataChannels with the
3392 // information from the remote peer.
3393 if (rtp_data_desc) {
3394 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 18:33:113395 }
deadbeefab9b2d12015-10-14 18:33:113396
Steve Antondcc3c022017-12-23 00:02:543397 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:163398 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:543399 for (size_t i = 0; i < new_streams->count(); ++i) {
3400 MediaStreamInterface* new_stream = new_streams->at(i);
3401 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163402 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:543403 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3404 }
deadbeefab9b2d12015-10-14 18:33:113405
Steve Antondcc3c022017-12-23 00:02:543406 UpdateEndedRemoteMediaStreams();
3407 }
deadbeefab9b2d12015-10-14 18:33:113408
Henrik Boström79b69802019-07-18 09:16:563409 if (type == SdpType::kAnswer &&
3410 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3411 *current_local_description_)) {
3412 local_ice_credentials_to_replace_->ClearIceCredentials();
3413 }
3414
Steve Anton8a006912017-12-04 23:25:563415 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:333416}
3417
Henrik Boströmafa07dd2018-12-20 10:06:023418void PeerConnection::SetAssociatedRemoteStreams(
3419 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3420 const std::vector<std::string>& stream_ids,
3421 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3422 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3423 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3424 for (const std::string& stream_id : stream_ids) {
3425 rtc::scoped_refptr<MediaStreamInterface> stream =
3426 remote_streams_->find(stream_id);
3427 if (!stream) {
3428 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3429 MediaStream::Create(stream_id));
3430 remote_streams_->AddStream(stream);
3431 added_streams->push_back(stream);
3432 }
3433 media_streams.push_back(stream);
3434 }
3435 // Special case: "a=msid" missing, use random stream ID.
3436 if (media_streams.empty() &&
3437 !(remote_description()->description()->msid_signaling() &
3438 cricket::kMsidSignalingMediaSection)) {
3439 if (!missing_msid_default_stream_) {
3440 missing_msid_default_stream_ = MediaStreamProxy::Create(
3441 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3442 added_streams->push_back(missing_msid_default_stream_);
3443 }
3444 media_streams.push_back(missing_msid_default_stream_);
3445 }
3446 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3447 receiver->streams();
3448 // SetStreams() will add/remove the receiver's track to/from the streams. This
3449 // differs from the spec - the spec uses an "addList" and "removeList" to
3450 // update the stream-track relationships in a later step. We do this earlier,
3451 // changing the order of things, but the end-result is the same.
3452 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3453 // instead. https://crbug.com/webrtc/9480
3454 receiver->SetStreams(media_streams);
3455 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3456}
3457
Steve Anton0f5400a2018-07-17 21:25:363458void PeerConnection::ProcessRemovalOfRemoteTrack(
3459 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3460 transceiver,
3461 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3462 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3463 RTC_DCHECK(transceiver->mid());
3464 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3465 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 10:06:023466 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 21:25:363467 transceiver->internal()->receiver_internal()->streams();
3468 // This will remove the remote track from the streams.
3469 transceiver->internal()->receiver_internal()->set_stream_ids({});
3470 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 10:06:023471 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3472}
3473
3474void PeerConnection::RemoveRemoteStreamsIfEmpty(
3475 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3476 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3477 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3478 // streams, see if the stream was removed by checking if this was the last
3479 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 16:29:423480 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 10:06:023481 if (remote_stream->GetAudioTracks().empty() &&
3482 remote_stream->GetVideoTracks().empty()) {
3483 remote_streams_->RemoveStream(remote_stream);
3484 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 21:25:363485 }
3486 }
3487}
3488
Steve Antondcc3c022017-12-23 00:02:543489RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3490 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:483491 const SessionDescriptionInterface& new_session,
3492 const SessionDescriptionInterface* old_local_description,
3493 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:543494 RTC_DCHECK(IsUnifiedPlan());
3495
Steve Anton7464fca2018-01-19 19:10:373496 const cricket::ContentGroup* bundle_group = nullptr;
3497 if (new_session.GetType() == SdpType::kOffer) {
3498 auto bundle_group_or_error =
3499 GetEarlyBundleGroup(*new_session.description());
3500 if (!bundle_group_or_error.ok()) {
3501 return bundle_group_or_error.MoveError();
3502 }
3503 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:543504 }
Steve Antondcc3c022017-12-23 00:02:543505
Steve Antondcc3c022017-12-23 00:02:543506 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:543507 for (size_t i = 0; i < new_contents.size(); ++i) {
3508 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:543509 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 20:13:083510 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-23 00:02:543511 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3512 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:483513 const cricket::ContentInfo* old_local_content = nullptr;
3514 if (old_local_description &&
3515 i < old_local_description->description()->contents().size()) {
3516 old_local_content =
3517 &old_local_description->description()->contents()[i];
3518 }
3519 const cricket::ContentInfo* old_remote_content = nullptr;
3520 if (old_remote_description &&
3521 i < old_remote_description->description()->contents().size()) {
3522 old_remote_content =
3523 &old_remote_description->description()->contents()[i];
3524 }
Steve Antondcc3c022017-12-23 00:02:543525 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:483526 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3527 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:543528 if (!transceiver_or_error.ok()) {
3529 return transceiver_or_error.MoveError();
3530 }
3531 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:543532 RTCError error =
3533 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3534 if (!error.ok()) {
3535 return error;
3536 }
3537 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:233538 if (GetDataMid() && new_content.name != *GetDataMid()) {
3539 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:233540 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3541 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:233542 continue;
3543 }
3544 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3545 if (!error.ok()) {
3546 return error;
3547 }
Steve Antondcc3c022017-12-23 00:02:543548 } else {
3549 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3550 "Unknown section type.");
3551 }
3552 }
3553
3554 return RTCError::OK();
3555}
3556
3557RTCError PeerConnection::UpdateTransceiverChannel(
3558 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3559 transceiver,
3560 const cricket::ContentInfo& content,
3561 const cricket::ContentGroup* bundle_group) {
3562 RTC_DCHECK(IsUnifiedPlan());
3563 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-14 00:26:053564 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:543565 if (content.rejected) {
3566 if (channel) {
3567 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:053568 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:543569 }
3570 } else {
3571 if (!channel) {
Steve Anton69470252018-02-09 19:43:083572 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:353573 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543574 } else {
Steve Anton69470252018-02-09 19:43:083575 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:353576 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543577 }
3578 if (!channel) {
3579 LOG_AND_RETURN_ERROR(
3580 RTCErrorType::INTERNAL_ERROR,
3581 "Failed to create channel for mid=" + content.name);
3582 }
3583 transceiver->internal()->SetChannel(channel);
3584 }
3585 }
3586 return RTCError::OK();
3587}
3588
Steve Antonfa2260d2017-12-29 00:38:233589RTCError PeerConnection::UpdateDataChannel(
3590 cricket::ContentSource source,
3591 const cricket::ContentInfo& content,
3592 const cricket::ContentGroup* bundle_group) {
3593 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:403594 // If data channels are disabled, ignore this media section. CreateAnswer
3595 // will take care of rejecting it.
3596 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:233597 }
3598 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 17:44:593599 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Harald Alvestrand408cb4b2019-11-16 11:09:083600 DestroyDataChannelTransport();
Steve Antonfa2260d2017-12-29 00:38:233601 } else {
Bjorn A Mellembc3eebc2019-09-23 21:53:543602 if (!rtp_data_channel_ && !data_channel_transport_) {
Bjorn A Mellemb689af42019-08-21 17:44:593603 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 17:48:353604 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:233605 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3606 "Failed to create data channel.");
3607 }
3608 }
3609 if (source == cricket::CS_REMOTE) {
3610 const MediaContentDescription* data_desc = content.media_description();
3611 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3612 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3613 }
3614 }
3615 }
3616 return RTCError::OK();
3617}
3618
Amit Hilbuchbcd39d42019-01-26 01:13:563619// This method will extract any send encodings that were sent by the remote
3620// connection. This is currently only relevant for Simulcast scenario (where
3621// the number of layers may be communicated by the server).
3622static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3623 const MediaContentDescription& desc) {
3624 if (!desc.HasSimulcast()) {
3625 return {};
3626 }
3627 std::vector<RtpEncodingParameters> result;
3628 const SimulcastDescription& simulcast = desc.simulcast_description();
3629
3630 // This is a remote description, the parameters we are after should appear
3631 // as receive streams.
3632 for (const auto& alternatives : simulcast.receive_layers()) {
3633 RTC_DCHECK(!alternatives.empty());
3634 // There is currently no way to specify or choose from alternatives.
3635 // We will always use the first alternative, which is the most preferred.
3636 const SimulcastLayer& layer = alternatives[0];
3637 RtpEncodingParameters parameters;
3638 parameters.rid = layer.rid;
3639 parameters.active = !layer.is_paused;
3640 result.push_back(parameters);
3641 }
3642
3643 return result;
3644}
3645
3646static RTCError UpdateSimulcastLayerStatusInSender(
3647 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 20:49:223648 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563649 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193650 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223651 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:563652
3653 // The simulcast envelope cannot be changed, only the status of the streams.
3654 // So we will iterate over the send encodings rather than the layers.
3655 for (RtpEncodingParameters& encoding : parameters.encodings) {
3656 auto iter = std::find_if(layers.begin(), layers.end(),
3657 [&encoding](const SimulcastLayer& layer) {
3658 return layer.rid == encoding.rid;
3659 });
3660 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 20:49:223661 if (iter == layers.end()) {
3662 disabled_layers.push_back(encoding.rid);
3663 continue;
3664 }
3665
3666 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-26 01:13:563667 }
3668
Amit Hilbuch619b2942019-02-26 23:55:193669 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 20:49:223670 if (result.ok()) {
3671 result = sender->DisableEncodingLayers(disabled_layers);
3672 }
3673
3674 return result;
Amit Hilbuchbcd39d42019-01-26 01:13:563675}
3676
Amit Hilbuchaabd0362019-03-01 21:14:463677static bool SimulcastIsRejected(
3678 const ContentInfo* local_content,
3679 const MediaContentDescription& answer_media_desc) {
3680 bool simulcast_offered = local_content &&
3681 local_content->media_description() &&
3682 local_content->media_description()->HasSimulcast();
3683 bool simulcast_answered = answer_media_desc.HasSimulcast();
3684 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3685 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3686 return simulcast_offered && (!simulcast_answered || !rids_supported);
3687}
3688
Amit Hilbuch2297d332019-02-19 20:49:223689static RTCError DisableSimulcastInSender(
3690 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563691 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193692 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223693 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-26 01:13:563694 return RTCError::OK();
3695 }
3696
Amit Hilbuch2297d332019-02-19 20:49:223697 std::vector<std::string> disabled_layers;
3698 std::transform(
3699 parameters.encodings.begin() + 1, parameters.encodings.end(),
3700 std::back_inserter(disabled_layers),
3701 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3702 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-26 01:13:563703}
3704
Steve Antondcc3c022017-12-23 00:02:543705RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3706PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:483707 SdpType type,
Steve Antondcc3c022017-12-23 00:02:543708 size_t mline_index,
3709 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:483710 const ContentInfo* old_local_content,
3711 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:543712 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:483713 // If this is an offer then the m= section might be recycled. If the m=
3714 // section is being recycled (defined as: rejected in the current local or
3715 // remote description and not rejected in new description), dissociate the
3716 // currently associated RtpTransceiver by setting its mid property to null,
3717 // and discard the mapping between the transceiver and its m= section index.
3718 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3719 old_remote_content)) {
3720 // We want to dissociate the transceiver that has the rejected mid.
3721 const std::string& old_mid =
3722 (old_local_content && old_local_content->rejected)
3723 ? old_local_content->name
3724 : old_remote_content->name;
3725 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:543726 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:233727 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3728 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:433729 old_transceiver->internal()->set_mid(absl::nullopt);
3730 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:543731 }
3732 }
3733 const MediaContentDescription* media_desc = content.media_description();
3734 auto transceiver = GetAssociatedTransceiver(content.name);
3735 if (source == cricket::CS_LOCAL) {
3736 // Find the RtpTransceiver that corresponds to this m= section, using the
3737 // mapping between transceivers and m= section indices established when
3738 // creating the offer.
3739 if (!transceiver) {
3740 transceiver = GetTransceiverByMLineIndex(mline_index);
3741 }
3742 if (!transceiver) {
3743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3744 "Unknown transceiver");
3745 }
3746 } else {
3747 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3748 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3749 // of the same type...
Amit Hilbuchaa584152019-02-07 01:09:523750 // When simulcast is requested, a transceiver cannot be associated because
3751 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-23 00:02:543752 if (!transceiver &&
Amit Hilbuchaa584152019-02-07 01:09:523753 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3754 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-23 00:02:543755 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3756 }
3757 // If no RtpTransceiver was found in the previous step, create one with a
3758 // recvonly direction.
3759 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:233760 RTC_LOG(LS_INFO) << "Adding "
3761 << cricket::MediaTypeToString(media_desc->type())
3762 << " transceiver for MID=" << content.name
3763 << " at i=" << mline_index
3764 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:363765 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-26 01:13:563766 std::vector<RtpEncodingParameters> send_encodings =
3767 GetSendEncodingsFromRemoteDescription(*media_desc);
3768 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3769 send_encodings);
Steve Anton5f94aa22018-02-01 18:58:303770 std::string receiver_id;
3771 if (!media_desc->streams().empty()) {
3772 receiver_id = media_desc->streams()[0].id;
3773 } else {
3774 receiver_id = rtc::CreateRandomUuid();
3775 }
3776 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:063777 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:543778 transceiver->internal()->set_direction(
3779 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 15:29:443780 if (type == SdpType::kOffer) {
3781 transceiver_stable_states_by_transceivers_[transceiver] =
3782 TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
3783 absl::nullopt, absl::nullopt, true);
3784 }
Steve Antondcc3c022017-12-23 00:02:543785 }
Amit Hilbuchbcd39d42019-01-26 01:13:563786 // Check if the offer indicated simulcast but the answer rejected it.
3787 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 21:14:463788 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 20:36:313789 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-26 01:13:563790 RTCError error =
Amit Hilbuch2297d332019-02-19 20:49:223791 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563792 if (!error.ok()) {
3793 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3794 return std::move(error);
3795 }
3796 }
Steve Antondcc3c022017-12-23 00:02:543797 }
3798 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:083799 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:543800 LOG_AND_RETURN_ERROR(
3801 RTCErrorType::INVALID_PARAMETER,
3802 "Transceiver type does not match media description type.");
3803 }
Amit Hilbuchbcd39d42019-01-26 01:13:563804 if (media_desc->HasSimulcast()) {
3805 std::vector<SimulcastLayer> layers =
3806 source == cricket::CS_LOCAL
3807 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3808 : media_desc->simulcast_description()
3809 .receive_layers()
3810 .GetAllLayers();
3811 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 20:49:223812 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563813 if (!error.ok()) {
3814 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3815 return std::move(error);
3816 }
3817 }
Eldar Rello5ab79e62019-10-09 15:29:443818 if (type == SdpType::kOffer) {
3819 // Make sure we don't overwrite existing stable states and that the
3820 // state is really going to change when adding new record to the map.
3821 auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
3822 if (it == transceiver_stable_states_by_transceivers_.end() &&
3823 (transceiver->internal()->mid() != content.name ||
3824 transceiver->internal()->mline_index() != mline_index)) {
3825 transceiver_stable_states_by_transceivers_[transceiver] =
3826 TransceiverStableState(transceiver->internal()->direction(),
3827 transceiver->internal()->mid(),
3828 transceiver->internal()->mline_index(), false);
3829 }
3830 }
3831
Steve Antondcc3c022017-12-23 00:02:543832 // Associate the found or created RtpTransceiver with the m= section by
3833 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3834 // section, and establish a mapping between the transceiver and the index of
3835 // the m= section.
3836 transceiver->internal()->set_mid(content.name);
3837 transceiver->internal()->set_mline_index(mline_index);
3838 return std::move(transceiver);
3839}
3840
3841rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3842PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3843 RTC_DCHECK(IsUnifiedPlan());
3844 for (auto transceiver : transceivers_) {
3845 if (transceiver->mid() == mid) {
3846 return transceiver;
3847 }
3848 }
3849 return nullptr;
3850}
3851
3852rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3853PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3854 RTC_DCHECK(IsUnifiedPlan());
3855 for (auto transceiver : transceivers_) {
3856 if (transceiver->internal()->mline_index() == mline_index) {
3857 return transceiver;
3858 }
3859 }
3860 return nullptr;
3861}
3862
3863rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3864PeerConnection::FindAvailableTransceiverToReceive(
3865 cricket::MediaType media_type) const {
3866 RTC_DCHECK(IsUnifiedPlan());
3867 // From JSEP section 5.10 (Applying a Remote Description):
3868 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3869 // the same type that were added to the PeerConnection by addTrack and are not
3870 // associated with any m= section and are not stopped, find the first such
3871 // RtpTransceiver.
3872 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:083873 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:543874 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3875 !transceiver->stopped()) {
3876 return transceiver;
3877 }
3878 }
3879 return nullptr;
3880}
3881
Steve Antoned10bd92017-12-05 18:52:593882const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3883 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3884 transceiver,
3885 const SessionDescriptionInterface* sdesc) const {
3886 RTC_DCHECK(transceiver);
3887 RTC_DCHECK(sdesc);
3888 if (IsUnifiedPlan()) {
3889 if (!transceiver->internal()->mid()) {
3890 // This transceiver is not associated with a media section yet.
3891 return nullptr;
3892 }
3893 return sdesc->description()->GetContentByName(
3894 *transceiver->internal()->mid());
3895 } else {
3896 // Plan B only allows at most one audio and one video section, so use the
3897 // first media section of that type.
3898 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:083899 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:593900 }
3901}
3902
deadbeef46c73892016-11-17 03:42:043903PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 22:55:093904 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-17 03:42:043905 return configuration_;
3906}
3907
Niels Möller2579f0c2019-08-19 07:58:173908RTCError PeerConnection::SetConfiguration(
3909 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 22:55:093910 RTC_DCHECK_RUN_ON(signaling_thread());
3911 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 21:15:173912 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:103913 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 07:58:173914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3915 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 16:54:103916 }
3917
Qingsi Wanga2d60672018-04-11 23:57:453918 // According to JSEP, after setLocalDescription, changing the candidate pool
3919 // size is not allowed, and changing the set of ICE servers will not result
3920 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:173921 if (local_description() && configuration.ice_candidate_pool_size !=
3922 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 07:58:173923 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3924 "Can't change candidate pool size after calling "
3925 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:453926 }
Taylor Brandstettera1c30352016-05-13 15:15:113927
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453928 if (local_description() &&
3929 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 07:58:173930 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3931 "Can't change media_transport after calling "
3932 "SetLocalDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453933 }
3934
3935 if (remote_description() &&
3936 configuration.use_media_transport != configuration_.use_media_transport) {
Niels Möller2579f0c2019-08-19 07:58:173937 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3938 "Can't change media_transport after calling "
3939 "SetRemoteDescription.");
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453940 }
3941
Benjamin Wright8c27cca2018-10-25 17:16:443942 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 16:07:483943 configuration.use_media_transport_for_data_channels !=
3944 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 07:58:173945 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3946 "Can't change media_transport_for_data_channels "
3947 "after calling SetLocalDescription.");
Bjorn Mellema9bbd862018-11-02 16:07:483948 }
3949
3950 if (remote_description() &&
3951 configuration.use_media_transport_for_data_channels !=
3952 configuration_.use_media_transport_for_data_channels) {
Niels Möller2579f0c2019-08-19 07:58:173953 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3954 "Can't change media_transport_for_data_channels "
3955 "after calling SetRemoteDescription.");
Bjorn Mellema9bbd862018-11-02 16:07:483956 }
3957
3958 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 17:16:443959 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 07:58:173960 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3961 "Can't change crypto_options after calling "
3962 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 17:16:443963 }
3964
Anton Sukhanov316f3ac2019-05-23 22:50:383965 if (local_description() && configuration.use_datagram_transport !=
3966 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 07:58:173967 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3968 "Can't change use_datagram_transport "
3969 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 22:50:383970 }
3971
3972 if (remote_description() && configuration.use_datagram_transport !=
3973 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 07:58:173974 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3975 "Can't change use_datagram_transport "
3976 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 22:50:383977 }
3978
Bjorn A Mellemb689af42019-08-21 17:44:593979 if (local_description() &&
3980 configuration.use_datagram_transport_for_data_channels !=
3981 configuration_.use_datagram_transport_for_data_channels) {
3982 LOG_AND_RETURN_ERROR(
3983 RTCErrorType::INVALID_MODIFICATION,
3984 "Can't change use_datagram_transport_for_data_channels "
3985 "after calling SetLocalDescription.");
3986 }
3987
3988 if (remote_description() &&
3989 configuration.use_datagram_transport_for_data_channels !=
3990 configuration_.use_datagram_transport_for_data_channels) {
3991 LOG_AND_RETURN_ERROR(
3992 RTCErrorType::INVALID_MODIFICATION,
3993 "Can't change use_datagram_transport_for_data_channels "
3994 "after calling SetRemoteDescription.");
3995 }
3996
Bjorn A Mellem7da4e562019-09-26 18:02:113997 if (local_description() &&
3998 configuration.use_datagram_transport_for_data_channels_receive_only !=
3999 configuration_
4000 .use_datagram_transport_for_data_channels_receive_only) {
4001 LOG_AND_RETURN_ERROR(
4002 RTCErrorType::INVALID_MODIFICATION,
4003 "Can't change use_datagram_transport_for_data_channels_receive_only "
4004 "after calling SetLocalDescription.");
4005 }
4006
4007 if (remote_description() &&
4008 configuration.use_datagram_transport_for_data_channels_receive_only !=
4009 configuration_
4010 .use_datagram_transport_for_data_channels_receive_only) {
4011 LOG_AND_RETURN_ERROR(
4012 RTCErrorType::INVALID_MODIFICATION,
4013 "Can't change use_datagram_transport_for_data_channels_receive_only "
4014 "after calling SetRemoteDescription.");
4015 }
4016
Piotr (Peter) Slatala37227be2018-11-21 15:42:224017 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 22:50:384018 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 21:19:384019 (configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 17:44:594020 *configuration.use_datagram_transport) ||
4021 (configuration.use_datagram_transport_for_data_channels &&
4022 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 15:42:224023 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
4024 << "Media transport requires MaxBundle policy.";
4025 }
4026
deadbeef293e9262017-01-11 20:28:304027 // The simplest (and most future-compatible) way to tell if the config was
4028 // modified in an invalid way is to copy each property we do support
4029 // modifying, then use operator==. There are far more properties we don't
4030 // support modifying than those we do, and more could be added.
4031 RTCConfiguration modified_config = configuration_;
4032 modified_config.servers = configuration.servers;
4033 modified_config.type = configuration.type;
4034 modified_config.ice_candidate_pool_size =
4035 configuration.ice_candidate_pool_size;
4036 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 18:27:504037 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 21:56:024038 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
4039 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-04 00:54:054040 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:144041 modified_config.ice_check_interval_strong_connectivity =
4042 configuration.ice_check_interval_strong_connectivity;
4043 modified_config.ice_check_interval_weak_connectivity =
4044 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:574045 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
4046 modified_config.ice_unwritable_min_checks =
4047 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:174048 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:494049 modified_config.stun_candidate_keepalive_interval =
4050 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:404051 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:404052 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:114053 modified_config.active_reset_srtp_params =
4054 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:454055 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:484056 modified_config.use_media_transport_for_data_channels =
4057 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 21:19:384058 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 17:44:594059 modified_config.use_datagram_transport_for_data_channels =
4060 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 18:02:114061 modified_config.use_datagram_transport_for_data_channels_receive_only =
4062 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 14:16:354063 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 10:23:024064 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 20:28:304065 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 07:58:174066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
4067 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 20:28:304068 }
4069
Steve Anton038834f2017-07-14 22:59:594070 // Validate the modified configuration.
4071 RTCError validate_error = ValidateConfiguration(modified_config);
4072 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 07:58:174073 return validate_error;
Steve Anton038834f2017-07-14 22:59:594074 }
4075
deadbeef293e9262017-01-11 20:28:304076 // Note that this isn't possible through chromium, since it's an unsigned
4077 // short in WebIDL.
4078 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:174079 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 07:58:174080 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 20:28:304081 }
4082
4083 // Parse ICE servers before hopping to network thread.
4084 cricket::ServerAddresses stun_servers;
4085 std::vector<cricket::RelayServerConfig> turn_servers;
4086 RTCErrorType parse_error =
4087 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
4088 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 07:58:174089 return RTCError(parse_error);
deadbeef293e9262017-01-11 20:28:304090 }
Jonas Oreland3c028422019-08-22 14:16:354091 // Add the turn logging id to all turn servers
4092 for (cricket::RelayServerConfig& turn_server : turn_servers) {
4093 turn_server.turn_logging_id = configuration.turn_logging_id;
4094 }
4095
Harald Alvestrand8ebba742018-05-31 12:00:344096 // Note if STUN or TURN servers were supplied.
4097 if (!stun_servers.empty()) {
4098 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
4099 }
4100 if (!turn_servers.empty()) {
4101 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
4102 }
deadbeef293e9262017-01-11 20:28:304103
4104 // In theory this shouldn't fail.
4105 if (!network_thread()->Invoke<bool>(
4106 RTC_FROM_HERE,
4107 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
4108 stun_servers, turn_servers, modified_config.type,
4109 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:504110 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 22:45:494111 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:284112 modified_config.stun_candidate_keepalive_interval,
4113 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 07:58:174114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4115 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 20:28:304116 }
Honghai Zhang4cedf2b2016-08-31 15:18:114117
deadbeefd1a38b52016-12-10 21:15:334118 // As described in JSEP, calling setConfiguration with new ICE servers or
4119 // candidate policy must set a "needs-ice-restart" bit so that the next offer
4120 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:304121 if (modified_config.servers != configuration_.servers ||
4122 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 18:27:504123 modified_config.GetTurnPortPrunePolicy() !=
4124 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 22:50:294125 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:334126 }
skvladd1f5fda2017-02-04 00:54:054127
Qingsi Wang9c98f0c2018-02-15 23:10:594128 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 21:19:384129
4130 use_datagram_transport_ = datagram_transport_config_.enabled &&
4131 modified_config.use_datagram_transport.value_or(
4132 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 17:44:594133 use_datagram_transport_for_data_channels_ =
4134 datagram_transport_data_channel_config_.enabled &&
4135 modified_config.use_datagram_transport_for_data_channels.value_or(
4136 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 18:02:114137 use_datagram_transport_for_data_channels_receive_only_ =
4138 modified_config.use_datagram_transport_for_data_channels_receive_only
4139 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 21:31:154140 transport_controller_->SetMediaTransportSettings(
4141 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 22:50:384142 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem7da4e562019-09-26 18:02:114143 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4144 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-04 00:54:054145
Zhi Huangb57e1692018-06-12 18:41:114146 if (configuration_.active_reset_srtp_params !=
4147 modified_config.active_reset_srtp_params) {
4148 transport_controller_->SetActiveResetSrtpParams(
4149 modified_config.active_reset_srtp_params);
4150 }
4151
philipel16cec3b2019-10-25 10:23:024152 if (modified_config.allow_codec_switching.has_value()) {
philipel01294f02019-11-14 12:03:254153 cricket::VideoMediaChannel* video_channel = video_media_channel();
4154 if (video_channel) {
4155 video_channel->SetVideoCodecSwitchingEnabled(
4156 *modified_config.allow_codec_switching);
4157 }
philipel16cec3b2019-10-25 10:23:024158 }
4159
deadbeef293e9262017-01-11 20:28:304160 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 22:55:094161 use_media_transport_ = configuration.use_media_transport;
Niels Möller2579f0c2019-08-19 07:58:174162 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:454163}
4164
henrike@webrtc.org28e20752013-07-10 00:45:364165bool PeerConnection::AddIceCandidate(
4166 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 09:18:564167 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:174168 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:254169 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:104170 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:364171 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:254172 return false;
4173 }
Steve Antond25da372017-11-06 22:50:294174
4175 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:104176 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:074177 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:364178 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:294179 return false;
4180 }
4181
4182 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:104183 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:364184 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:294185 return false;
4186 }
4187
4188 bool valid = false;
4189 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4190 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:364191 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:294192 return false;
4193 }
4194
4195 // Add this candidate to the remote session description.
4196 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:104197 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:364198 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:294199 return false;
4200 }
4201
4202 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:364203 bool result = UseCandidate(ice_candidate);
4204 if (result) {
Qingsi Wang1ba5dec2019-08-19 18:57:174205 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 21:24:364206 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4207 } else {
4208 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4209 }
4210 return result;
Steve Antond25da372017-11-06 22:50:294211 } else {
Steve Antonc79268f2018-04-24 16:54:104212 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:364213 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:294214 return true;
4215 }
henrike@webrtc.org28e20752013-07-10 00:45:364216}
4217
Henrik Boströmee6f4f62019-11-06 11:36:124218void PeerConnection::AddIceCandidate(
4219 std::unique_ptr<IceCandidateInterface> candidate,
4220 std::function<void(RTCError)> callback) {
4221 RTC_DCHECK_RUN_ON(signaling_thread());
4222 // Chain this operation. If asynchronous operations are pending on the chain,
4223 // this operation will be queued to be invoked, otherwise the contents of the
4224 // lambda will execute immediately.
4225 operations_chain_->ChainOperation(
4226 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
4227 candidate = std::move(candidate), callback = std::move(callback)](
4228 std::function<void()> operations_chain_callback) {
4229 if (!this_weak_ptr) {
4230 operations_chain_callback();
4231 callback(RTCError(
4232 RTCErrorType::INVALID_STATE,
4233 "AddIceCandidate failed because the session was shut down"));
4234 return;
4235 }
4236 if (!this_weak_ptr->AddIceCandidate(candidate.get())) {
4237 operations_chain_callback();
4238 // Fail with an error type and message consistent with Chromium.
4239 // TODO(hbos): Fail with error types according to spec.
4240 callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
4241 "Error processing ICE candidate"));
4242 return;
4243 }
4244 operations_chain_callback();
4245 callback(RTCError::OK());
4246 });
4247}
4248
Honghai Zhang7fb69db2016-03-14 18:59:184249bool PeerConnection::RemoveIceCandidates(
4250 const std::vector<cricket::Candidate>& candidates) {
4251 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 09:31:564252 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 16:54:104253 if (IsClosed()) {
4254 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4255 return false;
4256 }
4257
Steve Antond25da372017-11-06 22:50:294258 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:104259 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4260 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:294261 return false;
4262 }
4263
4264 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:104265 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:294266 return false;
4267 }
4268
4269 size_t number_removed =
4270 mutable_remote_description()->RemoveCandidates(candidates);
4271 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:254272 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:104273 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:074274 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:254275 << " are removed.";
Steve Antond25da372017-11-06 22:50:294276 }
4277
4278 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:354279 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4280 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:104281 RTC_LOG(LS_ERROR)
4282 << "RemoveIceCandidates: Error when removing remote candidates: "
4283 << error.message();
Steve Antond25da372017-11-06 22:50:294284 }
4285 return true;
Honghai Zhang7fb69db2016-03-14 18:59:184286}
4287
Niels Möller0c4f7be2018-05-07 12:01:374288RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:024289 if (!worker_thread()->IsCurrent()) {
4290 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:054291 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:374292 }
Karl Wiberg6cab5c82019-03-26 08:57:014293 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 21:37:374294
Niels Möller0c4f7be2018-05-07 12:01:374295 const bool has_min = bitrate.min_bitrate_bps.has_value();
4296 const bool has_start = bitrate.start_bitrate_bps.has_value();
4297 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:374298 if (has_min && *bitrate.min_bitrate_bps < 0) {
4299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4300 "min_bitrate_bps <= 0");
4301 }
Niels Möller0c4f7be2018-05-07 12:01:374302 if (has_start) {
4303 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:374304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:374305 "start_bitrate_bps < min_bitrate_bps");
4306 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:374307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4308 "curent_bitrate_bps < 0");
4309 }
4310 }
4311 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:054312 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:374313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:374314 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:374315 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4317 "max_bitrate_bps < min_bitrate_bps");
4318 } else if (*bitrate.max_bitrate_bps < 0) {
4319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4320 "max_bitrate_bps < 0");
4321 }
4322 }
4323
zstein4b979802017-06-02 21:37:374324 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 17:31:544325 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:374326
4327 return RTCError::OK();
4328}
4329
henrika5f6bf242017-11-01 10:06:564330void PeerConnection::SetAudioPlayout(bool playout) {
4331 if (!worker_thread()->IsCurrent()) {
4332 worker_thread()->Invoke<void>(
4333 RTC_FROM_HERE,
4334 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4335 return;
4336 }
4337 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:554338 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:564339 audio_state->SetPlayout(playout);
4340}
4341
4342void PeerConnection::SetAudioRecording(bool recording) {
4343 if (!worker_thread()->IsCurrent()) {
4344 worker_thread()->Invoke<void>(
4345 RTC_FROM_HERE,
4346 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4347 return;
4348 }
4349 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:554350 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:564351 audio_state->SetRecording(recording);
4352}
4353
Steve Anton8c0f7a72017-10-03 17:03:104354std::unique_ptr<rtc::SSLCertificate>
4355PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:514356 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4357 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:104358 return nullptr;
4359 }
Steve Antonf25303e2018-10-16 22:23:314360 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:104361}
4362
Zhi Huang70b820f2018-01-27 22:16:154363std::unique_ptr<rtc::SSLCertChain>
4364PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 12:33:434365 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 19:35:374366 auto audio_transceiver = GetFirstAudioTransceiver();
4367 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:154368 return nullptr;
4369 }
Zhi Huang70b820f2018-01-27 22:16:154370 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:374371 audio_transceiver->internal()->channel()->transport_name());
4372}
4373
4374rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4375PeerConnection::GetFirstAudioTransceiver() const {
4376 for (auto transceiver : transceivers_) {
4377 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4378 return transceiver;
4379 }
4380 }
4381 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:154382}
4383
Bjorn Tereliusde939432017-11-20 16:38:144384bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4385 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 16:38:144386 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 08:21:114387 RTC_FROM_HERE,
4388 [this, output = std::move(output), output_period_ms]() mutable {
4389 return StartRtcEventLog_w(std::move(output), output_period_ms);
4390 });
ivoc14d5dbe2016-07-04 14:06:554391}
4392
Niels Möllerf00ca1a2019-05-10 09:33:124393bool PeerConnection::StartRtcEventLog(
4394 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 10:27:234395 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4396 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4397 output_period_ms = 5000;
4398 }
4399 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 09:33:124400}
4401
ivoc14d5dbe2016-07-04 14:06:554402void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:024403 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:554404 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4405}
4406
Harald Alvestrandad88c882018-11-28 15:47:464407rtc::scoped_refptr<DtlsTransportInterface>
4408PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:564409 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 15:47:464410 return transport_controller_->LookupDtlsTransportByMid(mid);
4411}
4412
Harald Alvestrand4a7b3ac2019-01-17 09:39:404413rtc::scoped_refptr<DtlsTransport>
4414PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:564415 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 09:39:404416 return transport_controller_->LookupDtlsTransportByMid(mid);
4417}
4418
Harald Alvestrandc85328f2019-02-28 06:51:004419rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4420 const {
Karl Wiberg2cc368f2019-04-02 09:31:564421 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 21:53:544422 if (!sctp_mid_) {
4423 return nullptr;
4424 }
4425 return transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandc85328f2019-02-28 06:51:004426}
4427
henrike@webrtc.org28e20752013-07-10 00:45:364428const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 09:37:284429 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174430 return pending_local_description_ ? pending_local_description_.get()
4431 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:364432}
4433
4434const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 09:37:284435 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174436 return pending_remote_description_ ? pending_remote_description_.get()
4437 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:364438}
4439
deadbeeffe4a8a42016-12-21 01:56:174440const SessionDescriptionInterface* PeerConnection::current_local_description()
4441 const {
Karl Wiberg739506e2019-04-03 09:37:284442 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174443 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174444}
4445
4446const SessionDescriptionInterface* PeerConnection::current_remote_description()
4447 const {
Karl Wiberg739506e2019-04-03 09:37:284448 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174449 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174450}
4451
4452const SessionDescriptionInterface* PeerConnection::pending_local_description()
4453 const {
Karl Wiberg739506e2019-04-03 09:37:284454 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174455 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174456}
4457
4458const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4459 const {
Karl Wiberg739506e2019-04-03 09:37:284460 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174461 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174462}
4463
henrike@webrtc.org28e20752013-07-10 00:45:364464void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 09:18:564465 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:174466 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:364467 // Update stats here so that we have the most recent stats for tracks and
4468 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:264469 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:364470
Steve Anton75737c02017-11-06 18:37:174471 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:344472 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:084473
Mirko Bonadei739baf02019-01-27 16:29:424474 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:134475 transceiver->Stop();
4476 }
Steve Anton25cfeb92018-04-26 18:44:004477
4478 // Ensure that all asynchronous stats requests are completed before destroying
4479 // the transport controller below.
4480 if (stats_collector_) {
4481 stats_collector_->WaitForPendingRequest();
4482 }
4483
4484 // Don't destroy BaseChannels until after stats has been cleaned up so that
4485 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:134486 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:174487
Qingsi Wang93a84392018-01-31 01:13:094488 // The event log is used in the transport controller, which must be outlived
4489 // by the former. CreateOffer by the peer connection is implemented
4490 // asynchronously and if the peer connection is closed without resetting the
4491 // WebRTC session description factory, the session description factory would
4492 // call the transport controller.
4493 webrtc_session_desc_factory_.reset();
4494 transport_controller_.reset();
4495
deadbeef42a42632017-03-10 23:18:004496 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:054497 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4498 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:024499
Steve Anton978b8762017-09-29 19:15:024500 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:574501 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:154502 call_.reset();
4503 // The event log must outlive call (and any other object that uses it).
4504 event_log_.reset();
4505 });
Harald Alvestrand8ebba742018-05-31 12:00:344506 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:164507 // The .h file says that observer can be discarded after close() returns.
4508 // Make sure this is true.
4509 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:364510}
4511
Steve Antonad182762018-09-05 20:22:404512void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 09:18:564513 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:404514 switch (msg->message_id) {
4515 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4516 SetSessionDescriptionMsg* param =
4517 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4518 param->observer->OnSuccess();
4519 delete param;
4520 break;
4521 }
4522 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4523 SetSessionDescriptionMsg* param =
4524 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4525 param->observer->OnFailure(std::move(param->error));
4526 delete param;
4527 break;
4528 }
4529 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4530 CreateSessionDescriptionMsg* param =
4531 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4532 param->observer->OnFailure(std::move(param->error));
4533 delete param;
4534 break;
4535 }
4536 case MSG_GETSTATS: {
4537 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4538 StatsReports reports;
4539 stats_->GetStats(param->track, &reports);
4540 param->observer->OnComplete(reports);
4541 delete param;
4542 break;
4543 }
4544 case MSG_FREE_DATACHANNELS: {
4545 sctp_data_channels_to_free_.clear();
4546 break;
4547 }
4548 case MSG_REPORT_USAGE_PATTERN: {
4549 ReportUsagePattern();
4550 break;
4551 }
4552 default:
4553 RTC_NOTREACHED() << "Not implemented";
4554 break;
4555 }
4556}
4557
Steve Antonafb0bb72018-02-20 19:35:374558cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4559 RTC_DCHECK(!IsUnifiedPlan());
4560 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4561 GetAudioTransceiver()->internal()->channel());
4562 if (voice_channel) {
4563 return voice_channel->media_channel();
4564 } else {
4565 return nullptr;
4566 }
4567}
4568
4569cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4570 RTC_DCHECK(!IsUnifiedPlan());
4571 auto* video_channel = static_cast<cricket::VideoChannel*>(
4572 GetVideoTransceiver()->internal()->channel());
4573 if (video_channel) {
4574 return video_channel->media_channel();
4575 } else {
4576 return nullptr;
4577 }
4578}
4579
Steve Anton4171afb2017-11-20 18:20:224580void PeerConnection::CreateAudioReceiver(
4581 MediaStreamInterface* stream,
4582 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:514583 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4584 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:534585 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4586 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:024587 auto* audio_receiver = new AudioRtpReceiver(
4588 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:054589 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 23:23:054590 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4591 audio_receiver->SetupUnsignaledMediaChannel();
4592 } else {
4593 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4594 }
Steve Antond3679212018-01-18 01:41:024595 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4596 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:224597 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:124598 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:344599 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:364600}
4601
Steve Anton4171afb2017-11-20 18:20:224602void PeerConnection::CreateVideoReceiver(
4603 MediaStreamInterface* stream,
4604 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:514605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4606 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:534607 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4608 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:024609 auto* video_receiver = new VideoRtpReceiver(
4610 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:054611 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 23:23:054612 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4613 video_receiver->SetupUnsignaledMediaChannel();
4614 } else {
4615 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4616 }
Steve Antond3679212018-01-18 01:41:024617 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4618 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:224619 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:124620 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:344621 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:364622}
4623
deadbeef70ab1a12015-09-28 23:53:554624// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4625// description.
Henrik Boström933d8b02017-10-10 17:05:164626rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:224627 const RtpSenderInfo& remote_sender_info) {
4628 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4629 if (!receiver) {
4630 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4631 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:164632 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554633 }
Steve Anton4171afb2017-11-20 18:20:224634 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4635 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4636 } else {
4637 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4638 }
Henrik Boström933d8b02017-10-10 17:05:164639 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:364640}
4641
korniltsev.anatolyec390b52017-07-25 00:00:254642void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4643 MediaStreamInterface* stream) {
4644 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364645 RTC_DCHECK(track);
4646 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254647 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224648 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254649 // We already have a sender for this track, so just change the stream_id
4650 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:384651 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254652 return;
4653 }
4654
4655 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364656 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204657 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054658 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:224659 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:254660 // If the sender has already been configured in SDP, we call SetSsrc,
4661 // which will connect the sender to the underlying transport. This can
4662 // occur if a local session description that contains the ID of the sender
4663 // is set before AddStream is called. It can also occur if the local
4664 // session description is not changed and RemoveStream is called, and
4665 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:224666 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184667 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224668 if (sender_info) {
4669 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254670 }
4671}
4672
4673// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4674// indefinitely, when we have unified plan SDP.
4675void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4676 MediaStreamInterface* stream) {
4677 RTC_DCHECK(!IsClosed());
4678 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224679 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254680 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4681 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254682 return;
4683 }
Steve Anton4171afb2017-11-20 18:20:224684 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254685}
4686
4687void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4688 MediaStreamInterface* stream) {
4689 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364690 RTC_DCHECK(track);
4691 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254692 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224693 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254694 // We already have a sender for this track, so just change the stream_id
4695 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:384696 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254697 return;
4698 }
4699
4700 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364701 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204702 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054703 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:224704 GetVideoTransceiver()->internal()->AddSender(new_sender);
4705 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184706 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224707 if (sender_info) {
4708 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254709 }
4710}
4711
4712void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4713 MediaStreamInterface* stream) {
4714 RTC_DCHECK(!IsClosed());
4715 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224716 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254717 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4718 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254719 return;
4720 }
Steve Anton4171afb2017-11-20 18:20:224721 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254722}
4723
Steve Antonba818672017-11-06 18:21:574724void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 18:21:574725 if (ice_connection_state_ == new_state) {
4726 return;
4727 }
4728
deadbeefcbecd352015-09-23 18:50:274729 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:574730 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:114731 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:274732 return;
4733 }
Steve Antonba818672017-11-06 18:21:574734
Mirko Bonadei675513b2017-11-09 10:09:254735 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4736 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:574737 RTC_DCHECK(ice_connection_state_ !=
4738 PeerConnectionInterface::kIceConnectionClosed);
4739
henrike@webrtc.org28e20752013-07-10 00:45:364740 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164741 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364742}
4743
Alex Loiko9289eda2018-11-23 16:18:594744void PeerConnection::SetStandardizedIceConnectionState(
4745 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 18:37:264746 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:594747 return;
Qingsi Wang36e31472019-05-29 18:37:264748 }
4749
4750 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:594751 return;
Qingsi Wang36e31472019-05-29 18:37:264752 }
4753
4754 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4755 << standardized_ice_connection_state_ << " => " << new_state;
4756
Alex Loiko9289eda2018-11-23 16:18:594757 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 10:25:144758 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:594759}
4760
Jonas Olsson635474e2018-10-18 13:58:174761void PeerConnection::SetConnectionState(
4762 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 13:58:174763 if (connection_state_ == new_state)
4764 return;
4765 if (IsClosed())
4766 return;
4767 connection_state_ = new_state;
4768 Observer()->OnConnectionChange(new_state);
4769}
4770
henrike@webrtc.org28e20752013-07-10 00:45:364771void PeerConnection::OnIceGatheringChange(
4772 PeerConnectionInterface::IceGatheringState new_state) {
4773 if (IsClosed()) {
4774 return;
4775 }
4776 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164777 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364778}
4779
jbauch81bf7b02017-03-25 15:31:124780void PeerConnection::OnIceCandidate(
4781 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 18:07:254782 if (IsClosed()) {
4783 return;
4784 }
Qingsi Wang1ba5dec2019-08-19 18:57:174785 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 08:50:164786 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:364787}
4788
Eldar Relloda13ea22019-06-01 09:23:434789void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4790 const std::string& url,
4791 int error_code,
4792 const std::string& error_text) {
4793 if (IsClosed()) {
4794 return;
4795 }
4796 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4797}
4798
Honghai Zhang7fb69db2016-03-14 18:59:184799void PeerConnection::OnIceCandidatesRemoved(
4800 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 18:07:254801 if (IsClosed()) {
4802 return;
4803 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164804 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:184805}
4806
Alex Drake00c7ecf2019-08-06 17:54:474807void PeerConnection::OnSelectedCandidatePairChanged(
4808 const cricket::CandidatePairChangeEvent& event) {
4809 if (IsClosed()) {
4810 return;
4811 }
Qingsi Wang1ba5dec2019-08-19 18:57:174812
Qingsi Wangcc46b10c2019-09-12 18:19:014813 if (event.selected_candidate_pair.local_candidate().type() ==
4814 LOCAL_PORT_TYPE &&
4815 event.selected_candidate_pair.remote_candidate().type() ==
4816 LOCAL_PORT_TYPE) {
4817 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4818 }
4819
Alex Drake00c7ecf2019-08-06 17:54:474820 Observer()->OnIceSelectedCandidatePairChanged(event);
4821}
4822
henrike@webrtc.org28e20752013-07-10 00:45:364823void PeerConnection::ChangeSignalingState(
4824 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:574825 if (signaling_state_ == signaling_state) {
4826 return;
4827 }
Mirko Bonadei675513b2017-11-09 10:09:254828 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4829 << GetSignalingStateString(signaling_state_)
4830 << " New state: "
4831 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:364832 signaling_state_ = signaling_state;
4833 if (signaling_state == kClosed) {
4834 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:164835 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:594836 standardized_ice_connection_state_ =
4837 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:174838 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4839 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364840 if (ice_gathering_state_ != kIceGatheringComplete) {
4841 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:164842 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364843 }
4844 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164845 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364846}
4847
deadbeefeb459812015-12-16 03:24:434848void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4849 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254850 if (IsClosed()) {
4851 return;
4852 }
korniltsev.anatolyec390b52017-07-25 00:00:254853 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144854 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434855}
4856
deadbeefeb459812015-12-16 03:24:434857void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4858 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254859 if (IsClosed()) {
4860 return;
4861 }
korniltsev.anatolyec390b52017-07-25 00:00:254862 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144863 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434864}
4865
4866void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4867 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254868 if (IsClosed()) {
4869 return;
4870 }
korniltsev.anatolyec390b52017-07-25 00:00:254871 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144872 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434873}
4874
4875void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4876 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254877 if (IsClosed()) {
4878 return;
4879 }
korniltsev.anatolyec390b52017-07-25 00:00:254880 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144881 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434882}
4883
Henrik Boström31638672017-11-23 16:48:324884void PeerConnection::PostSetSessionDescriptionSuccess(
4885 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:404886 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4887 signaling_thread()->Post(RTC_FROM_HERE, this,
4888 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:324889}
4890
deadbeefab9b2d12015-10-14 18:33:114891void PeerConnection::PostSetSessionDescriptionFailure(
4892 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:404893 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:034894 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404895 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4896 msg->error = std::move(error);
4897 signaling_thread()->Post(RTC_FROM_HERE, this,
4898 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114899}
4900
4901void PeerConnection::PostCreateSessionDescriptionFailure(
4902 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:034903 RTCError error) {
4904 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404905 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4906 msg->error = std::move(error);
4907 signaling_thread()->Post(RTC_FROM_HERE, this,
4908 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114909}
4910
zhihuang1c378ed2017-08-17 21:10:504911void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:544912 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:114913 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:544914 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:504915
Steve Antondcc3c022017-12-23 00:02:544916 if (IsUnifiedPlan()) {
4917 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4918 } else {
4919 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4920 }
4921
Steve Antonfa2260d2017-12-29 00:38:234922 // Intentionally unset the data channel type for RTP data channel with the
4923 // second condition. Otherwise the RTP data channels would be successfully
4924 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4925 // when building with chromium. We want to leave RTP data channels broken, so
4926 // people won't try to use them.
4927 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4928 session_options->data_channel_type = data_channel_type();
4929 }
4930
Steve Antondcc3c022017-12-23 00:02:544931 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 09:16:564932 bool ice_restart = offer_answer_options.ice_restart ||
4933 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-23 00:02:544934 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 09:16:564935 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-23 00:02:544936 options.transport_options.enable_ice_renomination =
4937 configuration_.enable_ice_renomination;
4938 }
4939
4940 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444941 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:124942 session_options->pooled_ice_credentials =
4943 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4944 RTC_FROM_HERE,
4945 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4946 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 09:25:484947 session_options->offer_extmap_allow_mixed =
4948 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:054949
Bjorn A Mellemc85ebbe2019-06-07 17:28:064950 if (configuration_.use_media_transport ||
4951 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:054952 session_options->media_transport_settings =
4953 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4954 }
Bjorn A Mellemc85ebbe2019-06-07 17:28:064955
4956 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 17:44:594957 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 17:28:064958 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 22:12:474959 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 17:28:064960 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 22:12:474961 if (!params) {
4962 continue;
4963 }
4964 options.transport_options.opaque_parameters = params;
4965 if ((use_datagram_transport_ &&
4966 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4967 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4968 (use_datagram_transport_for_data_channels_ &&
4969 options.type == cricket::MEDIA_TYPE_DATA)) {
4970 options.alt_protocol = params->protocol;
4971 }
Bjorn A Mellemc85ebbe2019-06-07 17:28:064972 }
4973 }
4974
Harald Alvestrand4aa11922019-05-14 20:00:014975 // Allow fallback for using obsolete SCTP syntax.
4976 // Note that the default in |session_options| is true, while
4977 // the default in |options| is false.
4978 session_options->use_obsolete_sctp_sdp =
4979 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-23 00:02:544980}
4981
4982void PeerConnection::GetOptionsForPlanBOffer(
4983 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4984 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504985 // Figure out transceiver directional preferences.
4986 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4987 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4988
4989 // By default, generate sendrecv/recvonly m= sections.
4990 bool recv_audio = true;
4991 bool recv_video = true;
4992
4993 // By default, only offer a new m= section if we have media to send with it.
4994 bool offer_new_audio_description = send_audio;
4995 bool offer_new_video_description = send_video;
4996 bool offer_new_data_description = HasDataChannels();
4997
4998 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544999 if (offer_answer_options.offer_to_receive_audio !=
5000 RTCOfferAnswerOptions::kUndefined) {
5001 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:505002 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:545003 offer_new_audio_description ||
5004 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:505005 }
Steve Antondcc3c022017-12-23 00:02:545006 if (offer_answer_options.offer_to_receive_video !=
5007 RTCOfferAnswerOptions::kUndefined) {
5008 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:505009 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:545010 offer_new_video_description ||
5011 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:505012 }
5013
Danil Chapovalov66cadcc2018-06-19 14:47:435014 absl::optional<size_t> audio_index;
5015 absl::optional<size_t> video_index;
5016 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:505017 // If a current description exists, generate m= sections in the same order,
5018 // using the first audio/video/data section that appears and rejecting
5019 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:175020 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:505021 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:175022 local_description(),
Steve Anton1d03a752017-11-27 22:30:095023 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5024 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5025 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:115026 }
5027
zhihuang1c378ed2017-08-17 21:10:505028 // Add audio/video/data m= sections to the end if needed.
5029 if (!audio_index && offer_new_audio_description) {
5030 session_options->media_description_options.push_back(
5031 cricket::MediaDescriptionOptions(
5032 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:095033 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5034 false));
Oskar Sundbom9b28a032017-11-16 09:53:305035 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:455036 }
zhihuang1c378ed2017-08-17 21:10:505037 if (!video_index && offer_new_video_description) {
5038 session_options->media_description_options.push_back(
5039 cricket::MediaDescriptionOptions(
5040 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:095041 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5042 false));
Oskar Sundbom9b28a032017-11-16 09:53:305043 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:455044 }
zhihuang1c378ed2017-08-17 21:10:505045 if (!data_index && offer_new_data_description) {
5046 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235047 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:305048 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505049 }
5050
5051 cricket::MediaDescriptionOptions* audio_media_description_options =
5052 !audio_index ? nullptr
5053 : &session_options->media_description_options[*audio_index];
5054 cricket::MediaDescriptionOptions* video_media_description_options =
5055 !video_index ? nullptr
5056 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:505057
Amit Hilbuchc63ddb22019-01-02 18:13:585058 AddPlanBRtpSenderOptions(GetSendersInternal(),
5059 audio_media_description_options,
5060 video_media_description_options,
5061 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:545062}
5063
Steve Antondcc3c022017-12-23 00:02:545064static cricket::MediaDescriptionOptions
5065GetMediaDescriptionOptionsForTransceiver(
5066 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5067 transceiver,
5068 const std::string& mid) {
5069 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:085070 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:545071 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 17:25:515072 media_description_options.codec_preferences =
5073 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 18:58:305074 // This behavior is specified in JSEP. The gist is that:
5075 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5076 // sendrecv.
5077 // 2. If the MSID is included, then it must be included in any subsequent
5078 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-26 01:13:565079 if (transceiver->stopped() ||
5080 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5081 !transceiver->internal()->has_ever_been_used_to_send())) {
5082 return media_description_options;
Steve Anton5f94aa22018-02-01 18:58:305083 }
Amit Hilbuchbcd39d42019-01-26 01:13:565084
5085 cricket::SenderOptions sender_options;
5086 sender_options.track_id = transceiver->sender()->id();
5087 sender_options.stream_ids = transceiver->sender()->stream_ids();
5088
5089 // The following sets up RIDs and Simulcast.
5090 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 23:55:195091 RtpParameters send_parameters =
5092 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-26 01:13:565093 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5094 send_parameters.encodings.end(),
5095 [](const RtpEncodingParameters& encoding) {
5096 return !encoding.rid.empty();
5097 });
5098
Amit Hilbuchb7446ed2019-01-28 20:25:255099 std::vector<RidDescription> send_rids;
5100 SimulcastLayerList send_layers;
5101 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5102 if (encoding.rid.empty()) {
5103 continue;
5104 }
5105 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5106 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5107 }
5108
Amit Hilbuchbcd39d42019-01-26 01:13:565109 if (has_rids) {
5110 sender_options.rids = send_rids;
5111 }
5112
5113 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:565114 // When RIDs are configured, we must set num_sim_layers to 0 to.
5115 // Otherwise, num_sim_layers must be 1 because either there is no
5116 // simulcast, or simulcast is acheived by munging the SDP.
5117 sender_options.num_sim_layers = has_rids ? 0 : 1;
5118 media_description_options.sender_options.push_back(sender_options);
5119
Steve Antondcc3c022017-12-23 00:02:545120 return media_description_options;
5121}
5122
Steve Anton5c72e712018-12-10 22:25:305123// Returns the ContentInfo at mline index |i|, or null if none exists.
5124static const ContentInfo* GetContentByIndex(
5125 const SessionDescriptionInterface* sdesc,
5126 size_t i) {
5127 if (!sdesc) {
5128 return nullptr;
5129 }
5130 const ContentInfos& contents = sdesc->description()->contents();
5131 return (i < contents.size() ? &contents[i] : nullptr);
5132}
5133
Steve Antondcc3c022017-12-23 00:02:545134void PeerConnection::GetOptionsForUnifiedPlanOffer(
5135 const RTCOfferAnswerOptions& offer_answer_options,
5136 cricket::MediaSessionOptions* session_options) {
5137 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5138 // Offers) and 5.2.2 (Subsequent Offers).
5139 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 18:35:455140 const ContentInfos no_infos;
Steve Antondcc3c022017-12-23 00:02:545141 const ContentInfos& local_contents =
5142 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:455143 : no_infos);
Steve Antondcc3c022017-12-23 00:02:545144 const ContentInfos& remote_contents =
5145 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:455146 : no_infos);
Steve Antondcc3c022017-12-23 00:02:545147 // The mline indices that can be recycled. New transceivers should reuse these
5148 // slots first.
5149 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-23 00:02:545150 // First, go through each media section that exists in either the local or
5151 // remote description and generate a media section in this offer for the
5152 // associated transceiver. If a media section can be recycled, generate a
5153 // default, rejected media section here that can be later overwritten.
5154 for (size_t i = 0;
5155 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5156 // Either |local_content| or |remote_content| is non-null.
5157 const ContentInfo* local_content =
5158 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:305159 const ContentInfo* current_local_content =
5160 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-23 00:02:545161 const ContentInfo* remote_content =
5162 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:305163 const ContentInfo* current_remote_content =
5164 GetContentByIndex(current_remote_description(), i);
5165 bool had_been_rejected =
5166 (current_local_content && current_local_content->rejected) ||
5167 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-23 00:02:545168 const std::string& mid =
5169 (local_content ? local_content->name : remote_content->name);
5170 cricket::MediaType media_type =
5171 (local_content ? local_content->media_description()->type()
5172 : remote_content->media_description()->type());
5173 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5174 media_type == cricket::MEDIA_TYPE_VIDEO) {
5175 auto transceiver = GetAssociatedTransceiver(mid);
5176 RTC_CHECK(transceiver);
5177 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 22:25:305178 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 23:33:485179 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:545180 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:085181 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5182 RtpTransceiverDirection::kInactive,
5183 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:545184 recycleable_mline_indices.push(i);
5185 } else {
5186 session_options->media_description_options.push_back(
5187 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5188 // CreateOffer shouldn't really cause any state changes in
5189 // PeerConnection, but we need a way to match new transceivers to new
5190 // media sections in SetLocalDescription and JSEP specifies this is done
5191 // by recording the index of the media section generated for the
5192 // transceiver in the offer.
5193 transceiver->internal()->set_mline_index(i);
5194 }
5195 } else {
5196 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:235197 RTC_CHECK(GetDataMid());
5198 if (had_been_rejected || mid != *GetDataMid()) {
5199 session_options->media_description_options.push_back(
5200 GetMediaDescriptionOptionsForRejectedData(mid));
5201 } else {
5202 session_options->media_description_options.push_back(
5203 GetMediaDescriptionOptionsForActiveData(mid));
5204 }
Steve Antondcc3c022017-12-23 00:02:545205 }
5206 }
Amit Hilbuchae3df542019-01-07 20:13:085207
Steve Antondcc3c022017-12-23 00:02:545208 // Next, look for transceivers that are newly added (that is, are not stopped
5209 // and not associated). Reuse media sections marked as recyclable first,
5210 // otherwise append to the end of the offer. New media sections should be
5211 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 16:29:425212 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:545213 if (transceiver->mid() || transceiver->stopped()) {
5214 continue;
5215 }
5216 size_t mline_index;
5217 if (!recycleable_mline_indices.empty()) {
5218 mline_index = recycleable_mline_indices.front();
5219 recycleable_mline_indices.pop();
5220 session_options->media_description_options[mline_index] =
5221 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:085222 mid_generator_());
Steve Antondcc3c022017-12-23 00:02:545223 } else {
5224 mline_index = session_options->media_description_options.size();
5225 session_options->media_description_options.push_back(
5226 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:085227 mid_generator_()));
Steve Antondcc3c022017-12-23 00:02:545228 }
5229 // See comment above for why CreateOffer changes the transceiver's state.
5230 transceiver->internal()->set_mline_index(mline_index);
5231 }
Steve Antonfa2260d2017-12-29 00:38:235232 // Lastly, add a m-section if we have local data channels and an m section
5233 // does not already exist.
5234 if (!GetDataMid() && HasDataChannels()) {
5235 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 20:13:085236 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-29 00:38:235237 }
Steve Antondcc3c022017-12-23 00:02:545238}
5239
5240void PeerConnection::GetOptionsForAnswer(
5241 const RTCOfferAnswerOptions& offer_answer_options,
5242 cricket::MediaSessionOptions* session_options) {
5243 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5244
5245 if (IsUnifiedPlan()) {
5246 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5247 } else {
5248 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5249 }
5250
Steve Antonfa2260d2017-12-29 00:38:235251 // Intentionally unset the data channel type for RTP data channel. Otherwise
5252 // the RTP data channels would be successfully negotiated by default and the
5253 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5254 // We want to leave RTP data channels broken, so people won't try to use them.
5255 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
5256 session_options->data_channel_type = data_channel_type();
5257 }
5258
Steve Antondcc3c022017-12-23 00:02:545259 // Apply ICE renomination flag.
5260 for (auto& options : session_options->media_description_options) {
5261 options.transport_options.enable_ice_renomination =
5262 configuration_.enable_ice_renomination;
5263 }
zhihuang8f65cdf2016-05-07 01:40:305264
5265 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:445266 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:125267 session_options->pooled_ice_credentials =
5268 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5269 RTC_FROM_HERE,
5270 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5271 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 17:28:065272
5273 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 17:44:595274 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 17:28:065275 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 22:12:475276 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 17:28:065277 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 22:12:475278 if (!params) {
5279 continue;
5280 }
5281 options.transport_options.opaque_parameters = params;
5282 if ((use_datagram_transport_ &&
5283 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5284 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5285 (use_datagram_transport_for_data_channels_ &&
5286 options.type == cricket::MEDIA_TYPE_DATA)) {
5287 options.alt_protocol = params->protocol;
5288 }
Bjorn A Mellemc85ebbe2019-06-07 17:28:065289 }
5290 }
deadbeefab9b2d12015-10-14 18:33:115291}
5292
Steve Antondcc3c022017-12-23 00:02:545293void PeerConnection::GetOptionsForPlanBAnswer(
5294 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:115295 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:505296 // Figure out transceiver directional preferences.
5297 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5298 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5299
5300 // By default, generate sendrecv/recvonly m= sections. The direction is also
5301 // restricted by the direction in the offer.
5302 bool recv_audio = true;
5303 bool recv_video = true;
5304
5305 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:545306 if (offer_answer_options.offer_to_receive_audio !=
5307 RTCOfferAnswerOptions::kUndefined) {
5308 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:525309 }
Steve Antondcc3c022017-12-23 00:02:545310 if (offer_answer_options.offer_to_receive_video !=
5311 RTCOfferAnswerOptions::kUndefined) {
5312 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:505313 }
5314
Danil Chapovalov66cadcc2018-06-19 14:47:435315 absl::optional<size_t> audio_index;
5316 absl::optional<size_t> video_index;
5317 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:295318
5319 // Generate m= sections that match those in the offer.
5320 // Note that mediasession.cc will handle intersection our preferred
5321 // direction with the offered direction.
5322 GenerateMediaDescriptionOptions(
5323 remote_description(),
5324 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5325 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5326 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:505327
5328 cricket::MediaDescriptionOptions* audio_media_description_options =
5329 !audio_index ? nullptr
5330 : &session_options->media_description_options[*audio_index];
5331 cricket::MediaDescriptionOptions* video_media_description_options =
5332 !video_index ? nullptr
5333 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:505334
Amit Hilbuchc63ddb22019-01-02 18:13:585335 AddPlanBRtpSenderOptions(GetSendersInternal(),
5336 audio_media_description_options,
5337 video_media_description_options,
5338 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:545339}
zhihuangaf388472016-11-02 23:49:485340
Steve Antondcc3c022017-12-23 00:02:545341void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5342 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5343 cricket::MediaSessionOptions* session_options) {
5344 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5345 // Answers) and 5.3.2 (Subsequent Answers).
5346 RTC_DCHECK(remote_description());
5347 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5348 for (const ContentInfo& content :
5349 remote_description()->description()->contents()) {
5350 cricket::MediaType media_type = content.media_description()->type();
5351 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5352 media_type == cricket::MEDIA_TYPE_VIDEO) {
5353 auto transceiver = GetAssociatedTransceiver(content.name);
5354 RTC_CHECK(transceiver);
5355 session_options->media_description_options.push_back(
5356 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5357 } else {
5358 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:405359 // Reject all data sections if data channels are disabled.
5360 // Reject a data section if it has already been rejected.
5361 // Reject all data sections except for the first one.
5362 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
5363 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:235364 session_options->media_description_options.push_back(
5365 GetMediaDescriptionOptionsForRejectedData(content.name));
5366 } else {
5367 session_options->media_description_options.push_back(
5368 GetMediaDescriptionOptionsForActiveData(content.name));
5369 }
Steve Antondcc3c022017-12-23 00:02:545370 }
5371 }
htaa2a49d92016-03-04 10:51:395372}
5373
zhihuang1c378ed2017-08-17 21:10:505374void PeerConnection::GenerateMediaDescriptionOptions(
5375 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:095376 RtpTransceiverDirection audio_direction,
5377 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:435378 absl::optional<size_t>* audio_index,
5379 absl::optional<size_t>* video_index,
5380 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:395381 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:505382 for (const cricket::ContentInfo& content :
5383 session_desc->description()->contents()) {
5384 if (IsAudioContent(&content)) {
5385 // If we already have an audio m= section, reject this extra one.
5386 if (*audio_index) {
5387 session_options->media_description_options.push_back(
5388 cricket::MediaDescriptionOptions(
5389 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 22:25:305390 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:505391 } else {
Steve Anton5c72e712018-12-10 22:25:305392 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:505393 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:305394 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5395 content.name, audio_direction,
5396 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:305397 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505398 }
5399 } else if (IsVideoContent(&content)) {
5400 // If we already have an video m= section, reject this extra one.
5401 if (*video_index) {
5402 session_options->media_description_options.push_back(
5403 cricket::MediaDescriptionOptions(
5404 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 22:25:305405 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:505406 } else {
Steve Anton5c72e712018-12-10 22:25:305407 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:505408 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:305409 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5410 content.name, video_direction,
5411 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:305412 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505413 }
5414 } else {
5415 RTC_DCHECK(IsDataContent(&content));
5416 // If we already have an data m= section, reject this extra one.
5417 if (*data_index) {
5418 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235419 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:505420 } else {
5421 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235422 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:305423 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505424 }
5425 }
htaa2a49d92016-03-04 10:51:395426 }
deadbeefab9b2d12015-10-14 18:33:115427}
5428
Steve Antonfa2260d2017-12-29 00:38:235429cricket::MediaDescriptionOptions
5430PeerConnection::GetMediaDescriptionOptionsForActiveData(
5431 const std::string& mid) const {
5432 // Direction for data sections is meaningless, but legacy endpoints might
5433 // expect sendrecv.
5434 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5435 RtpTransceiverDirection::kSendRecv,
5436 /*stopped=*/false);
5437 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5438 return options;
5439}
5440
5441cricket::MediaDescriptionOptions
5442PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5443 const std::string& mid) const {
5444 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5445 RtpTransceiverDirection::kInactive,
5446 /*stopped=*/true);
5447 AddRtpDataChannelOptions(rtp_data_channels_, &options);
5448 return options;
5449}
5450
Danil Chapovalov66cadcc2018-06-19 14:47:435451absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:235452 switch (data_channel_type_) {
5453 case cricket::DCT_RTP:
5454 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435455 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:235456 }
5457 return rtp_data_channel_->content_name();
5458 case cricket::DCT_SCTP:
Bjorn Mellem175aa2e2018-11-08 19:23:225459 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellemb689af42019-08-21 17:44:595460 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5461 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
5462 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:235463 default:
Danil Chapovalov66cadcc2018-06-19 14:47:435464 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:235465 }
5466}
5467
Steve Anton4171afb2017-11-20 18:20:225468void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5469 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5470 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:405471 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:075472}
5473
Steve Anton4171afb2017-11-20 18:20:225474void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:115475 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:225476 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:115477 cricket::MediaType media_type,
5478 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:365479 RTC_DCHECK(!IsUnifiedPlan());
5480
Steve Anton4171afb2017-11-20 18:20:225481 std::vector<RtpSenderInfo>* current_senders =
5482 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:115483
Steve Anton4171afb2017-11-20 18:20:225484 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:015485 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:225486 for (auto sender_it = current_senders->begin();
5487 sender_it != current_senders->end();
5488 /* incremented manually */) {
5489 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:115490 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:225491 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:095492 std::string params_stream_id;
5493 if (params) {
5494 params_stream_id =
5495 (!params->first_stream_id().empty() ? params->first_stream_id()
5496 : kDefaultStreamId);
5497 }
Seth Hampson5b4f0752018-04-02 23:31:365498 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:095499 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:405500 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:105501 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:225502 sender_exists) {
5503 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:405504 } else {
Steve Anton4171afb2017-11-20 18:20:225505 OnRemoteSenderRemoved(info, media_type);
5506 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:115507 }
5508 }
5509
Steve Anton4171afb2017-11-20 18:20:225510 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:115511 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:335512 if (!params.has_ssrcs()) {
5513 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5514 // sender, this means it is coming from a Unified Plan endpoint,so we just
5515 // create a default.
5516 default_sender_needed = true;
5517 break;
5518 }
5519
Seth Hampson845e8782018-03-02 19:34:105520 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:365521 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:335522 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5523 // not supported in Plan B, we just take the first here and create the
5524 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:105525 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:095526 (!params.first_stream_id().empty() ? params.first_stream_id()
5527 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:225528 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:115529 uint32_t ssrc = params.first_ssrc();
5530
5531 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:105532 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:115533 if (!stream) {
5534 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:195535 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:105536 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:115537 remote_streams_->AddStream(stream);
5538 new_streams->AddStream(stream);
5539 }
5540
Steve Anton4171afb2017-11-20 18:20:225541 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185542 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:225543 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:105544 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:225545 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:115546 }
5547 }
deadbeefbda7e0b2015-12-09 01:13:405548
Steve Anton4171afb2017-11-20 18:20:225549 // Add default sender if necessary.
5550 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:405551 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:105552 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:405553 if (!default_stream) {
5554 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:195555 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:105556 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:405557 remote_streams_->AddStream(default_stream);
5558 new_streams->AddStream(default_stream);
5559 }
Steve Anton4171afb2017-11-20 18:20:225560 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5561 ? kDefaultAudioSenderId
5562 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:105563 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185564 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:225565 if (!default_sender_info) {
5566 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 01:07:055567 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 18:20:225568 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:405569 }
5570 }
deadbeefab9b2d12015-10-14 18:33:115571}
5572
Steve Anton4171afb2017-11-20 18:20:225573void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5574 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:235575 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5576 << " receiver for track_id=" << sender_info.sender_id
5577 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:115578
Steve Anton3d954a62018-04-02 18:27:235579 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:115580 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:225581 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:115582 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:225583 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:115584 } else {
nisseeb4ca4e2017-01-12 10:24:275585 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:115586 }
5587}
5588
Steve Anton4171afb2017-11-20 18:20:225589void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5590 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:095591 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5592 << " receiver for track_id=" << sender_info.sender_id
5593 << " and stream_id=" << sender_info.stream_id;
5594
Seth Hampson845e8782018-03-02 19:34:105595 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:115596
Henrik Boström933d8b02017-10-10 17:05:165597 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:115598 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:195599 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5600 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:225601 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:115602 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:225603 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:115604 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:115605 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:115606 }
5607 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:195608 // Stopping or destroying a VideoRtpReceiver will end the
5609 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:225610 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:115611 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:225612 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:115613 if (video_track) {
perkjd61bf802016-03-24 10:16:195614 // There's no guarantee the track is still available, e.g. the track may
5615 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:115616 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:115617 }
5618 } else {
nisseede5da42017-01-12 13:15:365619 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:115620 }
Henrik Boström933d8b02017-10-10 17:05:165621 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:165622 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:165623 }
deadbeefab9b2d12015-10-14 18:33:115624}
5625
5626void PeerConnection::UpdateEndedRemoteMediaStreams() {
5627 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5628 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5629 MediaStreamInterface* stream = remote_streams_->at(i);
5630 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5631 streams_to_remove.push_back(stream);
5632 }
5633 }
5634
Taylor Brandstetter98cde262016-05-31 20:02:215635 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:115636 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:165637 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:115638 }
5639}
5640
Steve Anton4171afb2017-11-20 18:20:225641void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:115642 const std::vector<cricket::StreamParams>& streams,
5643 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:225644 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:115645
Seth Hampson845e8782018-03-02 19:34:105646 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:115647 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:225648 for (auto sender_it = current_senders->begin();
5649 sender_it != current_senders->end();
5650 /* incremented manually */) {
5651 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:115652 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:225653 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5654 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:105655 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:225656 OnLocalSenderRemoved(info, media_type);
5657 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:115658 } else {
Steve Anton4171afb2017-11-20 18:20:225659 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:115660 }
5661 }
5662
Steve Anton4171afb2017-11-20 18:20:225663 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:115664 for (const cricket::StreamParams& params : streams) {
5665 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:225666 // sender id.
Seth Hampson845e8782018-03-02 19:34:105667 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:225668 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:115669 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:225670 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185671 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:225672 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:105673 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:225674 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:115675 }
5676 }
5677}
5678
Steve Anton4171afb2017-11-20 18:20:225679void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5680 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:365681 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:225682 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:015683 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:225684 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5685 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:255686 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:115687 return;
5688 }
5689
deadbeeffac06552015-11-25 19:26:015690 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:255691 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075692 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015693 return;
deadbeefab9b2d12015-10-14 18:33:115694 }
deadbeeffac06552015-11-25 19:26:015695
Henrik Andreasssoncc189172019-05-20 09:01:385696 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:225697 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:115698}
5699
Steve Anton4171afb2017-11-20 18:20:225700void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5701 cricket::MediaType media_type) {
5702 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:015703 if (!sender) {
5704 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:115705 // SessionDescriptions has been renegotiated.
5706 return;
5707 }
deadbeeffac06552015-11-25 19:26:015708
5709 // A sender has been removed from the SessionDescription but it's still
5710 // associated with the PeerConnection. This only occurs if the SDP doesn't
5711 // match with the calls to CreateSender, AddStream and RemoveStream.
5712 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:255713 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075714 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015715 return;
deadbeefab9b2d12015-10-14 18:33:115716 }
deadbeeffac06552015-11-25 19:26:015717
Steve Anton4171afb2017-11-20 18:20:225718 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:115719}
5720
5721void PeerConnection::UpdateLocalRtpDataChannels(
5722 const cricket::StreamParamsVec& streams) {
5723 std::vector<std::string> existing_channels;
5724
5725 // Find new and active data channels.
5726 for (const cricket::StreamParams& params : streams) {
5727 // |it->sync_label| is actually the data channel label. The reason is that
5728 // we use the same naming of data channels as we do for
5729 // MediaStreams and Tracks.
5730 // For MediaStreams, the sync_label is the MediaStream label and the
5731 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:105732 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:115733 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:565734 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:255735 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:115736 continue;
5737 }
5738 // Set the SSRC the data channel should use for sending.
5739 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5740 existing_channels.push_back(data_channel_it->first);
5741 }
5742
5743 UpdateClosingRtpDataChannels(existing_channels, true);
5744}
5745
5746void PeerConnection::UpdateRemoteRtpDataChannels(
5747 const cricket::StreamParamsVec& streams) {
5748 std::vector<std::string> existing_channels;
5749
5750 // Find new and active data channels.
5751 for (const cricket::StreamParams& params : streams) {
5752 // The data channel label is either the mslabel or the SSRC if the mslabel
5753 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:105754 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:115755 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:105756 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:115757 auto data_channel_it = rtp_data_channels_.find(label);
5758 if (data_channel_it == rtp_data_channels_.end()) {
5759 // This is a new data channel.
5760 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5761 } else {
5762 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5763 }
5764 existing_channels.push_back(label);
5765 }
5766
5767 UpdateClosingRtpDataChannels(existing_channels, false);
5768}
5769
5770void PeerConnection::UpdateClosingRtpDataChannels(
5771 const std::vector<std::string>& active_channels,
5772 bool is_local_update) {
5773 auto it = rtp_data_channels_.begin();
5774 while (it != rtp_data_channels_.end()) {
5775 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-29 01:25:265776 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 18:33:115777 ++it;
5778 continue;
5779 }
5780
5781 if (is_local_update) {
5782 data_channel->SetSendSsrc(0);
5783 } else {
5784 data_channel->RemotePeerRequestClose();
5785 }
5786
5787 if (data_channel->state() == DataChannel::kClosed) {
5788 rtp_data_channels_.erase(it);
5789 it = rtp_data_channels_.begin();
5790 } else {
5791 ++it;
5792 }
5793 }
5794}
5795
5796void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5797 uint32_t remote_ssrc) {
5798 rtc::scoped_refptr<DataChannel> channel(
5799 InternalCreateDataChannel(label, nullptr));
5800 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:255801 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:075802 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:115803 return;
5804 }
5805 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:395806 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5807 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:165808 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:115809}
5810
5811rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5812 const std::string& label,
5813 const InternalDataChannelInit* config) {
5814 if (IsClosed()) {
5815 return nullptr;
5816 }
Steve Anton75737c02017-11-06 18:37:175817 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:255818 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:115819 << "InternalCreateDataChannel: Data is not supported in this call.";
5820 return nullptr;
5821 }
5822 InternalDataChannelInit new_config =
5823 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 19:23:225824 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 18:33:115825 if (new_config.id < 0) {
5826 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:175827 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:115828 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:255829 RTC_LOG(LS_ERROR)
5830 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:115831 return nullptr;
5832 }
5833 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:255834 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:075835 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:115836 return nullptr;
5837 }
5838 }
5839
Steve Anton75737c02017-11-06 18:37:175840 rtc::scoped_refptr<DataChannel> channel(
5841 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:115842 if (!channel) {
5843 sid_allocator_.ReleaseSid(new_config.id);
5844 return nullptr;
5845 }
5846
5847 if (channel->data_channel_type() == cricket::DCT_RTP) {
5848 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:255849 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5850 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:115851 return nullptr;
5852 }
5853 rtp_data_channels_[channel->label()] = channel;
5854 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:225855 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 18:33:115856 sctp_data_channels_.push_back(channel);
5857 channel->SignalClosed.connect(this,
5858 &PeerConnection::OnSctpDataChannelClosed);
5859 }
5860
Steve Anton2d8609c2018-01-24 00:38:465861 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:115862 return channel;
5863}
5864
5865bool PeerConnection::HasDataChannels() const {
5866 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5867}
5868
5869void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 10:29:385870 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 18:33:115871 for (const auto& channel : sctp_data_channels_) {
5872 if (channel->id() < 0) {
5873 int sid;
5874 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 10:29:385875 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5876 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 18:33:115877 continue;
5878 }
5879 channel->SetSctpSid(sid);
5880 }
5881 }
Harald Alvestrand1f928d32019-03-28 10:29:385882 // Since closing modifies the list of channels, we have to do the actual
5883 // closing outside the loop.
5884 for (const auto& channel : channels_to_close) {
5885 channel->CloseAbruptly();
5886 }
deadbeefab9b2d12015-10-14 18:33:115887}
5888
5889void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:295890 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:115891 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5892 ++it) {
5893 if (it->get() == channel) {
5894 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:325895 // After the closing procedure is done, it's safe to use this ID for
5896 // another data channel.
deadbeefab9b2d12015-10-14 18:33:115897 sid_allocator_.ReleaseSid(channel->id());
5898 }
deadbeefbd292462015-12-15 02:15:295899 // Since this method is triggered by a signal from the DataChannel,
5900 // we can't free it directly here; we need to free it asynchronously.
5901 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:115902 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:405903 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5904 nullptr);
deadbeefab9b2d12015-10-14 18:33:115905 return;
5906 }
5907 }
5908}
5909
Harald Alvestrand408cb4b2019-11-16 11:09:085910void PeerConnection::OnTransportChannelClosed() {
deadbeefab9b2d12015-10-14 18:33:115911 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5912 // DataChannel may callback to us and try to modify the list.
5913 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5914 temp_rtp_dcs.swap(rtp_data_channels_);
5915 for (const auto& kv : temp_rtp_dcs) {
Harald Alvestrand408cb4b2019-11-16 11:09:085916 kv.second->OnTransportChannelClosed();
deadbeefab9b2d12015-10-14 18:33:115917 }
5918
5919 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5920 temp_sctp_dcs.swap(sctp_data_channels_);
5921 for (const auto& channel : temp_sctp_dcs) {
Harald Alvestrand408cb4b2019-11-16 11:09:085922 channel->OnTransportChannelClosed();
deadbeefab9b2d12015-10-14 18:33:115923 }
5924}
5925
5926void PeerConnection::OnDataChannelOpenMessage(
5927 const std::string& label,
5928 const InternalDataChannelInit& config) {
5929 rtc::scoped_refptr<DataChannel> channel(
5930 InternalCreateDataChannel(label, &config));
5931 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:255932 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:115933 return;
5934 }
5935
deadbeefa601f5c2016-06-06 21:27:395936 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5937 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:165938 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:415939 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:115940}
5941
Bjorn Mellem175aa2e2018-11-08 19:23:225942bool PeerConnection::HandleOpenMessage_s(
5943 const cricket::ReceiveDataParams& params,
5944 const rtc::CopyOnWriteBuffer& buffer) {
5945 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5946 // Received OPEN message; parse and signal that a new data channel should
5947 // be created.
5948 std::string label;
5949 InternalDataChannelInit config;
5950 config.id = params.ssrc;
5951 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5952 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5953 << params.ssrc;
5954 return true;
5955 }
5956 config.open_handshake_role = InternalDataChannelInit::kAcker;
5957 OnDataChannelOpenMessage(label, config);
5958 return true;
5959 }
5960 return false;
5961}
5962
Steve Anton4171afb2017-11-20 18:20:225963rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5964PeerConnection::GetAudioTransceiver() const {
5965 // This method only works with Plan B SDP, where there is a single
5966 // audio/video transceiver.
5967 RTC_DCHECK(!IsUnifiedPlan());
5968 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085969 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:225970 return transceiver;
5971 }
5972 }
5973 RTC_NOTREACHED();
5974 return nullptr;
5975}
5976
5977rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5978PeerConnection::GetVideoTransceiver() const {
5979 // This method only works with Plan B SDP, where there is a single
5980 // audio/video transceiver.
5981 RTC_DCHECK(!IsUnifiedPlan());
5982 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085983 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:225984 return transceiver;
5985 }
5986 }
5987 RTC_NOTREACHED();
5988 return nullptr;
5989}
5990
5991// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5992// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:505993bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:225994 switch (type) {
5995 case cricket::MEDIA_TYPE_AUDIO:
5996 return !GetAudioTransceiver()->internal()->senders().empty();
5997 case cricket::MEDIA_TYPE_VIDEO:
5998 return !GetVideoTransceiver()->internal()->senders().empty();
5999 case cricket::MEDIA_TYPE_DATA:
6000 return false;
6001 }
6002 RTC_NOTREACHED();
6003 return false;
zhihuang1c378ed2017-08-17 21:10:506004}
6005
Steve Anton4171afb2017-11-20 18:20:226006rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6007PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 16:29:426008 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:226009 for (auto sender : transceiver->internal()->senders()) {
6010 if (sender->track() == track) {
6011 return sender;
6012 }
6013 }
6014 }
6015 return nullptr;
deadbeeffac06552015-11-25 19:26:016016}
6017
Steve Anton4171afb2017-11-20 18:20:226018rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
6019PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 16:29:426020 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:226021 for (auto sender : transceiver->internal()->senders()) {
6022 if (sender->id() == sender_id) {
6023 return sender;
6024 }
6025 }
6026 }
6027 return nullptr;
deadbeef70ab1a12015-09-28 23:53:556028}
6029
Steve Anton4171afb2017-11-20 18:20:226030rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
6031PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 16:29:426032 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:226033 for (auto receiver : transceiver->internal()->receivers()) {
6034 if (receiver->id() == receiver_id) {
6035 return receiver;
6036 }
6037 }
6038 }
6039 return nullptr;
deadbeef70ab1a12015-09-28 23:53:556040}
6041
Steve Anton4171afb2017-11-20 18:20:226042std::vector<PeerConnection::RtpSenderInfo>*
6043PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
6044 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6045 media_type == cricket::MEDIA_TYPE_VIDEO);
6046 return (media_type == cricket::MEDIA_TYPE_AUDIO)
6047 ? &remote_audio_sender_infos_
6048 : &remote_video_sender_infos_;
6049}
6050
6051std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:116052 cricket::MediaType media_type) {
6053 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
6054 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:226055 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
6056 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:116057}
6058
Steve Anton4171afb2017-11-20 18:20:226059const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
6060 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:186061 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:226062 const std::string sender_id) const {
6063 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:186064 if (sender_info.stream_id == stream_id &&
6065 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:226066 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:116067 }
6068 }
6069 return nullptr;
6070}
6071
6072DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
6073 for (const auto& channel : sctp_data_channels_) {
6074 if (channel->id() == sid) {
6075 return channel;
6076 }
6077 }
6078 return nullptr;
6079}
6080
Karl Wibergfb3be392019-03-22 13:13:226081PeerConnection::InitializePortAllocatorResult
6082PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:076083 const cricket::ServerAddresses& stun_servers,
6084 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:116085 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 13:13:226086 RTC_DCHECK_RUN_ON(network_thread());
6087
Taylor Brandstetterf8e65772016-06-28 00:20:156088 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:116089 // To handle both internal and externally created port allocator, we will
6090 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 13:13:226091 int port_allocator_flags = port_allocator_->flags();
6092 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
6093 cricket::PORTALLOCATOR_ENABLE_IPV6 |
6094 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:116095 // If the disable-IPv6 flag was specified, we'll not override it
6096 // by experiment.
6097 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 13:13:226098 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:476099 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
6100 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 13:13:226101 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:116102 }
6103
zhihuangb09b3f92017-03-07 22:40:516104 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 13:13:226105 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:256106 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:516107 }
6108
Taylor Brandstettera1c30352016-05-13 15:15:116109 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 13:13:226110 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:256111 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:116112 }
6113
honghaiz60347052016-06-01 01:29:126114 if (configuration.candidate_network_policy ==
6115 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 13:13:226116 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:256117 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:126118 }
6119
Daniel Lazarenko2870b0a2018-01-25 09:30:226120 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 13:13:226121 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:226122 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
6123 }
6124
Karl Wibergfb3be392019-03-22 13:13:226125 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 15:15:116126 // No step delay is used while allocating ports.
6127 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 17:41:586128 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 15:15:116129 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:116130 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:116131
Harald Alvestrandb2a74782018-06-28 11:54:076132 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:266133 for (auto& turn_server : turn_servers_copy) {
6134 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:256135 }
Taylor Brandstettera1c30352016-05-13 15:15:116136 // Call this last since it may create pooled allocator sessions using the
6137 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:496138 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:266139 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 18:27:506140 configuration.ice_candidate_pool_size,
6141 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:496142 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 13:13:226143
6144 InitializePortAllocatorResult res;
6145 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
6146 return res;
Taylor Brandstettera1c30352016-05-13 15:15:116147}
6148
deadbeef91dd5672016-05-18 23:55:306149bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:306150 const cricket::ServerAddresses& stun_servers,
6151 const std::vector<cricket::RelayServerConfig>& turn_servers,
6152 IceTransportsType type,
6153 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:506154 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 22:45:496155 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:286156 absl::optional<int> stun_candidate_keepalive_interval,
6157 bool have_local_description) {
Qingsi Wangc129c352019-04-18 17:41:586158 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 20:28:306159 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:456160 // According to JSEP, after setLocalDescription, changing the candidate pool
6161 // size is not allowed, and changing the set of ICE servers will not result
6162 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 09:37:286163 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 23:57:456164 port_allocator_->FreezeCandidatePool();
6165 }
Benjamin Wright6f80f092018-08-14 00:06:266166 // Add the custom tls turn servers if they exist.
6167 auto turn_servers_copy = turn_servers;
6168 for (auto& turn_server : turn_servers_copy) {
6169 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
6170 }
Taylor Brandstettera1c30352016-05-13 15:15:116171 // Call this last since it may create pooled allocator sessions using the
6172 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:326173 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:266174 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:506175 turn_port_prune_policy, turn_customizer,
6176 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:116177}
6178
Steve Antonba818672017-11-06 18:21:576179cricket::ChannelManager* PeerConnection::channel_manager() const {
6180 return factory_->channel_manager();
6181}
6182
Elad Alon99c3fe52017-10-13 14:29:406183bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:146184 std::unique_ptr<RtcEventLogOutput> output,
6185 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 10:59:576186 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:166187 if (!event_log_) {
6188 return false;
6189 }
Bjorn Tereliusde939432017-11-20 16:38:146190 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:556191}
6192
6193void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 10:59:576194 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:166195 if (event_log_) {
6196 event_log_->StopLogging();
6197 }
ivoc14d5dbe2016-07-04 14:06:556198}
nisseeaabdf62017-05-05 09:23:026199
Amit Hilbuchdd9390c2018-11-14 00:26:056200cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:176201 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 16:29:426202 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056203 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:546204 if (channel && channel->content_name() == content_name) {
6205 return channel;
6206 }
Steve Anton75737c02017-11-06 18:37:176207 }
6208 if (rtp_data_channel() &&
6209 rtp_data_channel()->content_name() == content_name) {
6210 return rtp_data_channel();
6211 }
6212 return nullptr;
6213}
6214
6215bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 19:23:226216 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176217 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:256218 RTC_LOG(LS_INFO)
6219 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:076220 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:176221 return false;
6222 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546223 if (!data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:256224 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:076225 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:176226 return false;
6227 }
6228
Bjorn Mellem175aa2e2018-11-08 19:23:226229 absl::optional<rtc::SSLRole> dtls_role;
Bjorn A Mellembc3eebc2019-09-23 21:53:546230 if (sctp_mid_) {
Bjorn Mellem175aa2e2018-11-08 19:23:226231 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
Bjorn A Mellembc3eebc2019-09-23 21:53:546232 if (!dtls_role && is_caller_.has_value()) {
6233 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
6234 }
Zhi Huange830e682018-03-30 17:48:356235 *role = *dtls_role;
6236 return true;
6237 }
6238 return false;
Steve Anton75737c02017-11-06 18:37:176239}
6240
6241bool PeerConnection::GetSslRole(const std::string& content_name,
6242 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 09:31:566243 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176244 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:256245 RTC_LOG(LS_INFO)
6246 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:076247 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:176248 return false;
6249 }
6250
Zhi Huange830e682018-03-30 17:48:356251 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6252 if (dtls_role) {
6253 *role = *dtls_role;
6254 return true;
6255 }
6256 return false;
Steve Anton75737c02017-11-06 18:37:176257}
6258
Steve Antonf8470812017-12-04 18:46:216259void PeerConnection::SetSessionError(SessionError error,
6260 const std::string& error_desc) {
6261 RTC_DCHECK_RUN_ON(signaling_thread());
6262 if (error != session_error_) {
6263 session_error_ = error;
6264 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:176265 }
6266}
6267
Zhi Huange830e682018-03-30 17:48:356268RTCError PeerConnection::UpdateSessionState(
6269 SdpType type,
6270 cricket::ContentSource source,
6271 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:566272 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176273
6274 // If there's already a pending error then no state transition should happen.
6275 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:216276 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:476277
Steve Anton6d6a2ae2017-12-05 01:19:476278 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:516279 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:596280 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:476281 }
6282
6283 // Update the signaling state according to the specified state machine (see
6284 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:516285 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:476286 ChangeSignalingState(source == cricket::CS_LOCAL
6287 ? PeerConnectionInterface::kHaveLocalOffer
6288 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:516289 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:476290 ChangeSignalingState(source == cricket::CS_LOCAL
6291 ? PeerConnectionInterface::kHaveLocalPrAnswer
6292 : PeerConnectionInterface::kHaveRemotePrAnswer);
6293 } else {
Steve Anton3828c062017-12-06 18:34:516294 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:476295 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 15:29:446296 transceiver_stable_states_by_transceivers_.clear();
Steve Anton6d6a2ae2017-12-05 01:19:476297 }
6298
6299 // Update internal objects according to the session description's media
6300 // descriptions.
Zhi Huange830e682018-03-30 17:48:356301 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:476302 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:426303 return error;
Steve Anton6d6a2ae2017-12-05 01:19:476304 }
6305
Steve Anton8a006912017-12-04 23:25:566306 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176307}
6308
Steve Anton8a006912017-12-04 23:25:566309RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:516310 SdpType type,
Steve Anton8a006912017-12-04 23:25:566311 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:596312 const SessionDescriptionInterface* sdesc =
6313 (source == cricket::CS_LOCAL ? local_description()
6314 : remote_description());
Steve Anton75737c02017-11-06 18:37:176315 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:596316
6317 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 16:29:426318 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:176319 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:596320 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:056321 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:596322 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:176323 continue;
6324 }
6325 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:306326 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:596327 if (!content_desc) {
6328 continue;
6329 }
6330 std::string error;
Yves Gerey665174f2018-06-19 13:03:056331 bool success = (source == cricket::CS_LOCAL)
6332 ? channel->SetLocalContent(content_desc, type, &error)
6333 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:596334 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:576335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:596336 }
6337 }
6338
6339 // If using the RtpDataChannel, push down the new SDP section for it too.
6340 if (rtp_data_channel_) {
6341 const ContentInfo* data_content =
6342 cricket::GetFirstDataContent(sdesc->description());
6343 if (data_content && !data_content->rejected) {
6344 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:306345 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:596346 if (data_desc) {
6347 std::string error;
6348 bool success =
6349 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:516350 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:056351 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:596352 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:576353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:596354 }
Steve Anton75737c02017-11-06 18:37:176355 }
6356 }
6357 }
Steve Antoned10bd92017-12-05 18:52:596358
Steve Anton75737c02017-11-06 18:37:176359 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6360 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Bjorn A Mellembc3eebc2019-09-23 21:53:546361 if (sctp_mid_ && local_description() && remote_description()) {
6362 rtc::scoped_refptr<SctpTransport> sctp_transport =
6363 transport_controller_->GetSctpTransport(*sctp_mid_);
Harald Alvestrandfbb45bd2019-05-15 06:07:476364 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6365 local_description()->description());
6366 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6367 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 21:53:546368 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 09:49:176369 int max_message_size;
6370 // A remote max message size of zero means "any size supported".
6371 // We configure the connection with our own max message size.
6372 if (remote_sctp_description->max_message_size() == 0) {
6373 max_message_size = local_sctp_description->max_message_size();
6374 } else {
6375 max_message_size =
6376 std::min(local_sctp_description->max_message_size(),
6377 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 06:07:476378 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546379 sctp_transport->Start(local_sctp_description->port(),
6380 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 23:25:566381 }
Steve Anton75737c02017-11-06 18:37:176382 }
Steve Antoned10bd92017-12-05 18:52:596383
Steve Anton8a006912017-12-04 23:25:566384 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176385}
6386
Steve Anton8a006912017-12-04 23:25:566387RTCError PeerConnection::PushdownTransportDescription(
6388 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:516389 SdpType type) {
Steve Anton8a006912017-12-04 23:25:566390 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176391
Zhi Huange830e682018-03-30 17:48:356392 if (source == cricket::CS_LOCAL) {
6393 const SessionDescriptionInterface* sdesc = local_description();
6394 RTC_DCHECK(sdesc);
6395 return transport_controller_->SetLocalDescription(type,
6396 sdesc->description());
6397 } else {
6398 const SessionDescriptionInterface* sdesc = remote_description();
6399 RTC_DCHECK(sdesc);
6400 return transport_controller_->SetRemoteDescription(type,
6401 sdesc->description());
Steve Anton75737c02017-11-06 18:37:176402 }
Steve Anton75737c02017-11-06 18:37:176403}
6404
6405bool PeerConnection::GetTransportDescription(
6406 const SessionDescription* description,
6407 const std::string& content_name,
6408 cricket::TransportDescription* tdesc) {
6409 if (!description || !tdesc) {
6410 return false;
6411 }
6412 const TransportInfo* transport_info =
6413 description->GetTransportInfoByName(content_name);
6414 if (!transport_info) {
6415 return false;
6416 }
6417 *tdesc = transport_info->description;
6418 return true;
6419}
6420
Steve Anton75737c02017-11-06 18:37:176421cricket::IceConfig PeerConnection::ParseIceConfig(
6422 const PeerConnectionInterface::RTCConfiguration& config) const {
6423 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:176424 switch (config.continual_gathering_policy) {
6425 case PeerConnectionInterface::GATHER_ONCE:
6426 gathering_policy = cricket::GATHER_ONCE;
6427 break;
6428 case PeerConnectionInterface::GATHER_CONTINUALLY:
6429 gathering_policy = cricket::GATHER_CONTINUALLY;
6430 break;
6431 default:
6432 RTC_NOTREACHED();
6433 gathering_policy = cricket::GATHER_ONCE;
6434 }
Qingsi Wang9a5c6f82018-02-01 18:38:406435
Steve Anton75737c02017-11-06 18:37:176436 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:236437 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6438 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:176439 ice_config.prioritize_most_likely_candidate_pairs =
6440 config.prioritize_most_likely_ice_candidate_pairs;
6441 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:236442 RTCConfigurationToIceConfigOptionalInt(
6443 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:176444 ice_config.continual_gathering_policy = gathering_policy;
6445 ice_config.presume_writable_when_fully_relayed =
6446 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 23:55:336447 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6448 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 22:55:146449 ice_config.ice_check_interval_strong_connectivity =
6450 config.ice_check_interval_strong_connectivity;
6451 ice_config.ice_check_interval_weak_connectivity =
6452 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:176453 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-30 07:08:516454 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6455 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:176456 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:496457 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:176458 ice_config.regather_all_networks_interval_range =
6459 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:406460 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:176461 return ice_config;
6462}
6463
Steve Anton75737c02017-11-06 18:37:176464bool PeerConnection::SendData(const cricket::SendDataParams& params,
6465 const rtc::CopyOnWriteBuffer& payload,
6466 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 09:31:566467 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 21:53:546468 if (data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 19:23:226469 SendDataParams send_params;
6470 send_params.type = ToWebrtcDataMessageType(params.type);
6471 send_params.ordered = params.ordered;
6472 if (params.max_rtx_count >= 0) {
6473 send_params.max_rtx_count = params.max_rtx_count;
6474 } else if (params.max_rtx_ms >= 0) {
6475 send_params.max_rtx_ms = params.max_rtx_ms;
6476 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546477
6478 RTCError error = network_thread()->Invoke<RTCError>(
6479 RTC_FROM_HERE, [this, params, send_params, payload] {
6480 return data_channel_transport_->SendData(params.sid, send_params,
6481 payload);
6482 });
6483
6484 if (error.ok()) {
6485 *result = cricket::SendDataResult::SDR_SUCCESS;
6486 return true;
6487 } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
6488 // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
6489 // TODO(mellem): Stop using RTCError here and get rid of the mapping.
6490 *result = cricket::SendDataResult::SDR_BLOCK;
6491 return false;
6492 }
6493 *result = cricket::SendDataResult::SDR_ERROR;
6494 return false;
Bjorn A Mellemb689af42019-08-21 17:44:596495 } else if (rtp_data_channel_) {
6496 return rtp_data_channel_->SendData(params, payload, result);
Bjorn Mellem175aa2e2018-11-08 19:23:226497 }
Bjorn A Mellemb689af42019-08-21 17:44:596498 RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
6499 return false;
Steve Anton75737c02017-11-06 18:37:176500}
6501
6502bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:226503 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 21:53:546504 if (!rtp_data_channel_ && !data_channel_transport_) {
Steve Anton75737c02017-11-06 18:37:176505 // Don't log an error here, because DataChannels are expected to call
6506 // ConnectDataChannel in this state. It's the only way to initially tell
6507 // whether or not the underlying transport is ready.
6508 return false;
6509 }
Bjorn A Mellemb689af42019-08-21 17:44:596510 if (data_channel_transport_) {
6511 SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
6512 &DataChannel::OnChannelReady);
6513 SignalDataChannelTransportReceivedData_s.connect(
6514 webrtc_data_channel, &DataChannel::OnDataReceived);
6515 SignalDataChannelTransportChannelClosing_s.connect(
Bjorn Mellem175aa2e2018-11-08 19:23:226516 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
Bjorn A Mellemb689af42019-08-21 17:44:596517 SignalDataChannelTransportChannelClosed_s.connect(
Bjorn Mellem175aa2e2018-11-08 19:23:226518 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Bjorn A Mellemb689af42019-08-21 17:44:596519 }
6520 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:176521 rtp_data_channel_->SignalReadyToSendData.connect(
6522 webrtc_data_channel, &DataChannel::OnChannelReady);
6523 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
6524 &DataChannel::OnDataReceived);
Bjorn A Mellemb689af42019-08-21 17:44:596525 }
Steve Anton75737c02017-11-06 18:37:176526 return true;
6527}
6528
6529void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:226530 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellembc3eebc2019-09-23 21:53:546531 if (!rtp_data_channel_ && !data_channel_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:256532 RTC_LOG(LS_ERROR)
6533 << "DisconnectDataChannel called when rtp_data_channel_ and "
6534 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:176535 return;
6536 }
Bjorn A Mellemb689af42019-08-21 17:44:596537 if (data_channel_transport_) {
6538 SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
6539 SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
6540 SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
6541 SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
6542 }
6543 if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:176544 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
6545 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
Bjorn A Mellemb689af42019-08-21 17:44:596546 }
Steve Anton75737c02017-11-06 18:37:176547}
6548
6549void PeerConnection::AddSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 17:44:596550 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 21:53:546551 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6552 if (data_channel_transport_) {
6553 data_channel_transport_->OpenChannel(sid);
6554 }
6555 });
Bjorn Mellem175aa2e2018-11-08 19:23:226556 }
Steve Anton75737c02017-11-06 18:37:176557}
6558
6559void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn A Mellemb689af42019-08-21 17:44:596560 if (data_channel_transport_) {
Bjorn A Mellembc3eebc2019-09-23 21:53:546561 network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
6562 if (data_channel_transport_) {
6563 data_channel_transport_->CloseChannel(sid);
6564 }
6565 });
Bjorn Mellem175aa2e2018-11-08 19:23:226566 }
Steve Anton75737c02017-11-06 18:37:176567}
6568
6569bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 19:23:226570 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176571 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn A Mellembc3eebc2019-09-23 21:53:546572 (data_channel_transport_ && data_channel_transport_ready_to_send_);
Steve Anton75737c02017-11-06 18:37:176573}
6574
Bjorn Mellem175aa2e2018-11-08 19:23:226575void PeerConnection::OnDataReceived(int channel_id,
6576 DataMessageType type,
6577 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 09:37:286578 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 19:23:226579 cricket::ReceiveDataParams params;
6580 params.sid = channel_id;
6581 params.type = ToCricketDataMessageType(type);
Bjorn A Mellemb689af42019-08-21 17:44:596582 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 19:23:226583 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6584 RTC_DCHECK_RUN_ON(signaling_thread());
6585 if (!HandleOpenMessage_s(params, buffer)) {
Bjorn A Mellemb689af42019-08-21 17:44:596586 SignalDataChannelTransportReceivedData_s(params, buffer);
Bjorn Mellem175aa2e2018-11-08 19:23:226587 }
6588 });
6589}
6590
6591void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 09:37:286592 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 17:44:596593 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 19:23:226594 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6595 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 17:44:596596 SignalDataChannelTransportChannelClosing_s(channel_id);
Bjorn Mellem175aa2e2018-11-08 19:23:226597 });
6598}
6599
6600void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 09:37:286601 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 17:44:596602 data_channel_transport_invoker_->AsyncInvoke<void>(
Bjorn Mellem175aa2e2018-11-08 19:23:226603 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6604 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn A Mellemb689af42019-08-21 17:44:596605 SignalDataChannelTransportChannelClosed_s(channel_id);
6606 });
6607}
6608
6609void PeerConnection::OnReadyToSend() {
6610 RTC_DCHECK_RUN_ON(network_thread());
6611 data_channel_transport_invoker_->AsyncInvoke<void>(
6612 RTC_FROM_HERE, signaling_thread(), [this] {
6613 RTC_DCHECK_RUN_ON(signaling_thread());
6614 data_channel_transport_ready_to_send_ = true;
Bjorn A Mellembc3eebc2019-09-23 21:53:546615 SignalDataChannelTransportWritable_s(
6616 data_channel_transport_ready_to_send_);
Bjorn Mellem175aa2e2018-11-08 19:23:226617 });
6618}
6619
Danil Chapovalov66cadcc2018-06-19 14:47:436620absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 09:31:566621 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 17:48:356622 if (sctp_mid_ && transport_controller_) {
6623 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6624 if (dtls_transport) {
6625 return dtls_transport->transport_name();
6626 }
Danil Chapovalov66cadcc2018-06-19 14:47:436627 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:356628 }
Danil Chapovalov66cadcc2018-06-19 14:47:436629 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:356630}
6631
Qingsi Wang72a43a12018-02-21 00:03:186632cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6633 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:456634 network_thread()->Invoke<void>(
6635 RTC_FROM_HERE,
6636 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6637 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:186638 return candidate_states_list;
6639}
6640
Steve Anton5dfde182018-02-06 18:34:406641std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6642 const {
Karl Wiberga58e1692019-03-26 12:33:436643 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 18:34:406644 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 16:29:426645 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056646 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:406647 if (channel) {
6648 transport_names_by_mid[channel->content_name()] =
6649 channel->transport_name();
6650 }
Steve Anton75737c02017-11-06 18:37:176651 }
Steve Anton5dfde182018-02-06 18:34:406652 if (rtp_data_channel_) {
6653 transport_names_by_mid[rtp_data_channel_->content_name()] =
6654 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:176655 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546656 if (data_channel_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:436657 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356658 RTC_DCHECK(transport_name);
6659 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:176660 }
Steve Anton5dfde182018-02-06 18:34:406661 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:176662}
6663
Steve Anton5dfde182018-02-06 18:34:406664std::map<std::string, cricket::TransportStats>
6665PeerConnection::GetTransportStatsByNames(
6666 const std::set<std::string>& transport_names) {
6667 if (!network_thread()->IsCurrent()) {
6668 return network_thread()
6669 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6670 RTC_FROM_HERE,
6671 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:176672 }
Karl Wiberg2cc368f2019-04-02 09:31:566673 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 18:34:406674 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6675 for (const std::string& transport_name : transport_names) {
6676 cricket::TransportStats transport_stats;
6677 bool success =
6678 transport_controller_->GetStats(transport_name, &transport_stats);
6679 if (success) {
6680 transport_stats_by_name[transport_name] = std::move(transport_stats);
6681 } else {
6682 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6683 << transport_name;
6684 }
6685 }
6686 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:176687}
6688
6689bool PeerConnection::GetLocalCertificate(
6690 const std::string& transport_name,
6691 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:356692 if (!certificate) {
6693 return false;
6694 }
6695 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6696 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:176697}
6698
Taylor Brandstetterc3928662018-02-23 21:04:516699std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:176700 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:516701 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:176702}
6703
6704cricket::DataChannelType PeerConnection::data_channel_type() const {
6705 return data_channel_type_;
6706}
6707
6708bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 13:36:536709 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176710 return pending_ice_restarts_.find(content_name) !=
6711 pending_ice_restarts_.end();
6712}
6713
Steve Anton75737c02017-11-06 18:37:176714bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6715 return transport_controller_->NeedsIceRestart(content_name);
6716}
6717
6718void PeerConnection::OnCertificateReady(
6719 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6720 transport_controller_->SetLocalCertificate(certificate);
6721}
6722
6723void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:216724 SetSessionError(SessionError::kTransport,
6725 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:176726}
6727
Alex Loiko9289eda2018-11-23 16:18:596728void PeerConnection::OnTransportControllerConnectionState(
6729 cricket::IceConnectionState state) {
6730 switch (state) {
6731 case cricket::kIceConnectionConnecting:
6732 // If the current state is Connected or Completed, then there were
6733 // writable channels but now there are not, so the next state must
6734 // be Disconnected.
6735 // kIceConnectionConnecting is currently used as the default,
6736 // un-connected state by the TransportController, so its only use is
6737 // detecting disconnections.
6738 if (ice_connection_state_ ==
6739 PeerConnectionInterface::kIceConnectionConnected ||
6740 ice_connection_state_ ==
6741 PeerConnectionInterface::kIceConnectionCompleted) {
6742 SetIceConnectionState(
6743 PeerConnectionInterface::kIceConnectionDisconnected);
6744 }
6745 break;
6746 case cricket::kIceConnectionFailed:
6747 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6748 break;
6749 case cricket::kIceConnectionConnected:
6750 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6751 "all transports are writable.";
6752 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6753 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6754 break;
6755 case cricket::kIceConnectionCompleted:
6756 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6757 "all transports are complete.";
6758 if (ice_connection_state_ !=
6759 PeerConnectionInterface::kIceConnectionConnected) {
6760 // If jumping directly from "checking" to "connected",
6761 // signal "connected" first.
6762 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6763 }
6764 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6765 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6766 ReportTransportStats();
6767 break;
6768 default:
6769 RTC_NOTREACHED();
6770 }
6771}
6772
Steve Anton75737c02017-11-06 18:37:176773void PeerConnection::OnTransportControllerCandidatesGathered(
6774 const std::string& transport_name,
6775 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 18:37:176776 int sdp_mline_index;
6777 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:256778 RTC_LOG(LS_ERROR)
6779 << "OnTransportControllerCandidatesGathered: content name "
6780 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:176781 return;
6782 }
6783
6784 for (cricket::Candidates::const_iterator citer = candidates.begin();
6785 citer != candidates.end(); ++citer) {
6786 // Use transport_name as the candidate media id.
6787 std::unique_ptr<JsepIceCandidate> candidate(
6788 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6789 if (local_description()) {
6790 mutable_local_description()->AddCandidate(candidate.get());
6791 }
6792 OnIceCandidate(std::move(candidate));
6793 }
6794}
6795
Eldar Relloda13ea22019-06-01 09:23:436796void PeerConnection::OnTransportControllerCandidateError(
6797 const cricket::IceCandidateErrorEvent& event) {
6798 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6799 event.error_text);
6800}
6801
Steve Anton75737c02017-11-06 18:37:176802void PeerConnection::OnTransportControllerCandidatesRemoved(
6803 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 18:37:176804 // Sanity check.
6805 for (const cricket::Candidate& candidate : candidates) {
6806 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:256807 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:076808 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:256809 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:176810 return;
6811 }
6812 }
6813
6814 if (local_description()) {
6815 mutable_local_description()->RemoveCandidates(candidates);
6816 }
6817 OnIceCandidatesRemoved(candidates);
6818}
6819
Alex Drake00c7ecf2019-08-06 17:54:476820void PeerConnection::OnTransportControllerCandidateChanged(
6821 const cricket::CandidatePairChangeEvent& event) {
6822 OnSelectedCandidatePairChanged(event);
6823}
6824
Steve Anton75737c02017-11-06 18:37:176825void PeerConnection::OnTransportControllerDtlsHandshakeError(
6826 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:536827 RTC_HISTOGRAM_ENUMERATION(
6828 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6829 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:176830}
6831
Steve Antoned10bd92017-12-05 18:52:596832void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 16:29:426833 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056834 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:596835 if (channel && !channel->enabled()) {
6836 channel->Enable(true);
6837 }
Steve Anton75737c02017-11-06 18:37:176838 }
6839
Steve Anton4171afb2017-11-20 18:20:226840 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:176841 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:226842 }
Steve Anton75737c02017-11-06 18:37:176843}
6844
6845// Returns the media index for a local ice candidate given the content name.
6846bool PeerConnection::GetLocalCandidateMediaIndex(
6847 const std::string& content_name,
6848 int* sdp_mline_index) {
6849 if (!local_description() || !sdp_mline_index) {
6850 return false;
6851 }
6852
6853 bool content_found = false;
6854 const ContentInfos& contents = local_description()->description()->contents();
6855 for (size_t index = 0; index < contents.size(); ++index) {
6856 if (contents[index].name == content_name) {
6857 *sdp_mline_index = static_cast<int>(index);
6858 content_found = true;
6859 break;
6860 }
6861 }
6862 return content_found;
6863}
6864
6865bool PeerConnection::UseCandidatesInSessionDescription(
6866 const SessionDescriptionInterface* remote_desc) {
6867 if (!remote_desc) {
6868 return true;
6869 }
6870 bool ret = true;
6871
6872 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6873 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6874 for (size_t n = 0; n < candidates->count(); ++n) {
6875 const IceCandidateInterface* candidate = candidates->at(n);
6876 bool valid = false;
6877 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6878 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:256879 RTC_LOG(LS_INFO)
6880 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:076881 "candidate.";
Steve Anton75737c02017-11-06 18:37:176882 }
6883 continue;
6884 }
6885 ret = UseCandidate(candidate);
6886 if (!ret) {
6887 break;
6888 }
6889 }
6890 }
6891 return ret;
6892}
6893
6894bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 18:12:296895 RTCErrorOr<const cricket::ContentInfo*> result =
6896 FindContentInfo(remote_description(), candidate);
6897 if (!result.ok()) {
6898 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6899 << result.error().message();
Steve Anton75737c02017-11-06 18:37:176900 return false;
6901 }
Steve Anton75737c02017-11-06 18:37:176902 std::vector<cricket::Candidate> candidates;
6903 candidates.push_back(candidate->candidate());
6904 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 18:12:296905 RTCError error = transport_controller_->AddRemoteCandidates(
6906 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:506907 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 18:57:176908 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:506909 // Candidates successfully submitted for checking.
6910 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6911 ice_connection_state_ ==
6912 PeerConnectionInterface::kIceConnectionDisconnected) {
6913 // If state is New, then the session has just gotten its first remote ICE
6914 // candidates, so go to Checking.
6915 // If state is Disconnected, the session is re-using old candidates or
6916 // receiving additional ones, so go to Checking.
6917 // If state is Connected, stay Connected.
6918 // TODO(bemasc): If state is Connected, and the new candidates are for a
6919 // newly added transport, then the state actually _should_ move to
6920 // checking. Add a way to distinguish that case.
6921 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6922 }
6923 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:076924 } else {
Zhi Huange830e682018-03-30 17:48:356925 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:176926 }
6927 return true;
6928}
6929
Guido Urdaneta41633172019-05-23 18:12:296930RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6931 const SessionDescriptionInterface* description,
6932 const IceCandidateInterface* candidate) {
6933 if (candidate->sdp_mline_index() >= 0) {
6934 size_t mediacontent_index =
6935 static_cast<size_t>(candidate->sdp_mline_index());
6936 size_t content_size = description->description()->contents().size();
6937 if (mediacontent_index < content_size) {
6938 return &description->description()->contents()[mediacontent_index];
6939 } else {
6940 return RTCError(RTCErrorType::INVALID_RANGE,
6941 "Media line index (" +
6942 rtc::ToString(candidate->sdp_mline_index()) +
6943 ") out of range (number of mlines: " +
6944 rtc::ToString(content_size) + ").");
6945 }
6946 } else if (!candidate->sdp_mid().empty()) {
6947 auto& contents = description->description()->contents();
6948 auto it = absl::c_find_if(
6949 contents, [candidate](const cricket::ContentInfo& content_info) {
6950 return content_info.mid() == candidate->sdp_mid();
6951 });
6952 if (it == contents.end()) {
6953 return RTCError(
6954 RTCErrorType::INVALID_PARAMETER,
6955 "Mid " + candidate->sdp_mid() +
6956 " specified but no media section with that mid found.");
6957 } else {
6958 return &*it;
6959 }
6960 }
6961
6962 return RTCError(RTCErrorType::INVALID_PARAMETER,
6963 "Neither sdp_mline_index nor sdp_mid specified.");
6964}
6965
Steve Anton75737c02017-11-06 18:37:176966void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:176967 // Destroy video channel first since it may have a pointer to the
6968 // voice channel.
6969 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:296970 if (!video_info || video_info->rejected) {
6971 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:176972 }
6973
Steve Anton6fec8802017-12-04 18:37:296974 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6975 if (!audio_info || audio_info->rejected) {
6976 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:176977 }
6978
6979 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6980 if (!data_info || data_info->rejected) {
Harald Alvestrand408cb4b2019-11-16 11:09:086981 DestroyDataChannelTransport();
Steve Anton75737c02017-11-06 18:37:176982 }
6983}
6984
Steve Antondcc3c022017-12-23 00:02:546985RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6986 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:176987 const cricket::ContentGroup* bundle_group = nullptr;
6988 if (configuration_.bundle_policy ==
6989 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:546990 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:176991 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:566992 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6993 "max-bundle configured but session description "
6994 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:176995 }
6996 }
Mirko Bonadei9f3a44f2019-01-30 12:47:426997 return bundle_group;
Steve Antondcc3c022017-12-23 00:02:546998}
6999
7000RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:357001 // Creating the media channels. Transports should already have been created
7002 // at this point.
Steve Antondcc3c022017-12-23 00:02:547003 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:557004 if (voice && !voice->rejected &&
7005 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:357006 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:557007 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:567008 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7009 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:557010 }
7011 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
7012 }
7013
Steve Antondcc3c022017-12-23 00:02:547014 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:557015 if (video && !video->rejected &&
7016 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:357017 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:557018 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:567019 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7020 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:177021 }
Steve Antoneda6ccd2017-12-04 18:21:557022 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:177023 }
7024
Steve Antondcc3c022017-12-23 00:02:547025 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:177026 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn A Mellembc3eebc2019-09-23 21:53:547027 !rtp_data_channel_ && !data_channel_transport_) {
Zhi Huange830e682018-03-30 17:48:357028 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:567029 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
7030 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:177031 }
7032 }
7033
Steve Anton8a006912017-12-04 23:25:567034 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:177035}
7036
Steve Anton4171afb2017-11-20 18:20:227037// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:557038cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:357039 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:427040 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 22:50:387041 MediaTransportConfig media_transport_config =
7042 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 20:15:427043
Steve Anton75737c02017-11-06 18:37:177044 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 18:12:577045 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 22:50:387046 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7047 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 18:37:177048 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:557049 return nullptr;
Steve Anton75737c02017-11-06 18:37:177050 }
Steve Anton75737c02017-11-06 18:37:177051 voice_channel->SignalDtlsSrtpSetupFailure.connect(
7052 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:177053 voice_channel->SignalSentPacket.connect(this,
7054 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:357055 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:227056
Steve Antoneda6ccd2017-12-04 18:21:557057 return voice_channel;
Steve Anton75737c02017-11-06 18:37:177058}
7059
Steve Anton4171afb2017-11-20 18:20:227060// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:557061cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:357062 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:427063 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 22:50:387064 MediaTransportConfig media_transport_config =
7065 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 20:15:427066
Steve Anton75737c02017-11-06 18:37:177067 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 18:12:577068 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 22:50:387069 media_transport_config, signaling_thread(), mid, SrtpRequired(),
7070 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 18:12:577071 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 18:37:177072 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:557073 return nullptr;
Steve Anton75737c02017-11-06 18:37:177074 }
Steve Anton75737c02017-11-06 18:37:177075 video_channel->SignalDtlsSrtpSetupFailure.connect(
7076 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:177077 video_channel->SignalSentPacket.connect(this,
7078 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:357079 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:227080
Steve Antoneda6ccd2017-12-04 18:21:557081 return video_channel;
Steve Anton75737c02017-11-06 18:37:177082}
7083
Zhi Huange830e682018-03-30 17:48:357084bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 19:23:227085 switch (data_channel_type_) {
Bjorn Mellem175aa2e2018-11-08 19:23:227086 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:267087 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:267088 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
7089 case cricket::DCT_MEDIA_TRANSPORT:
Bjorn A Mellembc3eebc2019-09-23 21:53:547090 if (!network_thread()->Invoke<bool>(
7091 RTC_FROM_HERE,
7092 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
7093 mid))) {
Qingsi Wang437077d2019-09-10 17:52:267094 return false;
7095 }
Bjorn A Mellembc3eebc2019-09-23 21:53:547096
7097 // All non-RTP data channels must initialize |sctp_data_channels_|.
7098 for (const auto& channel : sctp_data_channels_) {
7099 channel->OnTransportChannelCreated();
7100 }
7101 return true;
Bjorn Mellem175aa2e2018-11-08 19:23:227102 case cricket::DCT_RTP:
7103 default:
7104 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
7105 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
7106 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-26 01:13:567107 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 19:23:227108 if (!rtp_data_channel_) {
7109 return false;
7110 }
7111 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
7112 this, &PeerConnection::OnDtlsSrtpSetupFailure);
7113 rtp_data_channel_->SignalSentPacket.connect(
7114 this, &PeerConnection::OnSentPacket_w);
7115 rtp_data_channel_->SetRtpTransport(rtp_transport);
7116 return true;
Steve Anton75737c02017-11-06 18:37:177117 }
Bjorn A Mellembc3eebc2019-09-23 21:53:547118 return false;
Steve Anton75737c02017-11-06 18:37:177119}
7120
7121Call::Stats PeerConnection::GetCallStats() {
7122 if (!worker_thread()->IsCurrent()) {
7123 return worker_thread()->Invoke<Call::Stats>(
7124 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
7125 }
Karl Wiberg6cab5c82019-03-26 08:57:017126 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:177127 if (call_) {
7128 return call_->GetStats();
7129 } else {
7130 return Call::Stats();
7131 }
7132}
7133
Bjorn A Mellemb689af42019-08-21 17:44:597134bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 21:53:547135 DataChannelTransportInterface* transport =
7136 transport_controller_->GetDataChannelTransport(mid);
7137 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:057138 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 17:44:597139 << "Data channel transport is not available for data channels, mid="
7140 << mid;
Bjorn Mellem175aa2e2018-11-08 19:23:227141 return false;
7142 }
Bjorn A Mellemb689af42019-08-21 17:44:597143 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 19:23:227144
Bjorn A Mellembc3eebc2019-09-23 21:53:547145 data_channel_transport_ = transport;
Mirko Bonadei317a1f02019-09-17 15:06:187146 data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
Bjorn A Mellemb689af42019-08-21 17:44:597147 sctp_mid_ = mid;
Bjorn A Mellembc3eebc2019-09-23 21:53:547148
7149 // Note: setting the data sink and checking initial state must be done last,
7150 // after setting up the data channel. Setting the data sink may trigger
7151 // callbacks to PeerConnection which require the transport to be completely
7152 // set up (eg. OnReadyToSend()).
7153 transport->SetDataSink(this);
Bjorn Mellem175aa2e2018-11-08 19:23:227154 return true;
7155}
7156
Bjorn A Mellemb689af42019-08-21 17:44:597157void PeerConnection::TeardownDataChannelTransport_n() {
Bjorn A Mellembc3eebc2019-09-23 21:53:547158 if (!sctp_mid_ && !data_channel_transport_) {
Bjorn Mellem175aa2e2018-11-08 19:23:227159 return;
7160 }
Bjorn A Mellemb689af42019-08-21 17:44:597161 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
7162 << *sctp_mid_;
7163
Bjorn A Mellemb689af42019-08-21 17:44:597164 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
7165 // it.
Bjorn A Mellembc3eebc2019-09-23 21:53:547166 sctp_mid_.reset();
Qingsi Wang437077d2019-09-10 17:52:267167 data_channel_transport_invoker_ = nullptr;
Bjorn A Mellembc3eebc2019-09-23 21:53:547168 if (data_channel_transport_) {
7169 data_channel_transport_->SetDataSink(nullptr);
7170 }
Bjorn A Mellemb689af42019-08-21 17:44:597171 data_channel_transport_ = nullptr;
Bjorn Mellem175aa2e2018-11-08 19:23:227172}
7173
Steve Anton75737c02017-11-06 18:37:177174// Returns false if bundle is enabled and rtcp_mux is disabled.
7175bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
7176 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
7177 if (!bundle_enabled)
7178 return true;
7179
7180 const cricket::ContentGroup* bundle_group =
7181 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
7182 RTC_DCHECK(bundle_group != NULL);
7183
7184 const cricket::ContentInfos& contents = desc->contents();
7185 for (cricket::ContentInfos::const_iterator citer = contents.begin();
7186 citer != contents.end(); ++citer) {
7187 const cricket::ContentInfo* content = (&*citer);
7188 RTC_DCHECK(content != NULL);
7189 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:007190 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:177191 if (!HasRtcpMuxEnabled(content))
7192 return false;
7193 }
7194 }
7195 // RTCP-MUX is enabled in all the contents.
7196 return true;
7197}
7198
7199bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:307200 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:177201}
7202
Steve Anton06817cd2018-12-18 23:55:307203static RTCError ValidateMids(const cricket::SessionDescription& description) {
7204 std::set<std::string> mids;
7205 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 19:32:207206 if (content.name.empty()) {
7207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7208 "A media section is missing a MID attribute.");
7209 }
Steve Anton06817cd2018-12-18 23:55:307210 if (!mids.insert(content.name).second) {
7211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7212 "Duplicate a=mid value '" + content.name + "'.");
7213 }
7214 }
7215 return RTCError::OK();
7216}
7217
Steve Anton8a006912017-12-04 23:25:567218RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:177219 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:567220 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:217221 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:567222 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:177223 }
7224
7225 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:567226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:177227 }
7228
Steve Anton3828c062017-12-06 18:34:517229 SdpType type = sdesc->GetType();
7230 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
7231 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:567232 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:037233 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:567234 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:177235 }
7236
Steve Anton06817cd2018-12-18 23:55:307237 RTCError error = ValidateMids(*sdesc->description());
7238 if (!error.ok()) {
7239 return error;
7240 }
7241
Steve Anton75737c02017-11-06 18:37:177242 // Verify crypto settings.
7243 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:567244 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
7245 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:537246 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:567247 if (!crypto_error.ok()) {
7248 return crypto_error;
7249 }
Steve Anton75737c02017-11-06 18:37:177250 }
7251
7252 // Verify ice-ufrag and ice-pwd.
7253 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:567254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7255 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:177256 }
7257
7258 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:567259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7260 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:177261 }
7262
7263 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
7264 // m-lines that do not rtcp-mux enabled.
7265
7266 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:517267 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:487268 // With an answer we want to compare the new answer session description with
7269 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:177270 const cricket::SessionDescription* offer_desc =
7271 (source == cricket::CS_LOCAL) ? remote_description()->description()
7272 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:487273 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
7274 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
7275 type)) {
Steve Anton8a006912017-12-04 23:25:567276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7277 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:177278 }
7279 } else {
Steve Anton75737c02017-11-06 18:37:177280 // The re-offers should respect the order of m= sections in current
7281 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:487282 // With a re-offer, either the current local or current remote descriptions
7283 // could be the most up to date, so we would like to check against both of
7284 // them if they exist. It could be the case that one of them has a 0 port
7285 // for a media section, but the other does not. This is important to check
7286 // against in the case that we are recycling an m= section.
7287 const cricket::SessionDescription* current_desc = nullptr;
7288 const cricket::SessionDescription* secondary_current_desc = nullptr;
7289 if (local_description()) {
7290 current_desc = local_description()->description();
7291 if (remote_description()) {
7292 secondary_current_desc = remote_description()->description();
7293 }
7294 } else if (remote_description()) {
7295 current_desc = remote_description()->description();
7296 }
Steve Anton75737c02017-11-06 18:37:177297 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:487298 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
7299 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:567300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7301 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:177302 }
7303 }
7304
Steve Antonba42e992018-04-09 21:10:017305 if (IsUnifiedPlan()) {
7306 // Ensure that each audio and video media section has at most one
7307 // "StreamParams". This will return an error if receiving a session
7308 // description from a "Plan B" endpoint which adds multiple tracks of the
7309 // same type. With Unified Plan, there can only be at most one track per
7310 // media section.
7311 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 18:35:457312 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 21:10:017313 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
7314 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
7315 desc.streams().size() > 1u) {
7316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
7317 "Media section has more than one track specified "
7318 "with a=ssrc lines which is not supported with "
7319 "Unified Plan.");
7320 }
7321 }
7322 }
7323
Steve Anton8a006912017-12-04 23:25:567324 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:177325}
7326
Steve Anton3828c062017-12-06 18:34:517327bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:177328 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:517329 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:177330 return (state == PeerConnectionInterface::kStable) ||
7331 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:527332 } else {
Steve Anton3828c062017-12-06 18:34:517333 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:177334 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
7335 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
7336 }
7337}
7338
Steve Anton3828c062017-12-06 18:34:517339bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:177340 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:517341 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:177342 return (state == PeerConnectionInterface::kStable) ||
7343 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:527344 } else {
Steve Anton3828c062017-12-06 18:34:517345 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:177346 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
7347 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
7348 }
7349}
7350
Steve Antonf8470812017-12-04 18:46:217351const char* PeerConnection::SessionErrorToString(SessionError error) const {
7352 switch (error) {
7353 case SessionError::kNone:
7354 return "ERROR_NONE";
7355 case SessionError::kContent:
7356 return "ERROR_CONTENT";
7357 case SessionError::kTransport:
7358 return "ERROR_TRANSPORT";
7359 }
7360 RTC_NOTREACHED();
7361 return "";
7362}
7363
Steve Anton75737c02017-11-06 18:37:177364std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:307365 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:217366 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
7367 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:327368 return desc.Release();
Steve Anton75737c02017-11-06 18:37:177369}
7370
Steve Anton8e20f172018-03-06 18:55:047371void PeerConnection::ReportSdpFormatReceived(
7372 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:047373 int num_audio_mlines = 0;
7374 int num_video_mlines = 0;
7375 int num_audio_tracks = 0;
7376 int num_video_tracks = 0;
7377 for (const ContentInfo& content : remote_offer.description()->contents()) {
7378 cricket::MediaType media_type = content.media_description()->type();
7379 int num_tracks = std::max(
7380 1, static_cast<int>(content.media_description()->streams().size()));
7381 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
7382 num_audio_mlines += 1;
7383 num_audio_tracks += num_tracks;
7384 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
7385 num_video_mlines += 1;
7386 num_video_tracks += num_tracks;
7387 }
7388 }
7389 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
7390 if (num_audio_mlines > 1 || num_video_mlines > 1) {
7391 format = kSdpFormatReceivedComplexUnifiedPlan;
7392 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
7393 format = kSdpFormatReceivedComplexPlanB;
7394 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
7395 format = kSdpFormatReceivedSimple;
7396 }
Qingsi Wang7fc821d2018-07-12 19:54:537397 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7398 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:047399}
7400
Qingsi Wang1ba5dec2019-08-19 18:57:177401void PeerConnection::ReportIceCandidateCollected(
7402 const cricket::Candidate& candidate) {
7403 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7404 if (candidate.address().IsPrivateIP()) {
7405 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7406 }
7407 if (candidate.address().IsUnresolvedIP()) {
7408 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7409 }
7410 if (candidate.address().family() == AF_INET6) {
7411 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7412 }
7413}
7414
7415void PeerConnection::ReportRemoteIceCandidateAdded(
7416 const cricket::Candidate& candidate) {
7417 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7418 if (candidate.address().IsPrivateIP()) {
7419 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7420 }
7421 if (candidate.address().IsUnresolvedIP()) {
7422 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7423 }
7424 if (candidate.address().family() == AF_INET6) {
7425 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7426 }
7427}
7428
Harald Alvestrand8ebba742018-05-31 12:00:347429void PeerConnection::NoteUsageEvent(UsageEvent event) {
7430 RTC_DCHECK_RUN_ON(signaling_thread());
7431 usage_event_accumulator_ |= static_cast<int>(event);
7432}
7433
7434void PeerConnection::ReportUsagePattern() const {
7435 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:537436 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7437 usage_event_accumulator_,
7438 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:557439 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 18:57:177440 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 08:39:557441 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7442 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 18:57:177443 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 08:39:557444 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7445 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7446 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7447 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:167448 // If called after close(), we can't report, because observer may have
7449 // been deallocated, and therefore pointer is null. Write to log instead.
7450 if (observer_) {
7451 Observer()->OnInterestingUsage(usage_event_accumulator_);
7452 } else {
7453 RTC_LOG(LS_INFO) << "Interesting usage signature "
7454 << usage_event_accumulator_
7455 << " observed after observer shutdown";
7456 }
Harald Alvestrandc0e97252018-07-26 08:39:557457 }
Harald Alvestrand8ebba742018-05-31 12:00:347458}
7459
Steve Anton0ffaaa22018-02-23 18:31:307460void PeerConnection::ReportNegotiatedSdpSemantics(
7461 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:537462 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:307463 switch (answer.description()->msid_signaling()) {
7464 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:537465 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:307466 break;
7467 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:537468 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:307469 break;
7470 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:537471 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:307472 break;
7473 case cricket::kMsidSignalingMediaSection |
7474 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:537475 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:307476 break;
7477 default:
7478 RTC_NOTREACHED();
7479 }
Qingsi Wang7fc821d2018-07-12 19:54:537480 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7481 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:307482}
7483
Steve Anton75737c02017-11-06 18:37:177484// We need to check the local/remote description for the Transport instead of
7485// the session, because a new Transport added during renegotiation may have
7486// them unset while the session has them set from the previous negotiation.
7487// Not doing so may trigger the auto generation of transport description and
7488// mess up DTLS identity information, ICE credential, etc.
7489bool PeerConnection::ReadyToUseRemoteCandidate(
7490 const IceCandidateInterface* candidate,
7491 const SessionDescriptionInterface* remote_desc,
7492 bool* valid) {
7493 *valid = true;
7494
7495 const SessionDescriptionInterface* current_remote_desc =
7496 remote_desc ? remote_desc : remote_description();
7497
7498 if (!current_remote_desc) {
7499 return false;
7500 }
7501
Guido Urdaneta41633172019-05-23 18:12:297502 RTCErrorOr<const cricket::ContentInfo*> result =
7503 FindContentInfo(current_remote_desc, candidate);
7504 if (!result.ok()) {
7505 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7506 << result.error().message();
Steve Anton75737c02017-11-06 18:37:177507
7508 *valid = false;
7509 return false;
7510 }
7511
Guido Urdaneta41633172019-05-23 18:12:297512 std::string transport_name = GetTransportName(result.value()->name);
7513 return !transport_name.empty();
Steve Anton75737c02017-11-06 18:37:177514}
7515
7516bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 21:19:387517 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 22:50:387518 (dtls_enabled_ ||
7519 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 18:37:177520}
7521
7522void PeerConnection::OnTransportControllerGatheringState(
7523 cricket::IceGatheringState state) {
7524 RTC_DCHECK(signaling_thread()->IsCurrent());
7525 if (state == cricket::kIceGatheringGathering) {
7526 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7527 } else if (state == cricket::kIceGatheringComplete) {
7528 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7529 }
7530}
7531
7532void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:457533 std::map<std::string, std::set<cricket::MediaType>>
7534 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 16:29:427535 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 22:39:457536 if (transceiver->internal()->channel()) {
7537 const std::string& transport_name =
7538 transceiver->internal()->channel()->transport_name();
7539 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:087540 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:457541 }
Steve Anton75737c02017-11-06 18:37:177542 }
7543 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:457544 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7545 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:177546 }
Zhi Huange830e682018-03-30 17:48:357547
Danil Chapovalov66cadcc2018-06-19 14:47:437548 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:357549 if (transport_name) {
7550 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:457551 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:177552 }
Zhi Huange830e682018-03-30 17:48:357553
Steve Antonc7b964c2018-02-01 22:39:457554 for (const auto& entry : media_types_by_transport_name) {
7555 const std::string& transport_name = entry.first;
7556 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:177557 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:457558 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:177559 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:457560 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:177561 }
7562 }
7563}
7564// Walk through the ConnectionInfos to gather best connection usage
7565// for IPv4 and IPv6.
7566void PeerConnection::ReportBestConnectionState(
7567 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:457568 for (const cricket::TransportChannelStats& channel_stats :
7569 stats.channel_stats) {
7570 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 06:10:277571 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 22:39:457572 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:177573 continue;
7574 }
7575
Steve Antonc7b964c2018-02-01 22:39:457576 const cricket::Candidate& local = connection_info.local_candidate;
7577 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:177578
7579 // Increment the counter for IceCandidatePairType.
7580 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7581 (local.type() == RELAY_PORT_TYPE &&
7582 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:537583 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7584 GetIceCandidatePairCounter(local, remote),
7585 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:177586 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:537587 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7588 GetIceCandidatePairCounter(local, remote),
7589 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:177590 } else {
7591 RTC_CHECK(0);
7592 }
Steve Anton75737c02017-11-06 18:37:177593
7594 // Increment the counter for IP type.
7595 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:537596 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7597 kBestConnections_IPv4,
7598 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:177599 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:537600 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7601 kBestConnections_IPv6,
7602 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:177603 } else {
Qingsi Wang1dac6d82018-12-12 23:28:477604 RTC_CHECK(!local.address().hostname().empty() &&
7605 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 18:37:177606 }
7607
7608 return;
7609 }
7610 }
7611}
7612
7613void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:457614 const cricket::TransportStats& stats,
7615 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:177616 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7617 return;
7618 }
7619
7620 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7621 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7622 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7623 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7624 return;
7625 }
7626
Qingsi Wang7fc821d2018-07-12 19:54:537627 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7628 for (cricket::MediaType media_type : media_types) {
7629 switch (media_type) {
7630 case cricket::MEDIA_TYPE_AUDIO:
7631 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7632 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7633 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7634 break;
7635 case cricket::MEDIA_TYPE_VIDEO:
7636 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7637 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7638 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7639 break;
7640 case cricket::MEDIA_TYPE_DATA:
7641 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7642 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7643 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7644 break;
7645 default:
7646 RTC_NOTREACHED();
7647 continue;
7648 }
Steve Antonc7b964c2018-02-01 22:39:457649 }
Qingsi Wang7fc821d2018-07-12 19:54:537650 }
7651
7652 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7653 for (cricket::MediaType media_type : media_types) {
7654 switch (media_type) {
7655 case cricket::MEDIA_TYPE_AUDIO:
7656 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7657 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7658 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7659 break;
7660 case cricket::MEDIA_TYPE_VIDEO:
7661 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7662 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7663 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7664 break;
7665 case cricket::MEDIA_TYPE_DATA:
7666 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7667 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7668 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7669 break;
7670 default:
7671 RTC_NOTREACHED();
7672 continue;
7673 }
Steve Antonc7b964c2018-02-01 22:39:457674 }
Steve Anton75737c02017-11-06 18:37:177675 }
7676}
7677
7678void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 08:57:017679 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:177680 RTC_DCHECK(call_);
7681 call_->OnSentPacket(sent_packet);
7682}
7683
7684const std::string PeerConnection::GetTransportName(
7685 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-14 00:26:057686 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:297687 if (channel) {
7688 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:177689 }
Bjorn A Mellembc3eebc2019-09-23 21:53:547690 if (data_channel_transport_) {
Zhi Huange830e682018-03-30 17:48:357691 RTC_DCHECK(sctp_mid_);
7692 if (content_name == *sctp_mid_) {
7693 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:297694 }
7695 }
7696 // Return an empty string if failed to retrieve the transport name.
7697 return "";
Steve Anton75737c02017-11-06 18:37:177698}
7699
Steve Anton6fec8802017-12-04 18:37:297700void PeerConnection::DestroyTransceiverChannel(
7701 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7702 transceiver) {
7703 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:177704
Amit Hilbuchdd9390c2018-11-14 00:26:057705 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:297706 if (channel) {
7707 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:057708 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:177709 }
7710}
7711
Harald Alvestrand408cb4b2019-11-16 11:09:087712void PeerConnection::DestroyDataChannelTransport() {
Steve Anton6fec8802017-12-04 18:37:297713 if (rtp_data_channel_) {
Harald Alvestrand408cb4b2019-11-16 11:09:087714 OnTransportChannelClosed();
Amit Hilbuchdd9390c2018-11-14 00:26:057715 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 18:37:297716 rtp_data_channel_ = nullptr;
7717 }
7718
7719 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7720 // grab a reference to this PeerConnection. If this is called from the
7721 // PeerConnection destructor, the RefCountedObject vtable will have already
7722 // been destroyed (since it is a subclass of PeerConnection) and using
7723 // rtc::Bind will cause "Pure virtual function called" error to appear.
7724
Bjorn A Mellembc3eebc2019-09-23 21:53:547725 if (sctp_mid_) {
Harald Alvestrand408cb4b2019-11-16 11:09:087726 OnTransportChannelClosed();
Bjorn Mellem175aa2e2018-11-08 19:23:227727 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7728 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 17:44:597729 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 19:23:227730 });
7731 }
Steve Anton6fec8802017-12-04 18:37:297732}
7733
Amit Hilbuchdd9390c2018-11-14 00:26:057734void PeerConnection::DestroyChannelInterface(
7735 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:297736 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:297737 switch (channel->media_type()) {
7738 case cricket::MEDIA_TYPE_AUDIO:
7739 channel_manager()->DestroyVoiceChannel(
7740 static_cast<cricket::VoiceChannel*>(channel));
7741 break;
7742 case cricket::MEDIA_TYPE_VIDEO:
7743 channel_manager()->DestroyVideoChannel(
7744 static_cast<cricket::VideoChannel*>(channel));
7745 break;
7746 case cricket::MEDIA_TYPE_DATA:
7747 channel_manager()->DestroyRtpDataChannel(
7748 static_cast<cricket::RtpDataChannel*>(channel));
7749 break;
7750 default:
7751 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7752 break;
7753 }
Zhi Huange830e682018-03-30 17:48:357754}
Steve Anton6fec8802017-12-04 18:37:297755
Taylor Brandstettercbaa2542018-04-16 23:42:147756bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:357757 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:147758 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 06:51:007759 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellemb689af42019-08-21 17:44:597760 MediaTransportInterface* media_transport,
Bjorn A Mellembc3eebc2019-09-23 21:53:547761 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 12:08:377762 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 22:55:097763 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 23:42:147764 bool ret = true;
Zhi Huange830e682018-03-30 17:48:357765 auto base_channel = GetChannel(mid);
7766 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:147767 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:357768 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:197769
Karl Wiberg5966c502019-02-21 22:55:097770 if (use_media_transport_) {
Tommi78a71382019-08-08 10:27:537771 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 21:31:157772 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:197773
Bjorn A Mellembc3eebc2019-09-23 21:53:547774 if (data_channel_transport_ && mid == sctp_mid_ &&
7775 data_channel_transport_ != data_channel_transport) {
7776 // Changed which data channel transport is used for |sctp_mid_| (eg. now
7777 // it's bundled).
7778 data_channel_transport_->SetDataSink(nullptr);
7779 data_channel_transport_ = data_channel_transport;
7780 if (data_channel_transport) {
7781 data_channel_transport->SetDataSink(this);
7782
7783 // There's a new data channel transport. This needs to be signaled to the
7784 // |sctp_data_channels_| so that they can reopen and reconnect. This is
7785 // necessary when bundling is applied.
7786 data_channel_transport_invoker_->AsyncInvoke<void>(
7787 RTC_FROM_HERE, signaling_thread(), [this] {
7788 RTC_DCHECK_RUN_ON(signaling_thread());
7789 for (auto channel : sctp_data_channels_) {
7790 channel->OnTransportChannelCreated();
7791 }
7792 });
Bjorn A Mellemb689af42019-08-21 17:44:597793 }
7794 }
7795
Taylor Brandstettercbaa2542018-04-16 23:42:147796 return ret;
Steve Anton75737c02017-11-06 18:37:177797}
7798
Guido Urdaneta1ff16c82019-05-20 17:31:537799void PeerConnection::OnSetStreams() {
7800 RTC_DCHECK_RUN_ON(signaling_thread());
7801 if (IsUnifiedPlan())
7802 UpdateNegotiationNeeded();
7803}
7804
Harald Alvestrand7a1c7f72018-08-01 08:50:167805PeerConnectionObserver* PeerConnection::Observer() const {
7806 // In earlier production code, the pointer was not cleared on close,
7807 // which might have led to undefined behavior if the observer was not
7808 // deallocated, or strange crashes if it was.
7809 // We use CHECK in order to catch such behavior if it exists.
7810 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7811 RTC_CHECK(observer_);
7812 return observer_;
7813}
7814
Benjamin Wright8c27cca2018-10-25 17:16:447815CryptoOptions PeerConnection::GetCryptoOptions() {
7816 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7817 // after it has been removed.
7818 return configuration_.crypto_options.has_value()
7819 ? *configuration_.crypto_options
7820 : factory_->options().crypto_options;
7821}
7822
Harald Alvestrand89061872018-01-02 13:08:347823void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 08:57:017824 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 13:08:347825 if (stats_collector_) {
7826 stats_collector_->ClearCachedStatsReport();
7827 }
7828}
7829
Harald Alvestrand7a1c7f72018-08-01 08:50:167830void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:407831 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7832 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:167833}
7834
Guido Urdaneta70c2db12019-04-16 10:24:147835void PeerConnection::UpdateNegotiationNeeded() {
7836 RTC_DCHECK_RUN_ON(signaling_thread());
7837 if (!IsUnifiedPlan()) {
7838 Observer()->OnRenegotiationNeeded();
7839 return;
7840 }
7841
7842 // If connection's [[IsClosed]] slot is true, abort these steps.
7843 if (IsClosed())
7844 return;
7845
7846 // If connection's signaling state is not "stable", abort these steps.
7847 if (signaling_state() != kStable)
7848 return;
7849
7850 // NOTE
7851 // The negotiation-needed flag will be updated once the state transitions to
7852 // "stable", as part of the steps for setting an RTCSessionDescription.
7853
7854 // If the result of checking if negotiation is needed is false, clear the
7855 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7856 // to false, and abort these steps.
7857 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7858 if (!is_negotiation_needed) {
7859 is_negotiation_needed_ = false;
7860 return;
7861 }
7862
7863 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7864 // steps.
7865 if (is_negotiation_needed_)
7866 return;
7867
7868 // Set connection's [[NegotiationNeeded]] slot to true.
7869 is_negotiation_needed_ = true;
7870
7871 // Queue a task that runs the following steps:
7872 // If connection's [[IsClosed]] slot is true, abort these steps.
7873 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7874 // Fire an event named negotiationneeded at connection.
7875 Observer()->OnRenegotiationNeeded();
7876}
7877
7878bool PeerConnection::CheckIfNegotiationIsNeeded() {
7879 RTC_DCHECK_RUN_ON(signaling_thread());
7880 // 1. If any implementation-specific negotiation is required, as described at
7881 // the start of this section, return true.
7882
Henrik Boström79b69802019-07-18 09:16:567883 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7884 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7885 return true;
7886 }
7887
7888 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 10:24:147889 const SessionDescriptionInterface* description = current_local_description();
7890 if (!description)
7891 return true;
7892
Henrik Boström79b69802019-07-18 09:16:567893 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 10:24:147894 // description has been negotiated yet for data, return true.
7895 if (!sctp_data_channels_.empty()) {
7896 if (!cricket::GetFirstDataContent(description->description()->contents()))
7897 return true;
7898 }
7899
Henrik Boström79b69802019-07-18 09:16:567900 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 10:24:147901 // following checks:
7902 for (const auto& transceiver : transceivers_) {
7903 const ContentInfo* current_local_msection =
7904 FindTransceiverMSection(transceiver.get(), description);
7905
7906 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7907 transceiver.get(), current_remote_description());
7908
Henrik Boström79b69802019-07-18 09:16:567909 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 10:24:147910 // but the associated m= section is not yet rejected in
7911 // connection.[[CurrentLocalDescription]] or
7912 // connection.[[CurrentRemoteDescription]], return true.
7913 if (transceiver->stopped()) {
7914 if (current_local_msection && !current_local_msection->rejected &&
7915 ((current_remote_msection && !current_remote_msection->rejected) ||
7916 !current_remote_msection)) {
7917 return true;
7918 }
7919 continue;
7920 }
7921
Henrik Boström79b69802019-07-18 09:16:567922 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 10:24:147923 // section in description, return true.
7924 if (!current_local_msection)
7925 return true;
7926
7927 const MediaContentDescription* current_local_media_description =
7928 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 09:16:567929 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 10:24:147930 // in description then perform the following checks:
7931
Henrik Boström79b69802019-07-18 09:16:567932 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 10:24:147933 // associated m= section in description either doesn't contain a single
7934 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7935 // m= section, or the MSID values themselves, differ from what is in
7936 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7937 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7938 if (current_local_media_description->streams().size() == 0)
7939 return true;
7940
7941 std::vector<std::string> msection_msids;
7942 for (const auto& stream : current_local_media_description->streams()) {
7943 for (const std::string& msid : stream.stream_ids())
7944 msection_msids.push_back(msid);
7945 }
7946
7947 std::vector<std::string> transceiver_msids =
7948 transceiver->sender()->stream_ids();
7949 if (msection_msids.size() != transceiver_msids.size())
7950 return true;
7951
7952 absl::c_sort(transceiver_msids);
7953 absl::c_sort(msection_msids);
7954 if (transceiver_msids != msection_msids)
7955 return true;
7956 }
7957
Henrik Boström79b69802019-07-18 09:16:567958 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 10:24:147959 // associated m= section in neither connection.[[CurrentLocalDescription]]
7960 // nor connection.[[CurrentRemoteDescription]] matches
7961 // transceiver.[[Direction]], return true.
7962 if (description->GetType() == SdpType::kOffer) {
7963 if (!current_remote_description())
7964 return true;
7965
7966 if (!current_remote_msection)
7967 return true;
7968
7969 RtpTransceiverDirection current_local_direction =
7970 current_local_media_description->direction();
7971 RtpTransceiverDirection current_remote_direction =
7972 current_remote_msection->media_description()->direction();
7973 if (transceiver->direction() != current_local_direction &&
7974 transceiver->direction() !=
7975 RtpTransceiverDirectionReversed(current_remote_direction)) {
7976 return true;
7977 }
7978 }
7979
Henrik Boström79b69802019-07-18 09:16:567980 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 10:24:147981 // associated m= section in the description does not match
7982 // transceiver.[[Direction]] intersected with the offered direction (as
7983 // described in [JSEP] (section 5.3.1.)), return true.
7984 if (description->GetType() == SdpType::kAnswer) {
7985 if (!remote_description())
7986 return true;
7987
7988 const ContentInfo* offered_remote_msection =
7989 FindTransceiverMSection(transceiver.get(), remote_description());
7990
7991 RtpTransceiverDirection offered_direction =
7992 offered_remote_msection
7993 ? offered_remote_msection->media_description()->direction()
7994 : RtpTransceiverDirection::kInactive;
7995
7996 if (current_local_media_description->direction() !=
7997 (RtpTransceiverDirectionIntersection(
7998 transceiver->direction(),
7999 RtpTransceiverDirectionReversed(offered_direction)))) {
8000 return true;
8001 }
8002 }
8003 }
8004
8005 // If all the preceding checks were performed and true was not returned,
8006 // nothing remains to be negotiated; return false.
8007 return false;
8008}
8009
Eldar Relloead0ec92019-10-21 20:01:318010RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 15:29:448011 auto state = signaling_state();
8012 if (state != PeerConnectionInterface::kHaveLocalOffer &&
8013 state != PeerConnectionInterface::kHaveRemoteOffer) {
8014 return RTCError(RTCErrorType::INVALID_STATE,
8015 "Called in wrong signalingState: " +
8016 GetSignalingStateString(signaling_state()));
8017 }
8018 RTC_DCHECK_RUN_ON(signaling_thread());
8019 RTC_DCHECK(IsUnifiedPlan());
8020
8021 for (auto&& transceivers_stable_state_pair :
8022 transceiver_stable_states_by_transceivers_) {
8023 auto transceiver = transceivers_stable_state_pair.first;
8024 auto state = transceivers_stable_state_pair.second;
8025 RTC_DCHECK(transceiver->internal()->mid().has_value());
8026 std::string mid = transceiver->internal()->mid().value();
8027 transport_controller_->RollbackTransportForMid(mid);
8028 DestroyTransceiverChannel(transceiver);
8029
Eldar Relloead0ec92019-10-21 20:01:318030 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
8031 transceiver->receiver()) {
8032 Observer()->OnRemoveTrack(transceiver->receiver());
8033 }
Eldar Rello5ab79e62019-10-09 15:29:448034 if (state.newly_created()) {
8035 // Remove added transceivers with no added track.
8036 if (transceiver->internal()->sender()->track()) {
8037 transceiver->internal()->set_created_by_addtrack(true);
8038 } else {
8039 int remaining_transceiver_count = 0;
8040 for (auto&& t : transceivers_) {
8041 if (t != transceiver) {
8042 transceivers_[remaining_transceiver_count++] = t;
8043 }
8044 }
8045 transceivers_.resize(remaining_transceiver_count);
8046 }
8047 }
8048 transceiver->internal()->sender_internal()->set_transport(nullptr);
8049 transceiver->internal()->receiver_internal()->set_transport(nullptr);
8050 transceiver->internal()->set_direction(state.direction());
8051 transceiver->internal()->set_mid(state.mid());
8052 transceiver->internal()->set_mline_index(state.mline_index());
8053 }
8054 transceiver_stable_states_by_transceivers_.clear();
8055 pending_local_description_.reset();
8056 pending_remote_description_.reset();
8057 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 20:01:318058
8059 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
8060 // gets called in SetRemoteDescription.
8061 if (sdp_type == SdpType::kRollback) {
8062 UpdateNegotiationNeeded();
8063 if (is_negotiation_needed_) {
8064 Observer()->OnRenegotiationNeeded();
8065 }
8066 }
Eldar Rello5ab79e62019-10-09 15:29:448067 return RTCError::OK();
8068}
8069
henrike@webrtc.org28e20752013-07-10 00:45:368070} // namespace webrtc