blob: b3247c64566132eae25cd64d00ec4f47e5c01177 [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>
Steve Antondcc3c022017-12-23 00:02:5415#include <queue>
Steve Anton75737c02017-11-06 18:37:1716#include <set>
kwiberg0eb15ed2015-12-17 11:04:1517#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3619
Steve Anton64b626b2019-01-29 01:25:2620#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 09:40:3321#include "absl/memory/memory.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"
Niels Möllerd8b9ed72019-05-08 11:53:5128#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 21:11:5729#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 17:11:0030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 05:38:4031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "call/call.h"
Steve Anton10542f22019-01-11 17:11:0033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3134#include "logging/rtc_event_log/rtc_event_log.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"
Karl Wiberge40468b2017-11-22 09:42:2657#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 17:11:0058#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 11:41:3059#include "rtc_base/strings/string_builder.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
Amit Hilbuche2a284d2019-03-05 20:36:31111// UMA metric names.
112const char kSimulcastVersionApplyLocalDescription[] =
113 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
114const char kSimulcastVersionApplyRemoteDescription[] =
115 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
116const char kSimulcastNumberOfEncodings[] =
117 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
118const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
119
Seth Hampson845e8782018-03-02 19:34:10120static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:22121static const char kDefaultAudioSenderId[] = "defaulta0";
122static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11123
zhihuang8f65cdf2016-05-07 01:40:30124// The length of RTCP CNAMEs.
125static const int kRtcpCnameLength = 16;
126
Steve Antonad182762018-09-05 20:22:40127enum {
128 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
129 MSG_SET_SESSIONDESCRIPTION_FAILED,
130 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
131 MSG_GETSTATS,
132 MSG_FREE_DATACHANNELS,
133 MSG_REPORT_USAGE_PATTERN,
134};
135
Harald Alvestrand19793842018-06-25 10:03:50136static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
137
Steve Antonad182762018-09-05 20:22:40138struct SetSessionDescriptionMsg : public rtc::MessageData {
139 explicit SetSessionDescriptionMsg(
140 webrtc::SetSessionDescriptionObserver* observer)
141 : observer(observer) {}
142
143 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
144 RTCError error;
145};
146
147struct CreateSessionDescriptionMsg : public rtc::MessageData {
148 explicit CreateSessionDescriptionMsg(
149 webrtc::CreateSessionDescriptionObserver* observer)
150 : observer(observer) {}
151
152 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
153 RTCError error;
154};
155
156struct GetStatsMsg : public rtc::MessageData {
157 GetStatsMsg(webrtc::StatsObserver* observer,
158 webrtc::MediaStreamTrackInterface* track)
159 : observer(observer), track(track) {}
160 rtc::scoped_refptr<webrtc::StatsObserver> observer;
161 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
162};
163
deadbeefab9b2d12015-10-14 18:33:11164// Check if we can send |new_stream| on a PeerConnection.
165bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
166 webrtc::MediaStreamInterface* new_stream) {
167 if (!new_stream || !current_streams) {
168 return false;
169 }
Seth Hampson13b8bad2018-03-13 23:05:28170 if (current_streams->find(new_stream->id()) != nullptr) {
171 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25172 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11173 return false;
174 }
175 return true;
176}
177
deadbeef5e97fb52015-10-15 19:49:08178// If the direction is "recvonly" or "inactive", treat the description
179// as containing no streams.
180// See: https://code.google.com/p/webrtc/issues/detail?id=5054
181std::vector<cricket::StreamParams> GetActiveStreams(
182 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10183 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08184 ? desc->streams()
185 : std::vector<cricket::StreamParams>();
186}
187
deadbeefab9b2d12015-10-14 18:33:11188bool IsValidOfferToReceiveMedia(int value) {
189 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
190 return (value >= Options::kUndefined) &&
191 (value <= Options::kMaxOfferToReceiveMedia);
192}
193
zhihuang1c378ed2017-08-17 21:10:50194// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 18:13:58195void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39196 const std::vector<rtc::scoped_refptr<
197 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50198 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37199 cricket::MediaDescriptionOptions* video_media_description_options,
200 int num_sim_layers) {
olka3c747662017-08-17 13:50:32201 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50202 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
203 if (audio_media_description_options) {
204 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38205 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50206 }
207 } else {
208 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
209 if (video_media_description_options) {
210 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 18:13:58211 sender->id(), sender->internal()->stream_ids(), {},
212 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50213 }
214 }
zhihuanga77e6bb2017-08-15 01:17:48215 }
zhihuang1c378ed2017-08-17 21:10:50216}
olka3c747662017-08-17 13:50:32217
zhihuang1c378ed2017-08-17 21:10:50218// Add options to |session_options| from |rtp_data_channels|.
219void AddRtpDataChannelOptions(
220 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
221 rtp_data_channels,
222 cricket::MediaDescriptionOptions* data_media_description_options) {
223 if (!data_media_description_options) {
224 return;
225 }
deadbeefab9b2d12015-10-14 18:33:11226 // Check for data channels.
227 for (const auto& kv : rtp_data_channels) {
228 const DataChannel* channel = kv.second;
229 if (channel->state() == DataChannel::kConnecting ||
230 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50231 // Legacy RTP data channels are signaled with the track/stream ID set to
232 // the data channel's label.
233 data_media_description_options->AddRtpDataChannel(channel->label(),
234 channel->label());
deadbeefab9b2d12015-10-14 18:33:11235 }
236 }
237}
238
Taylor Brandstettera1c30352016-05-13 15:15:11239uint32_t ConvertIceTransportTypeToCandidateFilter(
240 PeerConnectionInterface::IceTransportsType type) {
241 switch (type) {
242 case PeerConnectionInterface::kNone:
243 return cricket::CF_NONE;
244 case PeerConnectionInterface::kRelay:
245 return cricket::CF_RELAY;
246 case PeerConnectionInterface::kNoHost:
247 return (cricket::CF_ALL & ~cricket::CF_HOST);
248 case PeerConnectionInterface::kAll:
249 return cricket::CF_ALL;
250 default:
nissec80e7412017-01-11 13:56:46251 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11252 }
253 return cricket::CF_NONE;
254}
255
deadbeef293e9262017-01-11 20:28:30256// Helper to set an error and return from a method.
257bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
258 if (error) {
259 error->set_type(type);
260 }
261 return type == webrtc::RTCErrorType::NONE;
262}
263
Steve Anton038834f2017-07-14 22:59:59264bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 17:22:52265 bool ok = error.ok();
Steve Anton038834f2017-07-14 22:59:59266 if (error_out) {
267 *error_out = std::move(error);
268 }
Steve Antonf820a5e2018-08-10 17:22:52269 return ok;
Steve Anton038834f2017-07-14 22:59:59270}
271
Steve Antonba818672017-11-06 18:21:57272std::string GetSignalingStateString(
273 PeerConnectionInterface::SignalingState state) {
274 switch (state) {
275 case PeerConnectionInterface::kStable:
276 return "kStable";
277 case PeerConnectionInterface::kHaveLocalOffer:
278 return "kHaveLocalOffer";
279 case PeerConnectionInterface::kHaveLocalPrAnswer:
280 return "kHavePrAnswer";
281 case PeerConnectionInterface::kHaveRemoteOffer:
282 return "kHaveRemoteOffer";
283 case PeerConnectionInterface::kHaveRemotePrAnswer:
284 return "kHaveRemotePrAnswer";
285 case PeerConnectionInterface::kClosed:
286 return "kClosed";
287 }
288 RTC_NOTREACHED();
289 return "";
290}
deadbeef0a6c4ca2015-10-06 18:38:28291
Steve Anton75737c02017-11-06 18:37:17292IceCandidatePairType GetIceCandidatePairCounter(
293 const cricket::Candidate& local,
294 const cricket::Candidate& remote) {
295 const auto& l = local.type();
296 const auto& r = remote.type();
297 const auto& host = LOCAL_PORT_TYPE;
298 const auto& srflx = STUN_PORT_TYPE;
299 const auto& relay = RELAY_PORT_TYPE;
300 const auto& prflx = PRFLX_PORT_TYPE;
301 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 16:25:54302 bool local_hostname =
303 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
304 bool remote_hostname = !remote.address().hostname().empty() &&
305 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 18:37:17306 bool local_private = IPIsPrivate(local.address().ipaddr());
307 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 16:25:54308 if (local_hostname) {
309 if (remote_hostname) {
310 return kIceCandidatePairHostNameHostName;
311 } else if (remote_private) {
312 return kIceCandidatePairHostNameHostPrivate;
313 } else {
314 return kIceCandidatePairHostNameHostPublic;
315 }
316 } else if (local_private) {
317 if (remote_hostname) {
318 return kIceCandidatePairHostPrivateHostName;
319 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17320 return kIceCandidatePairHostPrivateHostPrivate;
321 } else {
322 return kIceCandidatePairHostPrivateHostPublic;
323 }
324 } else {
Jeroen de Borst833979f2018-12-13 16:25:54325 if (remote_hostname) {
326 return kIceCandidatePairHostPublicHostName;
327 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17328 return kIceCandidatePairHostPublicHostPrivate;
329 } else {
330 return kIceCandidatePairHostPublicHostPublic;
331 }
332 }
333 }
334 if (l == host && r == srflx)
335 return kIceCandidatePairHostSrflx;
336 if (l == host && r == relay)
337 return kIceCandidatePairHostRelay;
338 if (l == host && r == prflx)
339 return kIceCandidatePairHostPrflx;
340 if (l == srflx && r == host)
341 return kIceCandidatePairSrflxHost;
342 if (l == srflx && r == srflx)
343 return kIceCandidatePairSrflxSrflx;
344 if (l == srflx && r == relay)
345 return kIceCandidatePairSrflxRelay;
346 if (l == srflx && r == prflx)
347 return kIceCandidatePairSrflxPrflx;
348 if (l == relay && r == host)
349 return kIceCandidatePairRelayHost;
350 if (l == relay && r == srflx)
351 return kIceCandidatePairRelaySrflx;
352 if (l == relay && r == relay)
353 return kIceCandidatePairRelayRelay;
354 if (l == relay && r == prflx)
355 return kIceCandidatePairRelayPrflx;
356 if (l == prflx && r == host)
357 return kIceCandidatePairPrflxHost;
358 if (l == prflx && r == srflx)
359 return kIceCandidatePairPrflxSrflx;
360 if (l == prflx && r == relay)
361 return kIceCandidatePairPrflxRelay;
362 return kIceCandidatePairMax;
363}
364
Seth Hampsonae8a90a2018-02-13 23:33:48365// Logic to decide if an m= section can be recycled. This means that the new
366// m= section is not rejected, but the old local or remote m= section is
367// rejected. |old_content_one| and |old_content_two| refer to the m= section
368// of the old remote and old local descriptions in no particular order.
369// We need to check both the old local and remote because either
370// could be the most current from the latest negotation.
371bool IsMediaSectionBeingRecycled(SdpType type,
372 const ContentInfo& content,
373 const ContentInfo* old_content_one,
374 const ContentInfo* old_content_two) {
375 return type == SdpType::kOffer && !content.rejected &&
376 ((old_content_one && old_content_one->rejected) ||
377 (old_content_two && old_content_two->rejected));
378}
379
Steve Anton75737c02017-11-06 18:37:17380// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48381// |current_desc|. The number of m= sections in |new_desc| should be no
382// less than |current_desc|. In the case of checking an answer's
383// |new_desc|, the |current_desc| is the last offer that was set as the
384// local or remote. In the case of checking an offer's |new_desc| we
385// check against the local and remote descriptions stored from the last
386// negotiation, because either of these could be the most up to date for
387// possible rejected m sections. These are the |current_desc| and
388// |secondary_current_desc|.
389bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
390 const SessionDescription* secondary_current_desc,
391 const SessionDescription& new_desc,
392 const SdpType type) {
393 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 18:37:17394 return false;
395 }
396
Seth Hampsonae8a90a2018-02-13 23:33:48397 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
398 const cricket::ContentInfo* secondary_content_info = nullptr;
399 if (secondary_current_desc &&
400 i < secondary_current_desc->contents().size()) {
401 secondary_content_info = &secondary_current_desc->contents()[i];
402 }
403 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
404 &current_desc.contents()[i],
405 secondary_content_info)) {
406 // For new offer descriptions, if the media section can be recycled, it's
407 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-23 00:02:54408 continue;
409 }
Seth Hampsonae8a90a2018-02-13 23:33:48410 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17411 return false;
412 }
413 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48414 new_desc.contents()[i].media_description();
415 const MediaContentDescription* current_desc_mdesc =
416 current_desc.contents()[i].media_description();
417 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 18:37:17418 return false;
419 }
420 }
421 return true;
422}
423
Seth Hampsonae8a90a2018-02-13 23:33:48424bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
425 const SessionDescription& desc2) {
426 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17427}
428
Qingsi Wang7fc821d2018-07-12 19:54:53429void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
430 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20431 // Array of structs needed to map {KeyExchangeProtocolType,
432 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
433 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
434 static constexpr struct {
435 KeyExchangeProtocolType protocol_type;
436 cricket::MediaType media_type;
437 KeyExchangeProtocolMedia protocol_media;
438 } kEnumCounterKeyProtocolMediaMap[] = {
439 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
440 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
441 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
442 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
443 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
444 kEnumCounterKeyProtocolMediaTypeDtlsData},
445 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
446 kEnumCounterKeyProtocolMediaTypeSdesAudio},
447 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
448 kEnumCounterKeyProtocolMediaTypeSdesVideo},
449 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
450 kEnumCounterKeyProtocolMediaTypeSdesData},
451 };
452
Qingsi Wang7fc821d2018-07-12 19:54:53453 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
454 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26455
Mirko Bonadeiab499822018-09-11 08:43:20456 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
457 if (i.protocol_type == protocol_type && i.media_type == media_type) {
458 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
459 i.protocol_media,
460 kEnumCounterKeyProtocolMediaTypeMax);
461 }
Harald Alvestrandf9d0f1d2018-03-02 13:15:26462 }
463}
464
Harald Alvestrand76829d72018-07-18 21:24:36465void NoteAddIceCandidateResult(int result) {
466 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
467 kAddIceCandidateMax);
468}
469
Steve Anton75737c02017-11-06 18:37:17470// Checks that each non-rejected content has SDES crypto keys or a DTLS
471// fingerprint, unless it's in a BUNDLE group, in which case only the
472// BUNDLE-tag section (first media section/description in the BUNDLE group)
473// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
474// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
475// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 19:54:53476RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17481 continue;
482 }
Harald Alvestrand2e180612018-03-07 09:56:14483 // Note what media is used with each crypto protocol, for all sections.
484 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
485 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 19:54:53486 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56487 const std::string& mid = content_info.name;
488 if (bundle && bundle->HasContentName(mid) &&
489 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17490 // This isn't the first media section in the BUNDLE group, so it's not
491 // required to have crypto attributes, since only the crypto attributes
492 // from the first section actually get used.
493 continue;
494 }
495
496 // If the content isn't rejected or bundled into another m= section, crypto
497 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30498 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56499 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17500 if (!media || !tinfo) {
501 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56502 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17503 }
504 if (dtls_enabled) {
505 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25506 RTC_LOG(LS_WARNING)
507 << "Session description must have DTLS fingerprint if "
508 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56509 return RTCError(RTCErrorType::INVALID_PARAMETER,
510 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17511 }
512 } else {
513 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25514 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17515 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56516 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17517 }
518 }
519 }
Steve Anton8a006912017-12-04 23:25:56520 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17521}
522
523// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
524// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
525// media section/description in the BUNDLE group) needs a ufrag and pwd.
526bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
527 const cricket::ContentGroup* bundle =
528 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56529 for (const cricket::ContentInfo& content_info : desc->contents()) {
530 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17531 continue;
532 }
Steve Anton8a006912017-12-04 23:25:56533 const std::string& mid = content_info.name;
534 if (bundle && bundle->HasContentName(mid) &&
535 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17536 // This isn't the first media section in the BUNDLE group, so it's not
537 // required to have ufrag/password, since only the ufrag/password from
538 // the first section actually get used.
539 continue;
540 }
541
542 // If the content isn't rejected or bundled into another m= section,
543 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56544 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17545 if (!tinfo) {
546 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25547 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17548 return false;
549 }
550 if (tinfo->description.ice_ufrag.empty() ||
551 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25552 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17553 return false;
554 }
555 }
556 return true;
557}
558
Steve Anton75737c02017-11-06 18:37:17559// Get the SCTP port out of a SessionDescription.
560// Return -1 if not found.
561int GetSctpPort(const SessionDescription* session_description) {
Harald Alvestrand141c0ad2019-05-05 19:00:00562 const cricket::DataContentDescription* data_desc =
563 GetFirstDataContentDescription(session_description);
Steve Antonb1c1de12017-12-21 23:14:30564 RTC_DCHECK(data_desc);
565 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17566 return -1;
567 }
Harald Alvestrand141c0ad2019-05-05 19:00:00568 std::string value;
569 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
570 cricket::kGoogleSctpDataCodecName);
571 for (const cricket::DataCodec& codec : data_desc->codecs()) {
572 if (!codec.Matches(match_pattern)) {
573 continue;
574 }
575 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
576 return rtc::FromString<int>(value);
577 }
578 }
579 return -1;
Steve Anton75737c02017-11-06 18:37:17580}
581
Steve Anton75737c02017-11-06 18:37:17582// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
583bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
584 const SessionDescriptionInterface* new_desc,
585 const std::string& content_name) {
586 if (!old_desc) {
587 return false;
588 }
589 const SessionDescription* new_sd = new_desc->description();
590 const SessionDescription* old_sd = old_desc->description();
591 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
592 if (!cinfo || cinfo->rejected) {
593 return false;
594 }
595 // If the content isn't rejected, check if ufrag and password has changed.
596 const cricket::TransportDescription* new_transport_desc =
597 new_sd->GetTransportDescriptionByName(content_name);
598 const cricket::TransportDescription* old_transport_desc =
599 old_sd->GetTransportDescriptionByName(content_name);
600 if (!new_transport_desc || !old_transport_desc) {
601 // No transport description exists. This is not an ICE restart.
602 return false;
603 }
604 if (cricket::IceCredentialsChanged(
605 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
606 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25607 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
608 << ".";
Steve Anton75737c02017-11-06 18:37:17609 return true;
610 }
611 return false;
612}
613
Steve Anton80dd7b52018-02-17 01:08:42614// Generates a string error message for SetLocalDescription/SetRemoteDescription
615// from an RTCError.
616std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
617 SdpType type,
618 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 11:41:30619 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42620 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
621 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32622 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42623}
624
Seth Hampson5b4f0752018-04-02 23:31:36625std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
626 std::string output = "streams=[";
627 const char* separator = "";
628 for (const auto& stream_id : stream_ids) {
629 output.append(separator).append(stream_id);
630 separator = ", ";
631 }
632 output.append("]");
633 return output;
634}
635
Danil Chapovalov66cadcc2018-06-19 14:47:43636absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23637 int rtc_configuration_parameter) {
638 if (rtc_configuration_parameter ==
639 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43640 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23641 }
642 return rtc_configuration_parameter;
643}
644
Bjorn Mellem175aa2e2018-11-08 19:23:22645cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
646 switch (type) {
647 case DataMessageType::kText:
648 return cricket::DMT_TEXT;
649 case DataMessageType::kBinary:
650 return cricket::DMT_BINARY;
651 case DataMessageType::kControl:
652 return cricket::DMT_CONTROL;
653 default:
654 return cricket::DMT_NONE;
655 }
656 return cricket::DMT_NONE;
657}
658
659DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
660 switch (type) {
661 case cricket::DMT_TEXT:
662 return DataMessageType::kText;
663 case cricket::DMT_BINARY:
664 return DataMessageType::kBinary;
665 case cricket::DMT_CONTROL:
666 return DataMessageType::kControl;
667 case cricket::DMT_NONE:
668 default:
669 RTC_NOTREACHED();
670 }
671 return DataMessageType::kControl;
672}
673
Amit Hilbuche2a284d2019-03-05 20:36:31674void ReportSimulcastApiVersion(const char* name,
675 const SessionDescription& session) {
676 bool has_legacy = false;
677 bool has_spec_compliant = false;
678 for (const ContentInfo& content : session.contents()) {
679 if (!content.description) {
680 continue;
681 }
682 has_spec_compliant |= content.description->HasSimulcast();
683 for (const StreamParams& sp : content.description->streams()) {
684 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
685 }
686 }
687
688 if (has_legacy) {
689 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
690 kSimulcastApiVersionMax);
691 }
692 if (has_spec_compliant) {
693 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
694 kSimulcastApiVersionMax);
695 }
696 if (!has_legacy && !has_spec_compliant) {
697 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
698 kSimulcastApiVersionMax);
699 }
700}
701
Guido Urdaneta70c2db12019-04-16 10:24:14702const ContentInfo* FindTransceiverMSection(
703 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
704 const SessionDescriptionInterface* session_description) {
705 return transceiver->mid()
706 ? session_description->description()->GetContentByName(
707 *transceiver->mid())
708 : nullptr;
709}
710
Steve Anton75737c02017-11-06 18:37:17711} // namespace
712
Henrik Boström31638672017-11-23 16:48:32713// Upon completion, posts a task to execute the callback of the
714// SetSessionDescriptionObserver asynchronously on the same thread. At this
715// point, the state of the peer connection might no longer reflect the effects
716// of the SetRemoteDescription operation, as the peer connection could have been
717// modified during the post.
718// TODO(hbos): Remove this class once we remove the version of
719// PeerConnectionInterface::SetRemoteDescription() that takes a
720// SetSessionDescriptionObserver as an argument.
721class PeerConnection::SetRemoteDescriptionObserverAdapter
722 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
723 public:
724 SetRemoteDescriptionObserverAdapter(
725 rtc::scoped_refptr<PeerConnection> pc,
726 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
727 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
728
729 // SetRemoteDescriptionObserverInterface implementation.
730 void OnSetRemoteDescriptionComplete(RTCError error) override {
731 if (error.ok())
732 pc_->PostSetSessionDescriptionSuccess(wrapper_);
733 else
Harald Alvestrand5081c0c2018-03-09 14:18:03734 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32735 }
736
737 private:
738 rtc::scoped_refptr<PeerConnection> pc_;
739 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
740};
741
deadbeef293e9262017-01-11 20:28:30742bool PeerConnectionInterface::RTCConfiguration::operator==(
743 const PeerConnectionInterface::RTCConfiguration& o) const {
744 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10745 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30746 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56747 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10748 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30749 BundlePolicy bundle_policy;
750 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10751 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
752 int ice_candidate_pool_size;
753 bool disable_ipv6;
754 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11755 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22756 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10757 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43758 absl::optional<int> screencast_min_bitrate;
759 absl::optional<bool> combined_audio_video_bwe;
760 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30761 TcpCandidatePolicy tcp_candidate_policy;
762 CandidateNetworkPolicy candidate_network_policy;
763 int audio_jitter_buffer_max_packets;
764 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 14:45:20765 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 14:58:36766 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 20:28:30767 int ice_connection_receiving_timeout;
768 int ice_backup_candidate_pair_ping_interval;
769 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30770 bool prioritize_most_likely_ice_candidate_pairs;
771 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30772 bool prune_turn_ports;
773 bool presume_writable_when_fully_relayed;
774 bool enable_ice_renomination;
775 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 14:47:43776 absl::optional<int> ice_check_interval_strong_connectivity;
777 absl::optional<int> ice_check_interval_weak_connectivity;
778 absl::optional<int> ice_check_min_interval;
779 absl::optional<int> ice_unwritable_timeout;
780 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:17781 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 14:47:43782 absl::optional<int> stun_candidate_keepalive_interval;
783 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40784 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56785 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43786 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11787 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21788 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48789 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 17:16:44790 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48791 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30792 };
793 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
794 "Did you add something to RTCConfiguration and forget to "
795 "update operator==?");
796 return type == o.type && servers == o.servers &&
797 bundle_policy == o.bundle_policy &&
798 rtcp_mux_policy == o.rtcp_mux_policy &&
799 tcp_candidate_policy == o.tcp_candidate_policy &&
800 candidate_network_policy == o.candidate_network_policy &&
801 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
802 audio_jitter_buffer_fast_accelerate ==
803 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 14:45:20804 audio_jitter_buffer_min_delay_ms ==
805 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 14:58:36806 audio_jitter_buffer_enable_rtx_handling ==
807 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 20:28:30808 ice_connection_receiving_timeout ==
809 o.ice_connection_receiving_timeout &&
810 ice_backup_candidate_pair_ping_interval ==
811 o.ice_backup_candidate_pair_ping_interval &&
812 continual_gathering_policy == o.continual_gathering_policy &&
813 certificates == o.certificates &&
814 prioritize_most_likely_ice_candidate_pairs ==
815 o.prioritize_most_likely_ice_candidate_pairs &&
816 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51817 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11818 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22819 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30820 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30821 screencast_min_bitrate == o.screencast_min_bitrate &&
822 combined_audio_video_bwe == o.combined_audio_video_bwe &&
823 enable_dtls_srtp == o.enable_dtls_srtp &&
824 ice_candidate_pool_size == o.ice_candidate_pool_size &&
825 prune_turn_ports == o.prune_turn_ports &&
826 presume_writable_when_fully_relayed ==
827 o.presume_writable_when_fully_relayed &&
828 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14829 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14830 ice_check_interval_strong_connectivity ==
831 o.ice_check_interval_strong_connectivity &&
832 ice_check_interval_weak_connectivity ==
833 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10834 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57835 ice_unwritable_timeout == o.ice_unwritable_timeout &&
836 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-07 07:30:17837 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 22:45:49838 stun_candidate_keepalive_interval ==
839 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40840 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56841 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40842 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11843 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21844 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44845 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48846 use_media_transport_for_data_channels ==
847 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 09:25:48848 crypto_options == o.crypto_options &&
849 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30850}
851
852bool PeerConnectionInterface::RTCConfiguration::operator!=(
853 const PeerConnectionInterface::RTCConfiguration& o) const {
854 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26855}
856
zhihuang8f65cdf2016-05-07 01:40:30857// Generate a RTCP CNAME when a PeerConnection is created.
858std::string GenerateRtcpCname() {
859 std::string cname;
860 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25861 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27862 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30863 }
864 return cname;
865}
866
zhihuang1c378ed2017-08-17 21:10:50867bool ValidateOfferAnswerOptions(
868 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
869 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
870 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32871}
872
zhihuang1c378ed2017-08-17 21:10:50873// From |rtc_options|, fill parts of |session_options| shared by all generated
874// m= sections (in other words, nothing that involves a map/array).
875void ExtractSharedMediaSessionOptions(
876 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
877 cricket::MediaSessionOptions* session_options) {
878 session_options->vad_enabled = rtc_options.voice_activity_detection;
879 session_options->bundle_enabled = rtc_options.use_rtp_mux;
880}
zhihuanga77e6bb2017-08-15 01:17:48881
zhihuang38ede132017-06-15 19:52:32882PeerConnection::PeerConnection(PeerConnectionFactory* factory,
883 std::unique_ptr<RtcEventLog> event_log,
884 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36885 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32886 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 10:59:57887 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-07 01:40:30888 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11889 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32890 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 08:57:01891 call_(std::move(call)),
892 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36893
894PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17895 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22896 RTC_DCHECK_RUN_ON(signaling_thread());
897
Steve Anton8af21862017-12-15 19:20:13898 // Need to stop transceivers before destroying the stats collector because
899 // AudioRtpSender has a reference to the StatsCollector it will update when
900 // stopping.
Mirko Bonadei739baf02019-01-27 16:29:42901 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:13902 transceiver->Stop();
903 }
Steve Anton4171afb2017-11-20 18:20:22904
Taylor Brandstettera1c30352016-05-13 15:15:11905 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57906 if (stats_collector_) {
907 stats_collector_->WaitForPendingRequest();
908 stats_collector_ = nullptr;
909 }
Steve Anton75737c02017-11-06 18:37:17910
Steve Anton8af21862017-12-15 19:20:13911 // Don't destroy BaseChannels until after stats has been cleaned up so that
912 // the last stats request can still read from the channels.
913 DestroyAllChannels();
914
Mirko Bonadei675513b2017-11-09 10:09:25915 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17916
917 webrtc_session_desc_factory_.reset();
918 sctp_invoker_.reset();
919 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 19:23:22920 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 18:37:17921 transport_controller_.reset();
922
deadbeef91dd5672016-05-18 23:55:30923 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 13:13:22924 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
925 RTC_DCHECK_RUN_ON(network_thread());
926 port_allocator_.reset();
927 });
eladalon248fd4f2017-09-06 12:18:15928 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02929 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:57930 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:15931 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09932 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15933 event_log_.reset();
934 });
henrike@webrtc.org28e20752013-07-10 00:45:36935}
936
Steve Anton8af21862017-12-15 19:20:13937void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08938 // Destroy video channels first since they may have a pointer to a voice
939 // channel.
Mirko Bonadei739baf02019-01-27 16:29:42940 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08941 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08942 DestroyTransceiverChannel(transceiver);
943 }
944 }
Mirko Bonadei739baf02019-01-27 16:29:42945 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08946 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08947 DestroyTransceiverChannel(transceiver);
948 }
949 }
950 DestroyDataChannel();
951}
952
henrike@webrtc.org28e20752013-07-10 00:45:36953bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45954 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47955 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 09:18:56956 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 22:55:09957 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 21:15:17958 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59959
960 RTCError config_error = ValidateConfiguration(configuration);
961 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25962 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59963 return false;
964 }
965
Benjamin Wrightcab588882018-05-02 22:12:47966 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25967 RTC_LOG(LS_ERROR)
968 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07969 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30970 return false;
971 }
Jonas Orelandbdcee282017-10-10 12:01:40972
Benjamin Wrightcab588882018-05-02 22:12:47973 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30974 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25975 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07976 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10977 return false;
978 }
Benjamin Wrightd6f86e82018-05-08 20:12:25979
Benjamin Wrightcab588882018-05-02 22:12:47980 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15981 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47982 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25983 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10984
Harald Alvestrandb2a74782018-06-28 11:54:07985 cricket::ServerAddresses stun_servers;
986 std::vector<cricket::RelayServerConfig> turn_servers;
987
988 RTCErrorType parse_error =
989 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
990 if (parse_error != RTCErrorType::NONE) {
991 return false;
992 }
993
deadbeef91dd5672016-05-18 23:55:30994 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11995 // there.
Karl Wibergfb3be392019-03-22 13:13:22996 const auto pa_result =
997 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 11:54:07998 RTC_FROM_HERE,
999 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 13:13:221000 stun_servers, turn_servers, configuration));
1001
Harald Alvestrandb2a74782018-06-28 11:54:071002 // If initialization was successful, note if STUN or TURN servers
1003 // were supplied.
1004 if (!stun_servers.empty()) {
1005 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1006 }
1007 if (!turn_servers.empty()) {
1008 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1009 }
henrike@webrtc.org28e20752013-07-10 00:45:361010
Qingsi Wang7fc821d2018-07-12 19:54:531011 // Send information about IPv4/IPv6 status.
1012 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 13:13:221013 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 19:54:531014 address_family = kPeerConnection_IPv6;
1015 } else {
1016 address_family = kPeerConnection_IPv4;
1017 }
1018 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1019 kPeerConnectionAddressFamilyCounter_Max);
1020
Zhi Huange830e682018-03-30 17:48:351021 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1022
Steve Anton75737c02017-11-06 18:37:171023 // RFC 3264: The numeric value of the session id and version in the
1024 // o line MUST be representable with a "64 bit signed integer".
1025 // Due to this constraint session id |session_id_| is max limited to
1026 // LLONG_MAX.
1027 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:351028 JsepTransportController::Config config;
1029 config.redetermine_role_on_ice_restart =
1030 configuration.redetermine_role_on_ice_restart;
1031 config.ssl_max_version = factory_->options().ssl_max_version;
1032 config.disable_encryption = options.disable_encryption;
1033 config.bundle_policy = configuration.bundle_policy;
1034 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 17:16:441035 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1036 // stub.
1037 config.crypto_options = configuration.crypto_options.has_value()
1038 ? *configuration.crypto_options
1039 : options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:341040 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 10:59:571041 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 17:48:351042#if defined(ENABLE_EXTERNAL_AUTH)
1043 config.enable_external_auth = true;
1044#endif
Zhi Huangb57e1692018-06-12 18:41:111045 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:421046
Bjorn Mellema9bbd862018-11-02 16:07:481047 if (configuration.use_media_transport ||
1048 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 20:15:421049 if (!factory_->media_transport_factory()) {
1050 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 16:07:481051 << "PeerConnecton is initialized with use_media_transport = true or "
1052 << "use_media_transport_for_data_channels = true "
1053 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 20:15:421054 return false;
1055 }
1056
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:051057 if (configuration.use_media_transport ||
1058 configuration.use_media_transport_for_data_channels) {
1059 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1060 // RTP media transport is introduced. But until then, we require SDES to
1061 // be enabled.
1062 if (configuration.enable_dtls_srtp.has_value() &&
1063 configuration.enable_dtls_srtp.value()) {
1064 RTC_LOG(LS_WARNING)
1065 << "When media transport is used, SDES must be enabled. Set "
1066 "configuration.enable_dtls_srtp to false. use_media_transport="
1067 << configuration.use_media_transport
1068 << ", use_media_transport_for_data_channels="
1069 << configuration.use_media_transport_for_data_channels;
1070 return false;
1071 }
1072 }
1073
Piotr (Peter) Slatala55b91b92019-01-25 21:31:151074 config.use_media_transport_for_media = configuration.use_media_transport;
1075 config.use_media_transport_for_data_channels =
1076 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 20:15:421077 config.media_transport_factory = factory_->media_transport_factory();
1078 }
1079
Zhi Huange830e682018-03-30 17:48:351080 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:151081 signaling_thread(), network_thread(), port_allocator_.get(),
1082 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:351083 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:591084 this, &PeerConnection::OnTransportControllerConnectionState);
1085 transport_controller_->SignalStandardizedIceConnectionState.connect(
1086 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:171087 transport_controller_->SignalConnectionState.connect(
1088 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:351089 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:171090 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:351091 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:171092 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:351093 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:171094 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1095 transport_controller_->SignalDtlsHandshakeError.connect(
1096 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1097
1098 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:251099
deadbeefab9b2d12015-10-14 18:33:111100 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:011101 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:361102
Steve Antonba818672017-11-06 18:21:571103 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 22:55:091104 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 18:21:571105
Steve Anton75737c02017-11-06 18:37:171106 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1107 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1108 if (!configuration.certificates.empty()) {
1109 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1110 // just picking the first one. The decision should be made based on the DTLS
1111 // handshake. The DTLS negotiations need to know about all certificates.
1112 certificate = configuration.certificates[0];
1113 }
1114
Steve Antond25da372017-11-06 22:50:291115 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171116
1117 if (options.disable_encryption) {
1118 dtls_enabled_ = false;
1119 } else {
1120 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:471121 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:171122 // |configuration| can override the default |dtls_enabled_| value.
1123 if (configuration.enable_dtls_srtp) {
1124 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1125 }
1126 }
1127
Bjorn Mellem175aa2e2018-11-08 19:23:221128 if (configuration.use_media_transport_for_data_channels) {
1129 if (configuration.enable_rtp_data_channel) {
1130 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1131 "use_media_transport_for_data_channels are "
1132 "incompatible and cannot both be set to true";
1133 return false;
1134 }
1135 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1136 } else if (configuration.enable_rtp_data_channel) {
1137 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1138 // set. It takes precendence over the disable_sctp_data_channels
1139 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 18:37:171140 data_channel_type_ = cricket::DCT_RTP;
1141 } else {
1142 // DTLS has to be enabled to use SCTP.
1143 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1144 data_channel_type_ = cricket::DCT_SCTP;
1145 }
1146 }
1147
1148 video_options_.screencast_min_bitrate_kbps =
1149 configuration.screencast_min_bitrate;
1150 audio_options_.combined_audio_video_bwe =
1151 configuration.combined_audio_video_bwe;
1152
1153 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301154 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171155
1156 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301157 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171158
Jakob Ivarsson10403ae2018-11-27 14:45:201159 audio_options_.audio_jitter_buffer_min_delay_ms =
1160 configuration.audio_jitter_buffer_min_delay_ms;
1161
Jakob Ivarsson53eae872019-01-10 14:58:361162 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1163 configuration.audio_jitter_buffer_enable_rtx_handling;
1164
Steve Anton75737c02017-11-06 18:37:171165 // Whether the certificate generator/certificate is null or not determines
1166 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1167 // the right instructions by clearing the variables if needed.
1168 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471169 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171170 certificate = nullptr;
1171 } else if (certificate) {
1172 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471173 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171174 }
1175
1176 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1177 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-26 01:13:561178 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 18:37:171179 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1180 this, &PeerConnection::OnCertificateReady);
1181
1182 if (options.disable_encryption) {
1183 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1184 }
1185
1186 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 17:16:441187 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-11 00:08:051188 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:361189
Steve Anton4171afb2017-11-20 18:20:221190 // Add default audio/video transceivers for Plan B SDP.
1191 if (!IsUnifiedPlan()) {
1192 transceivers_.push_back(
1193 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1194 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1195 transceivers_.push_back(
1196 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1197 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1198 }
Harald Alvestrand183e09d2018-06-28 10:04:411199 int delay_ms =
1200 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401201 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1202 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 05:38:401203
1204 if (dependencies.video_bitrate_allocator_factory) {
1205 video_bitrate_allocator_factory_ =
1206 std::move(dependencies.video_bitrate_allocator_factory);
1207 } else {
1208 video_bitrate_allocator_factory_ =
1209 CreateBuiltinVideoBitrateAllocatorFactory();
1210 }
henrike@webrtc.org28e20752013-07-10 00:45:361211 return true;
1212}
1213
Steve Anton038834f2017-07-14 22:59:591214RTCError PeerConnection::ValidateConfiguration(
1215 const RTCConfiguration& config) const {
1216 if (config.ice_regather_interval_range &&
1217 config.continual_gathering_policy == GATHER_ONCE) {
1218 return RTCError(RTCErrorType::INVALID_PARAMETER,
1219 "ice_regather_interval_range specified but continual "
1220 "gathering policy is GATHER_ONCE");
1221 }
Qingsi Wangdea68892018-03-27 17:55:211222 auto result =
1223 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1224 return result;
Steve Anton038834f2017-07-14 22:59:591225}
1226
Yves Gerey665174f2018-06-19 13:03:051227rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 22:55:091228 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581229 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1230 "Plan SdpSemantics. Please use GetSenders "
1231 "instead.";
deadbeefab9b2d12015-10-14 18:33:111232 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361233}
1234
Yves Gerey665174f2018-06-19 13:03:051235rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 22:55:091236 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581237 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1238 "Plan SdpSemantics. Please use GetReceivers "
1239 "instead.";
deadbeefab9b2d12015-10-14 18:33:111240 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361241}
1242
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291243bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561244 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581245 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1246 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171247 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361248 if (IsClosed()) {
1249 return false;
1250 }
deadbeefab9b2d12015-10-14 18:33:111251 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361252 return false;
1253 }
deadbeefab9b2d12015-10-14 18:33:111254
1255 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431256 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1257 observer->SignalAudioTrackAdded.connect(this,
1258 &PeerConnection::OnAudioTrackAdded);
1259 observer->SignalAudioTrackRemoved.connect(
1260 this, &PeerConnection::OnAudioTrackRemoved);
1261 observer->SignalVideoTrackAdded.connect(this,
1262 &PeerConnection::OnVideoTrackAdded);
1263 observer->SignalVideoTrackRemoved.connect(
1264 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291265 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111266
deadbeefab9b2d12015-10-14 18:33:111267 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251268 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111269 }
1270 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251271 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111272 }
1273
tommi@webrtc.org03505bc2014-07-14 20:15:261274 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 10:24:141275 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361276 return true;
1277}
1278
1279void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561280 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581281 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1282 "Plan SdpSemantics. Please use RemoveTrack "
1283 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171284 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251285 if (!IsClosed()) {
1286 for (const auto& track : local_stream->GetAudioTracks()) {
1287 RemoveAudioTrack(track.get(), local_stream);
1288 }
1289 for (const auto& track : local_stream->GetVideoTracks()) {
1290 RemoveVideoTrack(track.get(), local_stream);
1291 }
deadbeefab9b2d12015-10-14 18:33:111292 }
deadbeefab9b2d12015-10-14 18:33:111293 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431294 stream_observers_.erase(
1295 std::remove_if(
1296 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291297 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281298 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431299 }),
1300 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111301
henrike@webrtc.org28e20752013-07-10 00:45:361302 if (IsClosed()) {
1303 return;
1304 }
Guido Urdaneta70c2db12019-04-16 10:24:141305 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361306}
1307
Steve Anton2d6c76a2018-01-06 01:10:521308RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571309 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101310 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 09:18:561311 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-06 01:10:521312 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571313 if (!track) {
1314 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1315 }
1316 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1317 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1319 "Track has invalid kind: " + track->kind());
1320 }
Steve Antonf9381f02017-12-14 18:23:571321 if (IsClosed()) {
1322 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1323 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421324 }
Steve Anton4171afb2017-11-20 18:20:221325 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571326 LOG_AND_RETURN_ERROR(
1327 RTCErrorType::INVALID_PARAMETER,
1328 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421329 }
Steve Antonf9381f02017-12-14 18:23:571330 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361331 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1332 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571333 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 10:24:141334 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171335 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571336 }
1337 return sender_or_error;
1338}
deadbeefe1f9d832016-01-14 23:35:421339
Steve Antonf9381f02017-12-14 18:23:571340RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1341PeerConnection::AddTrackPlanB(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101343 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361344 if (stream_ids.size() > 1u) {
1345 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1346 "AddTrack with more than one stream is not "
1347 "supported with Plan B semantics.");
1348 }
1349 std::vector<std::string> adjusted_stream_ids = stream_ids;
1350 if (adjusted_stream_ids.empty()) {
1351 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1352 }
Steve Anton02ee47c2018-01-11 00:26:061353 cricket::MediaType media_type =
1354 (track->kind() == MediaStreamTrackInterface::kAudioKind
1355 ? cricket::MEDIA_TYPE_AUDIO
1356 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361357 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201358 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421359 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051360 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221361 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221362 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181363 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361364 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221365 if (sender_info) {
1366 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421367 }
Steve Antonf9381f02017-12-14 18:23:571368 } else {
1369 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051370 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221371 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221372 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181373 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361374 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221375 if (sender_info) {
1376 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421377 }
deadbeefe1f9d832016-01-14 23:35:421378 }
Steve Anton02ee47c2018-01-11 00:26:061379 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571380}
deadbeefe1f9d832016-01-14 23:35:421381
Steve Antonf9381f02017-12-14 18:23:571382RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1383PeerConnection::AddTrackUnifiedPlan(
1384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101385 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571386 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1387 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231388 RTC_LOG(LS_INFO) << "Reusing an existing "
1389 << cricket::MediaTypeToString(transceiver->media_type())
1390 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571391 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121392 transceiver->internal()->set_direction(
1393 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571394 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121395 transceiver->internal()->set_direction(
1396 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571397 }
Steve Anton02ee47c2018-01-11 00:26:061398 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101399 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571400 } else {
1401 cricket::MediaType media_type =
1402 (track->kind() == MediaStreamTrackInterface::kAudioKind
1403 ? cricket::MEDIA_TYPE_AUDIO
1404 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231405 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1406 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501407 std::string sender_id = track->id();
1408 // Avoid creating a sender with an existing ID by generating a random ID.
1409 // This can happen if this is the second time AddTrack has created a sender
1410 // for this track.
1411 if (FindSenderById(sender_id)) {
1412 sender_id = rtc::CreateRandomUuid();
1413 }
Florent Castelli892acf02018-10-01 20:47:201414 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061415 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1416 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571417 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121418 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571419 }
Steve Antonf9381f02017-12-14 18:23:571420 return transceiver->sender();
1421}
1422
1423rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1424PeerConnection::FindFirstTransceiverForAddedTrack(
1425 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1426 RTC_DCHECK(track);
1427 for (auto transceiver : transceivers_) {
1428 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081429 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571430 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421431 !transceiver->internal()->has_ever_been_used_to_send() &&
1432 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571433 return transceiver;
1434 }
1435 }
1436 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421437}
1438
1439bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1440 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331441 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571442}
1443
Steve Anton24db5732018-07-23 17:27:331444RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571445 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 09:18:561446 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 18:23:571447 if (!sender) {
1448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1449 }
deadbeefe1f9d832016-01-14 23:35:421450 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1452 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421453 }
Steve Antonf9381f02017-12-14 18:23:571454 if (IsUnifiedPlan()) {
1455 auto transceiver = FindTransceiverBySender(sender);
1456 if (!transceiver || !sender->track()) {
1457 return RTCError::OK();
1458 }
1459 sender->SetTrack(nullptr);
1460 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121461 transceiver->internal()->set_direction(
1462 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571463 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121464 transceiver->internal()->set_direction(
1465 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571466 }
Steve Anton4171afb2017-11-20 18:20:221467 } else {
Steve Antonf9381f02017-12-14 18:23:571468 bool removed;
1469 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1470 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1471 } else {
1472 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1473 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1474 }
1475 if (!removed) {
1476 LOG_AND_RETURN_ERROR(
1477 RTCErrorType::INVALID_PARAMETER,
1478 "Couldn't find sender " + sender->id() + " to remove.");
1479 }
Steve Anton4171afb2017-11-20 18:20:221480 }
Guido Urdaneta70c2db12019-04-16 10:24:141481 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571482 return RTCError::OK();
1483}
1484
1485rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1486PeerConnection::FindTransceiverBySender(
1487 rtc::scoped_refptr<RtpSenderInterface> sender) {
1488 for (auto transceiver : transceivers_) {
1489 if (transceiver->sender() == sender) {
1490 return transceiver;
1491 }
1492 }
1493 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421494}
1495
Steve Anton9158ef62017-11-27 21:01:521496RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1497PeerConnection::AddTransceiver(
1498 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1499 return AddTransceiver(track, RtpTransceiverInit());
1500}
1501
1502RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1503PeerConnection::AddTransceiver(
1504 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1505 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561506 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581507 RTC_CHECK(IsUnifiedPlan())
1508 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521509 if (!track) {
1510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1511 }
1512 cricket::MediaType media_type;
1513 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1514 media_type = cricket::MEDIA_TYPE_AUDIO;
1515 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1516 media_type = cricket::MEDIA_TYPE_VIDEO;
1517 } else {
1518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1519 "Track kind is not audio or video");
1520 }
1521 return AddTransceiver(media_type, track, init);
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1526 return AddTransceiver(media_type, RtpTransceiverInit());
1527}
1528
1529RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1530PeerConnection::AddTransceiver(cricket::MediaType media_type,
1531 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561532 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581533 RTC_CHECK(IsUnifiedPlan())
1534 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521535 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1536 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1537 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1538 "media type is not audio or video");
1539 }
1540 return AddTransceiver(media_type, nullptr, init);
1541}
1542
1543RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1544PeerConnection::AddTransceiver(
1545 cricket::MediaType media_type,
1546 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071547 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 10:24:141548 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 21:01:521549 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1550 media_type == cricket::MEDIA_TYPE_VIDEO));
1551 if (track) {
1552 RTC_DCHECK_EQ(media_type,
1553 (track->kind() == MediaStreamTrackInterface::kAudioKind
1554 ? cricket::MEDIA_TYPE_AUDIO
1555 : cricket::MEDIA_TYPE_VIDEO));
1556 }
1557
Amit Hilbuche2a284d2019-03-05 20:36:311558 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1559 init.send_encodings.size(), 0, 7, 8);
1560
Amit Hilbuchaa584152019-02-07 01:09:521561 size_t num_rids = absl::c_count_if(init.send_encodings,
1562 [](const RtpEncodingParameters& encoding) {
1563 return !encoding.rid.empty();
1564 });
1565 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-07 01:09:521566 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-07 01:09:521567 RTCErrorType::INVALID_PARAMETER,
1568 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:391569 }
1570
Amit Hilbuchf4770402019-04-08 21:11:571571 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1572 [](const RtpEncodingParameters& encoding) {
1573 return !IsLegalRsidName(encoding.rid);
1574 })) {
1575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1576 "Invalid RID value provided.");
1577 }
1578
Amit Hilbuchaa584152019-02-07 01:09:521579 if (absl::c_any_of(init.send_encodings,
1580 [](const RtpEncodingParameters& encoding) {
1581 return encoding.ssrc.has_value();
1582 })) {
1583 LOG_AND_RETURN_ERROR(
1584 RTCErrorType::UNSUPPORTED_PARAMETER,
1585 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 20:47:201586 }
1587
1588 RtpParameters parameters;
1589 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-07 01:09:521590
1591 // Encodings are dropped from the tail if too many are provided.
1592 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1593 parameters.encodings.erase(
1594 parameters.encodings.begin() + kMaxSimulcastStreams,
1595 parameters.encodings.end());
1596 }
1597
1598 // Single RID should be removed.
1599 if (parameters.encodings.size() == 1 &&
1600 !parameters.encodings[0].rid.empty()) {
1601 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1602 parameters.encodings[0].rid.clear();
1603 }
1604
1605 // If RIDs were not provided, they are generated for simulcast scenario.
1606 if (parameters.encodings.size() > 1 && num_rids == 0) {
1607 rtc::UniqueStringGenerator rid_generator;
1608 for (RtpEncodingParameters& encoding : parameters.encodings) {
1609 encoding.rid = rid_generator();
1610 }
1611 }
1612
Florent Castelli892acf02018-10-01 20:47:201613 if (UnimplementedRtpParameterHasValue(parameters)) {
1614 LOG_AND_RETURN_ERROR(
1615 RTCErrorType::UNSUPPORTED_PARAMETER,
1616 "Attempted to set an unimplemented parameter of RtpParameters.");
1617 }
Steve Anton9158ef62017-11-27 21:01:521618
Florent Castellic1a0bcb2019-01-29 13:26:481619 auto result = cricket::CheckRtpParametersValues(parameters);
1620 if (!result.ok()) {
1621 LOG_AND_RETURN_ERROR(result.type(), result.message());
1622 }
1623
Steve Anton3d954a62018-04-02 18:27:231624 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1625 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501626 // Set the sender ID equal to the track ID if the track is specified unless
1627 // that sender ID is already in use.
1628 std::string sender_id =
1629 (track && !FindSenderById(track->id()) ? track->id()
1630 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 20:47:201631 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-07 01:09:521632 parameters.encodings);
Steve Anton02ee47c2018-01-11 00:26:061633 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1634 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1635 transceiver->internal()->set_direction(init.direction);
1636
Guido Urdaneta70c2db12019-04-16 10:24:141637 if (update_negotiation_needed) {
1638 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071639 }
Steve Antonf9381f02017-12-14 18:23:571640
1641 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1642}
1643
Steve Anton02ee47c2018-01-11 00:26:061644rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1645PeerConnection::CreateSender(
1646 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361647 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061648 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201649 const std::vector<std::string>& stream_ids,
1650 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 08:57:011651 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 21:01:521652 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061653 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1654 RTC_DCHECK(!track ||
1655 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1656 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1657 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 23:20:211658 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341659 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061660 } else {
1661 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1662 RTC_DCHECK(!track ||
1663 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1664 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 23:20:211665 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341666 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061667 }
Steve Anton111fdfd2018-06-25 20:03:361668 bool set_track_succeeded = sender->SetTrack(track);
1669 RTC_DCHECK(set_track_succeeded);
1670 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 20:47:201671 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061672 return sender;
1673}
1674
1675rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1676PeerConnection::CreateReceiver(cricket::MediaType media_type,
1677 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521678 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1679 receiver;
Steve Anton9158ef62017-11-27 21:01:521680 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521681 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531682 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1683 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341684 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521685 } else {
Steve Anton02ee47c2018-01-11 00:26:061686 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521687 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531688 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1689 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341690 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521691 }
Steve Anton02ee47c2018-01-11 00:26:061692 return receiver;
1693}
1694
1695rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1696PeerConnection::CreateAndAddTransceiver(
1697 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1698 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1699 receiver) {
Steve Anton07563732018-06-26 18:13:501700 // Ensure that the new sender does not have an ID that is already in use by
1701 // another sender.
1702 // Allow receiver IDs to conflict since those come from remote SDP (which
1703 // could be invalid, but should not cause a crash).
1704 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061705 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 17:25:511706 signaling_thread(),
1707 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 21:01:521708 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121709 transceiver->internal()->SignalNegotiationNeeded.connect(
1710 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571711 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521712}
1713
Steve Anton52d86772018-02-20 23:48:121714void PeerConnection::OnNegotiationNeeded() {
1715 RTC_DCHECK_RUN_ON(signaling_thread());
1716 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 10:24:141717 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121718}
1719
deadbeeffac06552015-11-25 19:26:011720rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441721 const std::string& kind,
1722 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 22:55:091723 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581724 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1725 "Plan SdpSemantics. Please use AddTransceiver "
1726 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171727 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251728 if (IsClosed()) {
1729 return nullptr;
1730 }
Steve Anton4171afb2017-11-20 18:20:221731
Seth Hampson5b4f0752018-04-02 23:31:361732 // Internally we need to have one stream with Plan B semantics, so we
1733 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101734 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361735 if (stream_id.empty()) {
1736 stream_ids.push_back(rtc::CreateRandomUuid());
1737 RTC_LOG(LS_INFO)
1738 << "No stream_id specified for sender. Generated stream ID: "
1739 << stream_ids[0];
1740 } else {
Seth Hampson845e8782018-03-02 19:34:101741 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061742 }
1743
Steve Anton4171afb2017-11-20 18:20:221744 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391745 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011746 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211747 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 20:03:361748 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-14 00:26:051749 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391750 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061751 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221752 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011753 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211754 auto video_sender =
1755 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-14 00:26:051756 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391757 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061758 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221759 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011760 } else {
Mirko Bonadei675513b2017-11-09 10:09:251761 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221762 return nullptr;
deadbeeffac06552015-11-25 19:26:011763 }
Steve Anton111fdfd2018-06-25 20:03:361764 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221765
deadbeefe1f9d832016-01-14 23:35:421766 return new_sender;
deadbeeffac06552015-11-25 19:26:011767}
1768
deadbeef70ab1a12015-09-28 23:53:551769std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1770 const {
Karl Wiberga58e1692019-03-26 12:33:431771 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:391772 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 16:29:421773 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 18:20:221774 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391775 }
1776 return ret;
deadbeef70ab1a12015-09-28 23:53:551777}
1778
Steve Anton4171afb2017-11-20 18:20:221779std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1780PeerConnection::GetSendersInternal() const {
1781 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1782 all_senders;
Mirko Bonadei739baf02019-01-27 16:29:421783 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:221784 auto senders = transceiver->internal()->senders();
1785 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1786 }
1787 return all_senders;
1788}
1789
deadbeef70ab1a12015-09-28 23:53:551790std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1791PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 12:33:431792 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:391793 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221794 for (const auto& receiver : GetReceiversInternal()) {
1795 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391796 }
1797 return ret;
deadbeef70ab1a12015-09-28 23:53:551798}
1799
Steve Anton4171afb2017-11-20 18:20:221800std::vector<
1801 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1802PeerConnection::GetReceiversInternal() const {
1803 std::vector<
1804 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1805 all_receivers;
Mirko Bonadei739baf02019-01-27 16:29:421806 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:221807 auto receivers = transceiver->internal()->receivers();
1808 all_receivers.insert(all_receivers.end(), receivers.begin(),
1809 receivers.end());
1810 }
1811 return all_receivers;
1812}
1813
Steve Anton9158ef62017-11-27 21:01:521814std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1815PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 22:55:091816 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581817 RTC_CHECK(IsUnifiedPlan())
1818 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521819 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:421820 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 21:01:521821 all_transceivers.push_back(transceiver);
1822 }
1823 return all_transceivers;
1824}
1825
henrike@webrtc.org28e20752013-07-10 00:45:361826bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491827 MediaStreamTrackInterface* track,
1828 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171829 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:011830 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 08:57:561831 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251832 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361833 return false;
1834 }
1835
tommi@webrtc.org03505bc2014-07-14 20:15:261836 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151837 // The StatsCollector is used to tell if a track is valid because it may
1838 // remember tracks that the PeerConnection previously removed.
1839 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251840 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1841 << track->id();
zhihuange9e94c32016-11-04 18:38:151842 return false;
1843 }
Steve Antonad182762018-09-05 20:22:401844 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1845 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361846 return true;
1847}
1848
hbos74e1a4f2016-09-16 06:33:011849void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201850 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:011851 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-16 06:33:011852 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201853 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011854 stats_collector_->GetStatsReport(callback);
1855}
1856
Henrik Boström1df1bf82018-03-20 12:24:201857void PeerConnection::GetStats(
1858 rtc::scoped_refptr<RtpSenderInterface> selector,
1859 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1860 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:011861 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:201862 RTC_DCHECK(callback);
1863 RTC_DCHECK(stats_collector_);
1864 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1865 if (selector) {
1866 for (const auto& proxy_transceiver : transceivers_) {
1867 for (const auto& proxy_sender :
1868 proxy_transceiver->internal()->senders()) {
1869 if (proxy_sender == selector) {
1870 internal_sender = proxy_sender->internal();
1871 break;
1872 }
1873 }
1874 if (internal_sender)
1875 break;
1876 }
1877 }
Sebastian Jansson6eb8a162018-11-16 10:29:551878 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:201879 // belong to the PeerConnection (in Plan B, senders can be removed from the
1880 // PeerConnection). This means that "all the stats objects representing the
1881 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1882 // produces an empty stats report.
1883 stats_collector_->GetStatsReport(internal_sender, callback);
1884}
1885
1886void PeerConnection::GetStats(
1887 rtc::scoped_refptr<RtpReceiverInterface> selector,
1888 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1889 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:011890 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:201891 RTC_DCHECK(callback);
1892 RTC_DCHECK(stats_collector_);
1893 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1894 if (selector) {
1895 for (const auto& proxy_transceiver : transceivers_) {
1896 for (const auto& proxy_receiver :
1897 proxy_transceiver->internal()->receivers()) {
1898 if (proxy_receiver == selector) {
1899 internal_receiver = proxy_receiver->internal();
1900 break;
1901 }
1902 }
1903 if (internal_receiver)
1904 break;
1905 }
1906 }
Sebastian Jansson6eb8a162018-11-16 10:29:551907 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:201908 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1909 // the PeerConnection). This means that "all the stats objects representing
1910 // the selector" is an empty set. Invoking GetStatsReport() with a null
1911 // selector produces an empty stats report.
1912 stats_collector_->GetStatsReport(internal_receiver, callback);
1913}
1914
henrike@webrtc.org28e20752013-07-10 00:45:361915PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 12:00:071916 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:361917 return signaling_state_;
1918}
1919
henrike@webrtc.org28e20752013-07-10 00:45:361920PeerConnectionInterface::IceConnectionState
1921PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:071922 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:361923 return ice_connection_state_;
1924}
1925
Alex Loiko9289eda2018-11-23 16:18:591926PeerConnectionInterface::IceConnectionState
1927PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:071928 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:591929 return standardized_ice_connection_state_;
1930}
1931
Jonas Olsson635474e2018-10-18 13:58:171932PeerConnectionInterface::PeerConnectionState
1933PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:071934 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 13:58:171935 return connection_state_;
1936}
1937
henrike@webrtc.org28e20752013-07-10 00:45:361938PeerConnectionInterface::IceGatheringState
1939PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 12:00:071940 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:361941 return ice_gathering_state_;
1942}
1943
Yves Gerey665174f2018-06-19 13:03:051944rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361945 const std::string& label,
1946 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 09:17:471947 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:171948 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501949
deadbeefab9b2d12015-10-14 18:33:111950 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111951
kwibergd1fe2812016-04-27 13:47:291952 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581953 if (config) {
1954 internal_config.reset(new InternalDataChannelInit(*config));
1955 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521956 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111957 InternalCreateDataChannel(label, internal_config.get()));
1958 if (!channel.get()) {
1959 return nullptr;
1960 }
henrike@webrtc.org28e20752013-07-10 00:45:361961
jiayl@webrtc.org001fd2d2014-05-29 15:31:111962 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1963 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171964 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 10:24:141965 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111966 }
Harald Alvestrand8ebba742018-05-31 12:00:341967 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361968 return DataChannelProxy::Create(signaling_thread(), channel.get());
1969}
1970
1971void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161972 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 22:55:091973 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:171974 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511975
nisse7ce109a2017-01-31 08:57:561976 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251977 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161978 return;
1979 }
deadbeefab9b2d12015-10-14 18:33:111980
Steve Anton8d3444d2017-10-20 22:30:511981 if (IsClosed()) {
1982 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251983 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031984 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101985 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511986 return;
1987 }
1988
zhihuang1c378ed2017-08-17 21:10:501989 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111990 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251991 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031992 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101993 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111994 return;
1995 }
1996
Steve Anton22da89f2018-01-25 21:58:071997 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1998 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1999 if (IsUnifiedPlan()) {
2000 RTCError error = HandleLegacyOfferOptions(options);
2001 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:032002 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:072003 return;
2004 }
2005 }
2006
zhihuang1c378ed2017-08-17 21:10:502007 cricket::MediaSessionOptions session_options;
2008 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:292009 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362010}
2011
Steve Anton22da89f2018-01-25 21:58:072012RTCError PeerConnection::HandleLegacyOfferOptions(
2013 const RTCOfferAnswerOptions& options) {
2014 RTC_DCHECK(IsUnifiedPlan());
2015
2016 if (options.offer_to_receive_audio == 0) {
2017 RemoveRecvDirectionFromReceivingTransceiversOfType(
2018 cricket::MEDIA_TYPE_AUDIO);
2019 } else if (options.offer_to_receive_audio == 1) {
2020 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2021 } else if (options.offer_to_receive_audio > 1) {
2022 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2023 "offer_to_receive_audio > 1 is not supported.");
2024 }
2025
2026 if (options.offer_to_receive_video == 0) {
2027 RemoveRecvDirectionFromReceivingTransceiversOfType(
2028 cricket::MEDIA_TYPE_VIDEO);
2029 } else if (options.offer_to_receive_video == 1) {
2030 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2031 } else if (options.offer_to_receive_video > 1) {
2032 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2033 "offer_to_receive_video > 1 is not supported.");
2034 }
2035
2036 return RTCError::OK();
2037}
2038
2039void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2040 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 16:29:422041 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:232042 RtpTransceiverDirection new_direction =
2043 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2044 if (new_direction != transceiver->direction()) {
2045 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2046 << " transceiver (MID="
2047 << transceiver->mid().value_or("<not set>") << ") from "
2048 << RtpTransceiverDirectionToString(
2049 transceiver->direction())
2050 << " to "
2051 << RtpTransceiverDirectionToString(new_direction)
2052 << " since CreateOffer specified offer_to_receive=0";
2053 transceiver->internal()->set_direction(new_direction);
2054 }
Steve Anton22da89f2018-01-25 21:58:072055 }
2056}
2057
2058void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2059 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 09:18:562060 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 21:58:072061 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:232062 RTC_LOG(LS_INFO)
2063 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2064 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:072065 RtpTransceiverInit init;
2066 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 10:24:142067 AddTransceiver(media_type, nullptr, init,
2068 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 21:58:072069 }
2070}
2071
2072std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2073PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2074 std::vector<
2075 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2076 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:422077 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082078 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:072079 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2080 receiving_transceivers.push_back(transceiver);
2081 }
2082 }
2083 return receiving_transceivers;
2084}
2085
htaa2a49d92016-03-04 10:51:392086void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2087 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 12:00:072088 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 10:51:392089 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:562090 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252091 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:392092 return;
2093 }
2094
Steve Antondffead82018-02-06 18:31:292095 if (!(signaling_state_ == kHaveRemoteOffer ||
2096 signaling_state_ == kHaveLocalPrAnswer)) {
2097 std::string error =
2098 "PeerConnection cannot create an answer in a state other than "
2099 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:252100 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032101 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102102 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:512103 return;
2104 }
2105
Steve Antondffead82018-02-06 18:31:292106 // The remote description should be set if we're in the right state.
2107 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:512108
Steve Anton22da89f2018-01-25 21:58:072109 if (IsUnifiedPlan()) {
2110 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2111 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2112 "supported with Unified Plan semantics. Use the "
2113 "RtpTransceiver API instead.";
2114 }
2115 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2116 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2117 "supported with Unified Plan semantics. Use the "
2118 "RtpTransceiver API instead.";
2119 }
2120 }
2121
htaa2a49d92016-03-04 10:51:392122 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:502123 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:392124
Steve Antond25da372017-11-06 22:50:292125 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362126}
2127
2128void PeerConnection::SetLocalDescription(
2129 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:422130 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 22:55:092131 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:172132 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:562133
Steve Anton80dd7b52018-02-17 01:08:422134 // The SetLocalDescription contract is that we take ownership of the session
2135 // description regardless of the outcome, so wrap it in a unique_ptr right
2136 // away. Ideally, SetLocalDescription's signature will be changed to take the
2137 // description as a unique_ptr argument to formalize this agreement.
2138 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2139
nisse7ce109a2017-01-31 08:57:562140 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252141 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362142 return;
2143 }
Steve Anton8a006912017-12-04 23:25:562144
henrike@webrtc.org28e20752013-07-10 00:45:362145 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:032146 PostSetSessionDescriptionFailure(
2147 observer,
2148 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362149 return;
2150 }
Steve Anton8d3444d2017-10-20 22:30:512151
Steve Anton80dd7b52018-02-17 01:08:422152 // If a session error has occurred the PeerConnection is in a possibly
2153 // inconsistent state so fail right away.
2154 if (session_error() != SessionError::kNone) {
2155 std::string error_message = GetSessionErrorMsg();
2156 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032157 PostSetSessionDescriptionFailure(
2158 observer,
2159 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422160 return;
2161 }
Steve Anton8d3444d2017-10-20 22:30:512162
Steve Anton80dd7b52018-02-17 01:08:422163 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2164 if (!error.ok()) {
2165 std::string error_message = GetSetDescriptionErrorMessage(
2166 cricket::CS_LOCAL, desc->GetType(), error);
2167 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032168 PostSetSessionDescriptionFailure(
2169 observer,
2170 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422171 return;
2172 }
2173
2174 // Grab the description type before moving ownership to ApplyLocalDescription,
2175 // which may destroy it before returning.
2176 const SdpType type = desc->GetType();
2177
2178 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:562179 // |desc| may be destroyed at this point.
2180
2181 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422182 // If ApplyLocalDescription fails, the PeerConnection could be in an
2183 // inconsistent state, so act conservatively here and set the session error
2184 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2185 SetSessionError(SessionError::kContent, error.message());
2186 std::string error_message =
2187 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2188 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032189 PostSetSessionDescriptionFailure(
2190 observer,
2191 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:512192 return;
2193 }
Steve Anton8a006912017-12-04 23:25:562194 RTC_DCHECK(local_description());
2195
2196 PostSetSessionDescriptionSuccess(observer);
2197
Steve Antonad182762018-09-05 20:22:402198 // MaybeStartGathering needs to be called after posting
2199 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2200 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:562201 transport_controller_->MaybeStartGathering();
2202
Steve Antona3a92c22017-12-07 18:27:412203 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562204 // TODO(deadbeef): We already had to hop to the network thread for
2205 // MaybeStartGathering...
2206 network_thread()->Invoke<void>(
2207 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2208 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302209 // Make UMA notes about what was agreed to.
2210 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562211 }
Guido Urdaneta70c2db12019-04-16 10:24:142212
2213 if (IsUnifiedPlan()) {
2214 bool was_negotiation_needed = is_negotiation_needed_;
2215 UpdateNegotiationNeeded();
2216 if (signaling_state() == kStable && was_negotiation_needed &&
2217 is_negotiation_needed_) {
2218 Observer()->OnRenegotiationNeeded();
2219 }
2220 }
2221
Harald Alvestrand8ebba742018-05-31 12:00:342222 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562223}
2224
2225RTCError PeerConnection::ApplyLocalDescription(
2226 std::unique_ptr<SessionDescriptionInterface> desc) {
2227 RTC_DCHECK_RUN_ON(signaling_thread());
2228 RTC_DCHECK(desc);
2229
henrike@webrtc.org28e20752013-07-10 00:45:362230 // Update stats here so that we have the most recent stats for tracks and
2231 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262232 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562233
Steve Antondcc3c022017-12-23 00:02:542234 // Take a reference to the old local description since it's used below to
2235 // compare against the new local description. When setting the new local
2236 // description, grab ownership of the replaced session description in case it
2237 // is the same as |old_local_description|, to keep it alive for the duration
2238 // of the method.
2239 const SessionDescriptionInterface* old_local_description =
2240 local_description();
2241 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352242 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512243 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542244 replaced_local_description = pending_local_description_
2245 ? std::move(pending_local_description_)
2246 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562247 current_local_description_ = std::move(desc);
2248 pending_local_description_ = nullptr;
2249 current_remote_description_ = std::move(pending_remote_description_);
2250 } else {
Steve Antondcc3c022017-12-23 00:02:542251 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562252 pending_local_description_ = std::move(desc);
2253 }
2254 // The session description to apply now must be accessed by
2255 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442256 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112257
Amit Hilbuche2a284d2019-03-05 20:36:312258 // Report statistics about any use of simulcast.
2259 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2260 *local_description()->description());
2261
Bjorn Mellem175aa2e2018-11-08 19:23:222262 if (!is_caller_) {
2263 if (remote_description()) {
2264 // Remote description was applied first, so this PC is the callee.
2265 is_caller_ = false;
2266 } else {
2267 // Local description is applied first, so this PC is the caller.
2268 is_caller_ = true;
2269 }
2270 }
2271
Zhi Huange830e682018-03-30 17:48:352272 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2273 if (!error.ok()) {
2274 return error;
2275 }
2276
Steve Antondcc3c022017-12-23 00:02:542277 if (IsUnifiedPlan()) {
2278 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482279 cricket::CS_LOCAL, *local_description(), old_local_description,
2280 remote_description());
Steve Anton8a006912017-12-04 23:25:562281 if (!error.ok()) {
2282 return error;
2283 }
Steve Anton0f5400a2018-07-17 21:25:362284 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2285 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:422286 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:402287 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2288 // Note that code paths that don't set MID won't be able to use
2289 // information about DTLS transports.
2290 if (transceiver->mid()) {
2291 auto dtls_transport =
2292 LookupDtlsTransportByMidInternal(*transceiver->mid());
2293 transceiver->internal()->sender_internal()->set_transport(
2294 dtls_transport);
2295 transceiver->internal()->receiver_internal()->set_transport(
2296 dtls_transport);
2297 }
2298
Steve Antondcc3c022017-12-23 00:02:542299 const ContentInfo* content =
2300 FindMediaSectionForTransceiver(transceiver, local_description());
2301 if (!content) {
2302 continue;
2303 }
2304 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362305 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2306 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542307 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362308 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2309 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2310 // "recvonly", process the removal of a remote track for the media
2311 // description, given transceiver, removeList, and muteTracks.
2312 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2313 (transceiver->internal()->fired_direction() &&
2314 RtpTransceiverDirectionHasRecv(
2315 *transceiver->internal()->fired_direction()))) {
2316 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2317 &removed_streams);
2318 }
2319 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2320 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542321 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362322 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542323 }
Steve Anton0f5400a2018-07-17 21:25:362324 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162325 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:422326 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162327 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362328 }
Mirko Bonadei739baf02019-01-27 16:29:422329 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162330 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542331 }
2332 } else {
Zhi Huange830e682018-03-30 17:48:352333 // Media channels will be created only when offer is set. These may use new
2334 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542335 if (type == SdpType::kOffer) {
2336 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2337 // description is applied. Restore back to old description.
2338 RTCError error = CreateChannels(*local_description()->description());
2339 if (!error.ok()) {
2340 return error;
2341 }
2342 }
Steve Antondcc3c022017-12-23 00:02:542343 // Remove unused channels if MediaContentDescription is rejected.
2344 RemoveUnusedChannels(local_description()->description());
2345 }
Steve Anton8a006912017-12-04 23:25:562346
Zhi Huange830e682018-03-30 17:48:352347 error = UpdateSessionState(type, cricket::CS_LOCAL,
2348 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562349 if (!error.ok()) {
2350 return error;
2351 }
Steve Antondcc3c022017-12-23 00:02:542352
Steve Anton8a006912017-12-04 23:25:562353 if (remote_description()) {
2354 // Now that we have a local description, we can push down remote candidates.
2355 UseCandidatesInSessionDescription(remote_description());
2356 }
2357
2358 pending_ice_restarts_.clear();
2359 if (session_error() != SessionError::kNone) {
2360 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2361 }
2362
deadbeefab9b2d12015-10-14 18:33:112363 // If setting the description decided our SSL role, allocate any necessary
2364 // SCTP sids.
2365 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222366 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112367 AllocateSctpSids(role);
2368 }
2369
Steve Antond3679212018-01-18 01:41:022370 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 16:29:422371 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-18 01:41:022372 const ContentInfo* content =
2373 FindMediaSectionForTransceiver(transceiver, local_description());
2374 if (!content) {
2375 continue;
2376 }
Amit Hilbuchbcd39d42019-01-26 01:13:562377 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2378 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 18:32:272379 // 0 is a special value meaning "this sender has no associated send
2380 // stream". Need to call this so the sender won't attempt to configure
2381 // a no longer existing stream and run into DCHECKs in the lower
2382 // layers.
2383 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-26 01:13:562384 } else {
2385 // Get the StreamParams from the channel which could generate SSRCs.
2386 const std::vector<StreamParams>& streams = channel->local_streams();
2387 transceiver->internal()->sender_internal()->set_stream_ids(
2388 streams[0].stream_ids());
2389 transceiver->internal()->sender_internal()->SetSsrc(
2390 streams[0].first_ssrc());
Steve Antond3679212018-01-18 01:41:022391 }
2392 }
2393 } else {
2394 // Plan B semantics.
2395
Steve Antondcc3c022017-12-23 00:02:542396 // Update state and SSRC of local MediaStreams and DataChannels based on the
2397 // local session description.
2398 const cricket::ContentInfo* audio_content =
2399 GetFirstAudioContent(local_description()->description());
2400 if (audio_content) {
2401 if (audio_content->rejected) {
2402 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2403 } else {
2404 const cricket::AudioContentDescription* audio_desc =
2405 audio_content->media_description()->as_audio();
2406 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2407 }
deadbeeffaac4972015-11-12 23:33:072408 }
deadbeefab9b2d12015-10-14 18:33:112409
Steve Antondcc3c022017-12-23 00:02:542410 const cricket::ContentInfo* video_content =
2411 GetFirstVideoContent(local_description()->description());
2412 if (video_content) {
2413 if (video_content->rejected) {
2414 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2415 } else {
2416 const cricket::VideoContentDescription* video_desc =
2417 video_content->media_description()->as_video();
2418 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2419 }
deadbeeffaac4972015-11-12 23:33:072420 }
deadbeefab9b2d12015-10-14 18:33:112421 }
2422
2423 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442424 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112425 if (data_content) {
Harald Alvestrand141c0ad2019-05-05 19:00:002426 const cricket::DataContentDescription* data_desc =
2427 data_content->media_description()->as_data();
2428 if (absl::StartsWith(data_desc->protocol(),
2429 cricket::kMediaProtocolRtpPrefix)) {
2430 UpdateLocalRtpDataChannels(data_desc->streams());
deadbeefab9b2d12015-10-14 18:33:112431 }
2432 }
2433
Steve Anton8a006912017-12-04 23:25:562434 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362435}
2436
Steve Anton06817cd2018-12-18 23:55:302437// The SDP parser used to populate these values by default for the 'content
2438// name' if an a=mid line was absent.
2439static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2440 switch (media_type) {
2441 case cricket::MEDIA_TYPE_AUDIO:
2442 return cricket::CN_AUDIO;
2443 case cricket::MEDIA_TYPE_VIDEO:
2444 return cricket::CN_VIDEO;
2445 case cricket::MEDIA_TYPE_DATA:
2446 return cricket::CN_DATA;
2447 }
2448 RTC_NOTREACHED();
2449 return "";
2450}
2451
2452void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 18:44:532453 cricket::SessionDescription* new_remote_description) {
2454 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 23:55:302455 const cricket::ContentInfos& local_contents =
2456 (local_description() ? local_description()->description()->contents()
2457 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 18:44:532458 const cricket::ContentInfos& remote_contents =
2459 (remote_description() ? remote_description()->description()->contents()
2460 : cricket::ContentInfos());
2461 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2462 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 23:55:302463 if (!content.name.empty()) {
2464 continue;
2465 }
Amit Hilbuchae3df542019-01-07 20:13:082466 std::string new_mid;
Steve Anton06817cd2018-12-18 23:55:302467 absl::string_view source_explanation;
2468 if (IsUnifiedPlan()) {
2469 if (i < local_contents.size()) {
2470 new_mid = local_contents[i].name;
2471 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 18:44:532472 } else if (i < remote_contents.size()) {
2473 new_mid = remote_contents[i].name;
2474 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 23:55:302475 } else {
Amit Hilbuchae3df542019-01-07 20:13:082476 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 23:55:302477 source_explanation = "generated just now";
2478 }
2479 } else {
Amit Hilbuchae3df542019-01-07 20:13:082480 new_mid = std::string(
2481 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 23:55:302482 source_explanation = "to match pre-existing behavior";
2483 }
Steve Antond7180cc2019-02-07 18:44:532484 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 20:13:082485 content.name = new_mid;
Steve Antond7180cc2019-02-07 18:44:532486 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 23:55:302487 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2488 << " is missing an a=mid line. Filling in the value '"
2489 << new_mid << "' " << source_explanation << ".";
2490 }
2491}
2492
henrike@webrtc.org28e20752013-07-10 00:45:362493void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072494 SetSessionDescriptionObserver* observer,
2495 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322496 SetRemoteDescription(
2497 std::unique_ptr<SessionDescriptionInterface>(desc),
2498 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2499 new SetRemoteDescriptionObserverAdapter(this, observer)));
2500}
2501
2502void PeerConnection::SetRemoteDescription(
2503 std::unique_ptr<SessionDescriptionInterface> desc,
2504 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 22:55:092505 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:172506 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562507
nisse7ce109a2017-01-31 08:57:562508 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252509 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362510 return;
2511 }
Steve Anton8a006912017-12-04 23:25:562512
henrike@webrtc.org28e20752013-07-10 00:45:362513 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322514 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562515 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362516 return;
2517 }
Steve Anton8d3444d2017-10-20 22:30:512518
Steve Anton80dd7b52018-02-17 01:08:422519 // If a session error has occurred the PeerConnection is in a possibly
2520 // inconsistent state so fail right away.
2521 if (session_error() != SessionError::kNone) {
2522 std::string error_message = GetSessionErrorMsg();
2523 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2524 observer->OnSetRemoteDescriptionComplete(
2525 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2526 return;
2527 }
Steve Anton71439a62018-02-15 19:53:062528
Steve Antonba42e992018-04-09 21:10:012529 if (desc->GetType() == SdpType::kOffer) {
2530 // Report to UMA the format of the received offer.
2531 ReportSdpFormatReceived(*desc);
2532 }
2533
Steve Anton06817cd2018-12-18 23:55:302534 // Handle remote descriptions missing a=mid lines for interop with legacy end
2535 // points.
2536 FillInMissingRemoteMids(desc->description());
2537
Steve Anton80dd7b52018-02-17 01:08:422538 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062539 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422540 std::string error_message = GetSetDescriptionErrorMessage(
2541 cricket::CS_REMOTE, desc->GetType(), error);
2542 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062543 observer->OnSetRemoteDescriptionComplete(
2544 RTCError(error.type(), std::move(error_message)));
2545 return;
2546 }
Steve Anton71439a62018-02-15 19:53:062547
Steve Anton80dd7b52018-02-17 01:08:422548 // Grab the description type before moving ownership to
2549 // ApplyRemoteDescription, which may destroy it before returning.
2550 const SdpType type = desc->GetType();
2551
2552 error = ApplyRemoteDescription(std::move(desc));
2553 // |desc| may be destroyed at this point.
2554
2555 if (!error.ok()) {
2556 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2557 // inconsistent state, so act conservatively here and set the session error
2558 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2559 SetSessionError(SessionError::kContent, error.message());
2560 std::string error_message =
2561 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2562 RTC_LOG(LS_ERROR) << error_message;
2563 observer->OnSetRemoteDescriptionComplete(
2564 RTCError(error.type(), std::move(error_message)));
2565 return;
2566 }
2567 RTC_DCHECK(remote_description());
2568
2569 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562570 // TODO(deadbeef): We already had to hop to the network thread for
2571 // MaybeStartGathering...
2572 network_thread()->Invoke<void>(
2573 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2574 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002575 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302576 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562577 }
2578
Guido Urdaneta70c2db12019-04-16 10:24:142579 if (IsUnifiedPlan()) {
2580 bool was_negotiation_needed = is_negotiation_needed_;
2581 UpdateNegotiationNeeded();
2582 if (signaling_state() == kStable && was_negotiation_needed &&
2583 is_negotiation_needed_) {
2584 Observer()->OnRenegotiationNeeded();
2585 }
2586 }
2587
Steve Anton8a006912017-12-04 23:25:562588 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342589 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562590}
2591
2592RTCError PeerConnection::ApplyRemoteDescription(
2593 std::unique_ptr<SessionDescriptionInterface> desc) {
2594 RTC_DCHECK_RUN_ON(signaling_thread());
2595 RTC_DCHECK(desc);
2596
henrike@webrtc.org28e20752013-07-10 00:45:362597 // Update stats here so that we have the most recent stats for tracks and
2598 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262599 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562600
Steve Antondcc3c022017-12-23 00:02:542601 // Take a reference to the old remote description since it's used below to
2602 // compare against the new remote description. When setting the new remote
2603 // description, grab ownership of the replaced session description in case it
2604 // is the same as |old_remote_description|, to keep it alive for the duration
2605 // of the method.
Steve Anton8a006912017-12-04 23:25:562606 const SessionDescriptionInterface* old_remote_description =
2607 remote_description();
Steve Anton8a006912017-12-04 23:25:562608 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512609 SdpType type = desc->GetType();
2610 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562611 replaced_remote_description = pending_remote_description_
2612 ? std::move(pending_remote_description_)
2613 : std::move(current_remote_description_);
2614 current_remote_description_ = std::move(desc);
2615 pending_remote_description_ = nullptr;
2616 current_local_description_ = std::move(pending_local_description_);
2617 } else {
2618 replaced_remote_description = std::move(pending_remote_description_);
2619 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362620 }
Steve Anton8a006912017-12-04 23:25:562621 // The session description to apply now must be accessed by
2622 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442623 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362624
Amit Hilbuche2a284d2019-03-05 20:36:312625 // Report statistics about any use of simulcast.
2626 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2627 *remote_description()->description());
2628
Zhi Huange830e682018-03-30 17:48:352629 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2630 if (!error.ok()) {
2631 return error;
2632 }
Steve Anton8a006912017-12-04 23:25:562633 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542634 if (IsUnifiedPlan()) {
2635 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482636 cricket::CS_REMOTE, *remote_description(), local_description(),
2637 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562638 if (!error.ok()) {
2639 return error;
2640 }
Steve Antondcc3c022017-12-23 00:02:542641 } else {
Zhi Huange830e682018-03-30 17:48:352642 // Media channels will be created only when offer is set. These may use new
2643 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542644 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352645 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542646 // description is applied. Restore back to old description.
2647 RTCError error = CreateChannels(*remote_description()->description());
2648 if (!error.ok()) {
2649 return error;
2650 }
2651 }
Steve Antondcc3c022017-12-23 00:02:542652 // Remove unused channels if MediaContentDescription is rejected.
2653 RemoveUnusedChannels(remote_description()->description());
2654 }
Steve Anton8a006912017-12-04 23:25:562655
Zhi Huange830e682018-03-30 17:48:352656 // NOTE: Candidates allocation will be initiated only when
2657 // SetLocalDescription is called.
2658 error = UpdateSessionState(type, cricket::CS_REMOTE,
2659 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562660 if (!error.ok()) {
2661 return error;
2662 }
2663
2664 if (local_description() &&
2665 !UseCandidatesInSessionDescription(remote_description())) {
2666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2667 }
2668
2669 if (old_remote_description) {
2670 for (const cricket::ContentInfo& content :
2671 old_remote_description->description()->contents()) {
2672 // Check if this new SessionDescription contains new ICE ufrag and
2673 // password that indicates the remote peer requests an ICE restart.
2674 // TODO(deadbeef): When we start storing both the current and pending
2675 // remote description, this should reset pending_ice_restarts and compare
2676 // against the current description.
2677 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2678 content.name)) {
Steve Anton3828c062017-12-06 18:34:512679 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562680 pending_ice_restarts_.insert(content.name);
2681 }
2682 } else {
2683 // We retain all received candidates only if ICE is not restarted.
2684 // When ICE is restarted, all previous candidates belong to an old
2685 // generation and should not be kept.
2686 // TODO(deadbeef): This goes against the W3C spec which says the remote
2687 // description should only contain candidates from the last set remote
2688 // description plus any candidates added since then. We should remove
2689 // this once we're sure it won't break anything.
2690 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2691 old_remote_description, content.name, mutable_remote_description());
2692 }
2693 }
2694 }
2695
2696 if (session_error() != SessionError::kNone) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2698 }
2699
2700 // Set the the ICE connection state to connecting since the connection may
2701 // become writable with peer reflexive candidates before any remote candidate
2702 // is signaled.
2703 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2704 // is to have a new signal the indicates a change in checking state from the
2705 // transport and expose a new checking() member from transport that can be
2706 // read to determine the current checking state. The existing SignalConnecting
2707 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412708 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172709 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562710 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2711 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2712 }
2713
deadbeefab9b2d12015-10-14 18:33:112714 // If setting the description decided our SSL role, allocate any necessary
2715 // SCTP sids.
2716 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222717 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112718 AllocateSctpSids(role);
2719 }
2720
Steve Antondcc3c022017-12-23 00:02:542721 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422722 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182723 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362724 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132725 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182726 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:422727 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:542728 const ContentInfo* content =
2729 FindMediaSectionForTransceiver(transceiver, remote_description());
2730 if (!content) {
2731 continue;
2732 }
2733 const MediaContentDescription* media_desc = content->media_description();
2734 RtpTransceiverDirection local_direction =
2735 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 10:06:022736 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2737 // RTCSessionDescription: Set the associated remote streams given
2738 // transceiver.[[Receiver]], msids, addList, and removeList".
2739 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2740 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2741 std::vector<std::string> stream_ids;
2742 if (!media_desc->streams().empty()) {
2743 // The remote description has signaled the stream IDs.
2744 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-11 01:15:202745 }
Henrik Boströmafa07dd2018-12-20 10:06:022746 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2747 << " (" << GetStreamIdsString(stream_ids) << ").";
2748 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2749 stream_ids, &added_streams,
2750 &removed_streams);
2751 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2752 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2753 // and transceiver's current direction is neither sendrecv nor recvonly,
2754 // process the addition of a remote track for the media description.
2755 if (!transceiver->fired_direction() ||
2756 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2757 RTC_LOG(LS_INFO)
2758 << "Processing the addition of a remote track for MID="
2759 << content->name << ".";
2760 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 10:25:052761 }
Steve Antondcc3c022017-12-23 00:02:542762 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:402763 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 21:25:362764 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2765 // removal of a remote track for the media description, given transceiver,
2766 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:542767 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362768 (transceiver->fired_direction() &&
2769 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2770 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2771 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542772 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:402773 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 21:25:362774 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:402775 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 21:25:362776 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542777 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:402778 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 21:25:362779 // direction.
Steve Antondcc3c022017-12-23 00:02:542780 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:402781 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2782 if (transceiver->mid()) {
2783 auto dtls_transport =
2784 LookupDtlsTransportByMidInternal(*transceiver->mid());
2785 transceiver->internal()->sender_internal()->set_transport(
2786 dtls_transport);
2787 transceiver->internal()->receiver_internal()->set_transport(
2788 dtls_transport);
2789 }
Steve Antondcc3c022017-12-23 00:02:542790 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:402791 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 21:25:362792 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:542793 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232794 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2795 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542796 transceiver->Stop();
2797 }
Seth Hampson2f0d7022018-02-20 19:54:422798 if (!content->rejected &&
2799 RtpTransceiverDirectionHasRecv(local_direction)) {
2800 // Set ssrc to 0 in the case of an unsignalled ssrc.
2801 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332802 if (!media_desc->streams().empty() &&
2803 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422804 ssrc = media_desc->streams()[0].first_ssrc();
2805 }
2806 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022807 }
Steve Antondcc3c022017-12-23 00:02:542808 }
Steve Antonc49bcd92018-02-14 22:28:132809 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162810 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:422811 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162812 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162813 observer->OnTrack(transceiver);
2814 observer->OnAddTrack(transceiver->receiver(),
2815 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202816 }
Mirko Bonadei739baf02019-01-27 16:29:422817 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162818 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132819 }
Mirko Bonadei739baf02019-01-27 16:29:422820 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162821 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182822 }
Mirko Bonadei739baf02019-01-27 16:29:422823 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162824 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182825 }
Steve Antondcc3c022017-12-23 00:02:542826 }
2827
Henrik Boströmfdb92012017-11-09 18:55:442828 const cricket::ContentInfo* audio_content =
2829 GetFirstAudioContent(remote_description()->description());
2830 const cricket::ContentInfo* video_content =
2831 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402832 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442833 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402834 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442835 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand141c0ad2019-05-05 19:00:002836 const cricket::DataContentDescription* data_desc =
2837 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402838
2839 // Check if the descriptions include streams, just in case the peer supports
2840 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442841 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402842 (audio_desc && !audio_desc->streams().empty()) ||
2843 (video_desc && !video_desc->streams().empty())) {
2844 remote_peer_supports_msid_ = true;
2845 }
deadbeefab9b2d12015-10-14 18:33:112846
2847 // We wait to signal new streams until we finish processing the description,
2848 // since only at that point will new streams have all their tracks.
2849 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2850
Steve Antondcc3c022017-12-23 00:02:542851 if (!IsUnifiedPlan()) {
2852 // TODO(steveanton): When removing RTP senders/receivers in response to a
2853 // rejected media section, there is some cleanup logic that expects the
2854 // voice/ video channel to still be set. But in this method the voice/video
2855 // channel would have been destroyed by the SetRemoteDescription caller
2856 // above so the cleanup that relies on them fails to run. The RemoveSenders
2857 // calls should be moved to right before the DestroyChannel calls to fix
2858 // this.
Steve Anton8d3444d2017-10-20 22:30:512859
Steve Antondcc3c022017-12-23 00:02:542860 // Find all audio rtp streams and create corresponding remote AudioTracks
2861 // and MediaStreams.
2862 if (audio_content) {
2863 if (audio_content->rejected) {
2864 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2865 } else {
2866 bool default_audio_track_needed =
2867 !remote_peer_supports_msid_ &&
2868 RtpTransceiverDirectionHasSend(audio_desc->direction());
2869 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2870 default_audio_track_needed, audio_desc->type(),
2871 new_streams);
2872 }
deadbeeffaac4972015-11-12 23:33:072873 }
deadbeefab9b2d12015-10-14 18:33:112874
Steve Antondcc3c022017-12-23 00:02:542875 // Find all video rtp streams and create corresponding remote VideoTracks
2876 // and MediaStreams.
2877 if (video_content) {
2878 if (video_content->rejected) {
2879 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2880 } else {
2881 bool default_video_track_needed =
2882 !remote_peer_supports_msid_ &&
2883 RtpTransceiverDirectionHasSend(video_desc->direction());
2884 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2885 default_video_track_needed, video_desc->type(),
2886 new_streams);
2887 }
deadbeeffaac4972015-11-12 23:33:072888 }
deadbeefab9b2d12015-10-14 18:33:112889
Harald Alvestrand141c0ad2019-05-05 19:00:002890 // Update the DataChannels with the information from the remote peer.
2891 if (data_desc) {
2892 if (absl::StartsWith(data_desc->protocol(),
2893 cricket::kMediaProtocolRtpPrefix)) {
2894 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2895 }
deadbeefab9b2d12015-10-14 18:33:112896 }
deadbeefab9b2d12015-10-14 18:33:112897
Steve Antondcc3c022017-12-23 00:02:542898 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162899 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542900 for (size_t i = 0; i < new_streams->count(); ++i) {
2901 MediaStreamInterface* new_stream = new_streams->at(i);
2902 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:162903 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542904 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2905 }
deadbeefab9b2d12015-10-14 18:33:112906
Steve Antondcc3c022017-12-23 00:02:542907 UpdateEndedRemoteMediaStreams();
2908 }
deadbeefab9b2d12015-10-14 18:33:112909
Steve Anton8a006912017-12-04 23:25:562910 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332911}
2912
Henrik Boströmafa07dd2018-12-20 10:06:022913void PeerConnection::SetAssociatedRemoteStreams(
2914 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2915 const std::vector<std::string>& stream_ids,
2916 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2917 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2918 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2919 for (const std::string& stream_id : stream_ids) {
2920 rtc::scoped_refptr<MediaStreamInterface> stream =
2921 remote_streams_->find(stream_id);
2922 if (!stream) {
2923 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2924 MediaStream::Create(stream_id));
2925 remote_streams_->AddStream(stream);
2926 added_streams->push_back(stream);
2927 }
2928 media_streams.push_back(stream);
2929 }
2930 // Special case: "a=msid" missing, use random stream ID.
2931 if (media_streams.empty() &&
2932 !(remote_description()->description()->msid_signaling() &
2933 cricket::kMsidSignalingMediaSection)) {
2934 if (!missing_msid_default_stream_) {
2935 missing_msid_default_stream_ = MediaStreamProxy::Create(
2936 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2937 added_streams->push_back(missing_msid_default_stream_);
2938 }
2939 media_streams.push_back(missing_msid_default_stream_);
2940 }
2941 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2942 receiver->streams();
2943 // SetStreams() will add/remove the receiver's track to/from the streams. This
2944 // differs from the spec - the spec uses an "addList" and "removeList" to
2945 // update the stream-track relationships in a later step. We do this earlier,
2946 // changing the order of things, but the end-result is the same.
2947 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2948 // instead. https://crbug.com/webrtc/9480
2949 receiver->SetStreams(media_streams);
2950 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2951}
2952
Steve Anton0f5400a2018-07-17 21:25:362953void PeerConnection::ProcessRemovalOfRemoteTrack(
2954 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2955 transceiver,
2956 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2957 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2958 RTC_DCHECK(transceiver->mid());
2959 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2960 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 10:06:022961 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 21:25:362962 transceiver->internal()->receiver_internal()->streams();
2963 // This will remove the remote track from the streams.
2964 transceiver->internal()->receiver_internal()->set_stream_ids({});
2965 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 10:06:022966 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2967}
2968
2969void PeerConnection::RemoveRemoteStreamsIfEmpty(
2970 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2971 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2972 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2973 // streams, see if the stream was removed by checking if this was the last
2974 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 16:29:422975 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 10:06:022976 if (remote_stream->GetAudioTracks().empty() &&
2977 remote_stream->GetVideoTracks().empty()) {
2978 remote_streams_->RemoveStream(remote_stream);
2979 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 21:25:362980 }
2981 }
2982}
2983
Steve Antondcc3c022017-12-23 00:02:542984RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2985 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482986 const SessionDescriptionInterface& new_session,
2987 const SessionDescriptionInterface* old_local_description,
2988 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542989 RTC_DCHECK(IsUnifiedPlan());
2990
Steve Anton7464fca2018-01-19 19:10:372991 const cricket::ContentGroup* bundle_group = nullptr;
2992 if (new_session.GetType() == SdpType::kOffer) {
2993 auto bundle_group_or_error =
2994 GetEarlyBundleGroup(*new_session.description());
2995 if (!bundle_group_or_error.ok()) {
2996 return bundle_group_or_error.MoveError();
2997 }
2998 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542999 }
Steve Antondcc3c022017-12-23 00:02:543000
Steve Antondcc3c022017-12-23 00:02:543001 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:543002 for (size_t i = 0; i < new_contents.size(); ++i) {
3003 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:543004 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 20:13:083005 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-23 00:02:543006 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3007 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:483008 const cricket::ContentInfo* old_local_content = nullptr;
3009 if (old_local_description &&
3010 i < old_local_description->description()->contents().size()) {
3011 old_local_content =
3012 &old_local_description->description()->contents()[i];
3013 }
3014 const cricket::ContentInfo* old_remote_content = nullptr;
3015 if (old_remote_description &&
3016 i < old_remote_description->description()->contents().size()) {
3017 old_remote_content =
3018 &old_remote_description->description()->contents()[i];
3019 }
Steve Antondcc3c022017-12-23 00:02:543020 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:483021 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3022 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:543023 if (!transceiver_or_error.ok()) {
3024 return transceiver_or_error.MoveError();
3025 }
3026 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:543027 RTCError error =
3028 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3029 if (!error.ok()) {
3030 return error;
3031 }
3032 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:233033 if (GetDataMid() && new_content.name != *GetDataMid()) {
3034 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:233035 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3036 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:233037 continue;
3038 }
3039 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3040 if (!error.ok()) {
3041 return error;
3042 }
Steve Antondcc3c022017-12-23 00:02:543043 } else {
3044 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3045 "Unknown section type.");
3046 }
3047 }
3048
3049 return RTCError::OK();
3050}
3051
3052RTCError PeerConnection::UpdateTransceiverChannel(
3053 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3054 transceiver,
3055 const cricket::ContentInfo& content,
3056 const cricket::ContentGroup* bundle_group) {
3057 RTC_DCHECK(IsUnifiedPlan());
3058 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-14 00:26:053059 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:543060 if (content.rejected) {
3061 if (channel) {
3062 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:053063 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:543064 }
3065 } else {
3066 if (!channel) {
Steve Anton69470252018-02-09 19:43:083067 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:353068 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543069 } else {
Steve Anton69470252018-02-09 19:43:083070 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:353071 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543072 }
3073 if (!channel) {
3074 LOG_AND_RETURN_ERROR(
3075 RTCErrorType::INTERNAL_ERROR,
3076 "Failed to create channel for mid=" + content.name);
3077 }
3078 transceiver->internal()->SetChannel(channel);
3079 }
3080 }
3081 return RTCError::OK();
3082}
3083
Steve Antonfa2260d2017-12-29 00:38:233084RTCError PeerConnection::UpdateDataChannel(
3085 cricket::ContentSource source,
3086 const cricket::ContentInfo& content,
3087 const cricket::ContentGroup* bundle_group) {
3088 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:403089 // If data channels are disabled, ignore this media section. CreateAnswer
3090 // will take care of rejecting it.
3091 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:233092 }
3093 if (content.rejected) {
3094 DestroyDataChannel();
3095 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:223096 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:353097 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:233098 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3099 "Failed to create data channel.");
3100 }
3101 }
3102 if (source == cricket::CS_REMOTE) {
3103 const MediaContentDescription* data_desc = content.media_description();
3104 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3105 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3106 }
3107 }
3108 }
3109 return RTCError::OK();
3110}
3111
Amit Hilbuchbcd39d42019-01-26 01:13:563112// This method will extract any send encodings that were sent by the remote
3113// connection. This is currently only relevant for Simulcast scenario (where
3114// the number of layers may be communicated by the server).
3115static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3116 const MediaContentDescription& desc) {
3117 if (!desc.HasSimulcast()) {
3118 return {};
3119 }
3120 std::vector<RtpEncodingParameters> result;
3121 const SimulcastDescription& simulcast = desc.simulcast_description();
3122
3123 // This is a remote description, the parameters we are after should appear
3124 // as receive streams.
3125 for (const auto& alternatives : simulcast.receive_layers()) {
3126 RTC_DCHECK(!alternatives.empty());
3127 // There is currently no way to specify or choose from alternatives.
3128 // We will always use the first alternative, which is the most preferred.
3129 const SimulcastLayer& layer = alternatives[0];
3130 RtpEncodingParameters parameters;
3131 parameters.rid = layer.rid;
3132 parameters.active = !layer.is_paused;
3133 result.push_back(parameters);
3134 }
3135
3136 return result;
3137}
3138
3139static RTCError UpdateSimulcastLayerStatusInSender(
3140 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 20:49:223141 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563142 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193143 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223144 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:563145
3146 // The simulcast envelope cannot be changed, only the status of the streams.
3147 // So we will iterate over the send encodings rather than the layers.
3148 for (RtpEncodingParameters& encoding : parameters.encodings) {
3149 auto iter = std::find_if(layers.begin(), layers.end(),
3150 [&encoding](const SimulcastLayer& layer) {
3151 return layer.rid == encoding.rid;
3152 });
3153 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 20:49:223154 if (iter == layers.end()) {
3155 disabled_layers.push_back(encoding.rid);
3156 continue;
3157 }
3158
3159 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-26 01:13:563160 }
3161
Amit Hilbuch619b2942019-02-26 23:55:193162 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 20:49:223163 if (result.ok()) {
3164 result = sender->DisableEncodingLayers(disabled_layers);
3165 }
3166
3167 return result;
Amit Hilbuchbcd39d42019-01-26 01:13:563168}
3169
Amit Hilbuchaabd0362019-03-01 21:14:463170static bool SimulcastIsRejected(
3171 const ContentInfo* local_content,
3172 const MediaContentDescription& answer_media_desc) {
3173 bool simulcast_offered = local_content &&
3174 local_content->media_description() &&
3175 local_content->media_description()->HasSimulcast();
3176 bool simulcast_answered = answer_media_desc.HasSimulcast();
3177 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3178 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3179 return simulcast_offered && (!simulcast_answered || !rids_supported);
3180}
3181
Amit Hilbuch2297d332019-02-19 20:49:223182static RTCError DisableSimulcastInSender(
3183 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563184 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193185 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223186 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-26 01:13:563187 return RTCError::OK();
3188 }
3189
Amit Hilbuch2297d332019-02-19 20:49:223190 std::vector<std::string> disabled_layers;
3191 std::transform(
3192 parameters.encodings.begin() + 1, parameters.encodings.end(),
3193 std::back_inserter(disabled_layers),
3194 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3195 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-26 01:13:563196}
3197
Steve Antondcc3c022017-12-23 00:02:543198RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3199PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:483200 SdpType type,
Steve Antondcc3c022017-12-23 00:02:543201 size_t mline_index,
3202 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:483203 const ContentInfo* old_local_content,
3204 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:543205 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:483206 // If this is an offer then the m= section might be recycled. If the m=
3207 // section is being recycled (defined as: rejected in the current local or
3208 // remote description and not rejected in new description), dissociate the
3209 // currently associated RtpTransceiver by setting its mid property to null,
3210 // and discard the mapping between the transceiver and its m= section index.
3211 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3212 old_remote_content)) {
3213 // We want to dissociate the transceiver that has the rejected mid.
3214 const std::string& old_mid =
3215 (old_local_content && old_local_content->rejected)
3216 ? old_local_content->name
3217 : old_remote_content->name;
3218 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:543219 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:233220 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3221 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:433222 old_transceiver->internal()->set_mid(absl::nullopt);
3223 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:543224 }
3225 }
3226 const MediaContentDescription* media_desc = content.media_description();
3227 auto transceiver = GetAssociatedTransceiver(content.name);
3228 if (source == cricket::CS_LOCAL) {
3229 // Find the RtpTransceiver that corresponds to this m= section, using the
3230 // mapping between transceivers and m= section indices established when
3231 // creating the offer.
3232 if (!transceiver) {
3233 transceiver = GetTransceiverByMLineIndex(mline_index);
3234 }
3235 if (!transceiver) {
3236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3237 "Unknown transceiver");
3238 }
3239 } else {
3240 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3241 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3242 // of the same type...
Amit Hilbuchaa584152019-02-07 01:09:523243 // When simulcast is requested, a transceiver cannot be associated because
3244 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-23 00:02:543245 if (!transceiver &&
Amit Hilbuchaa584152019-02-07 01:09:523246 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3247 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-23 00:02:543248 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3249 }
3250 // If no RtpTransceiver was found in the previous step, create one with a
3251 // recvonly direction.
3252 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:233253 RTC_LOG(LS_INFO) << "Adding "
3254 << cricket::MediaTypeToString(media_desc->type())
3255 << " transceiver for MID=" << content.name
3256 << " at i=" << mline_index
3257 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:363258 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-26 01:13:563259 std::vector<RtpEncodingParameters> send_encodings =
3260 GetSendEncodingsFromRemoteDescription(*media_desc);
3261 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3262 send_encodings);
Steve Anton5f94aa22018-02-01 18:58:303263 std::string receiver_id;
3264 if (!media_desc->streams().empty()) {
3265 receiver_id = media_desc->streams()[0].id;
3266 } else {
3267 receiver_id = rtc::CreateRandomUuid();
3268 }
3269 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:063270 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:543271 transceiver->internal()->set_direction(
3272 RtpTransceiverDirection::kRecvOnly);
3273 }
Amit Hilbuchbcd39d42019-01-26 01:13:563274
3275 // Check if the offer indicated simulcast but the answer rejected it.
3276 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 21:14:463277 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 20:36:313278 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-26 01:13:563279 RTCError error =
Amit Hilbuch2297d332019-02-19 20:49:223280 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563281 if (!error.ok()) {
3282 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3283 return std::move(error);
3284 }
3285 }
Steve Antondcc3c022017-12-23 00:02:543286 }
3287 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:083288 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:543289 LOG_AND_RETURN_ERROR(
3290 RTCErrorType::INVALID_PARAMETER,
3291 "Transceiver type does not match media description type.");
3292 }
Amit Hilbuchbcd39d42019-01-26 01:13:563293 if (media_desc->HasSimulcast()) {
3294 std::vector<SimulcastLayer> layers =
3295 source == cricket::CS_LOCAL
3296 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3297 : media_desc->simulcast_description()
3298 .receive_layers()
3299 .GetAllLayers();
3300 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 20:49:223301 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563302 if (!error.ok()) {
3303 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3304 return std::move(error);
3305 }
3306 }
Steve Antondcc3c022017-12-23 00:02:543307 // Associate the found or created RtpTransceiver with the m= section by
3308 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3309 // section, and establish a mapping between the transceiver and the index of
3310 // the m= section.
3311 transceiver->internal()->set_mid(content.name);
3312 transceiver->internal()->set_mline_index(mline_index);
3313 return std::move(transceiver);
3314}
3315
3316rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3317PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3318 RTC_DCHECK(IsUnifiedPlan());
3319 for (auto transceiver : transceivers_) {
3320 if (transceiver->mid() == mid) {
3321 return transceiver;
3322 }
3323 }
3324 return nullptr;
3325}
3326
3327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3328PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3329 RTC_DCHECK(IsUnifiedPlan());
3330 for (auto transceiver : transceivers_) {
3331 if (transceiver->internal()->mline_index() == mline_index) {
3332 return transceiver;
3333 }
3334 }
3335 return nullptr;
3336}
3337
3338rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3339PeerConnection::FindAvailableTransceiverToReceive(
3340 cricket::MediaType media_type) const {
3341 RTC_DCHECK(IsUnifiedPlan());
3342 // From JSEP section 5.10 (Applying a Remote Description):
3343 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3344 // the same type that were added to the PeerConnection by addTrack and are not
3345 // associated with any m= section and are not stopped, find the first such
3346 // RtpTransceiver.
3347 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:083348 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:543349 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3350 !transceiver->stopped()) {
3351 return transceiver;
3352 }
3353 }
3354 return nullptr;
3355}
3356
Steve Antoned10bd92017-12-05 18:52:593357const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3358 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3359 transceiver,
3360 const SessionDescriptionInterface* sdesc) const {
3361 RTC_DCHECK(transceiver);
3362 RTC_DCHECK(sdesc);
3363 if (IsUnifiedPlan()) {
3364 if (!transceiver->internal()->mid()) {
3365 // This transceiver is not associated with a media section yet.
3366 return nullptr;
3367 }
3368 return sdesc->description()->GetContentByName(
3369 *transceiver->internal()->mid());
3370 } else {
3371 // Plan B only allows at most one audio and one video section, so use the
3372 // first media section of that type.
3373 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:083374 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:593375 }
3376}
3377
deadbeef46c73892016-11-17 03:42:043378PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 22:55:093379 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-17 03:42:043380 return configuration_;
3381}
3382
deadbeef293e9262017-01-11 20:28:303383bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3384 RTCError* error) {
Karl Wiberg5966c502019-02-21 22:55:093385 RTC_DCHECK_RUN_ON(signaling_thread());
3386 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 21:15:173387 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:103388 if (IsClosed()) {
3389 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3390 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3391 }
3392
Qingsi Wanga2d60672018-04-11 23:57:453393 // According to JSEP, after setLocalDescription, changing the candidate pool
3394 // size is not allowed, and changing the set of ICE servers will not result
3395 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:173396 if (local_description() && configuration.ice_candidate_pool_size !=
3397 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:253398 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3399 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:303400 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453401 }
Taylor Brandstettera1c30352016-05-13 15:15:113402
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453403 if (local_description() &&
3404 configuration.use_media_transport != configuration_.use_media_transport) {
3405 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3406 "SetLocalDescription.";
3407 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3408 }
3409
3410 if (remote_description() &&
3411 configuration.use_media_transport != configuration_.use_media_transport) {
3412 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3413 "SetRemoteDescription.";
3414 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3415 }
3416
Benjamin Wright8c27cca2018-10-25 17:16:443417 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 16:07:483418 configuration.use_media_transport_for_data_channels !=
3419 configuration_.use_media_transport_for_data_channels) {
3420 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3421 "after calling SetLocalDescription.";
3422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3423 }
3424
3425 if (remote_description() &&
3426 configuration.use_media_transport_for_data_channels !=
3427 configuration_.use_media_transport_for_data_channels) {
3428 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3429 "after calling SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
3433 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 17:16:443434 configuration.crypto_options != configuration_.crypto_options) {
3435 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3436 "SetLocalDescription.";
3437 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3438 }
3439
Piotr (Peter) Slatala37227be2018-11-21 15:42:223440 if (configuration.use_media_transport_for_data_channels ||
3441 configuration.use_media_transport) {
3442 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3443 << "Media transport requires MaxBundle policy.";
3444 }
3445
deadbeef293e9262017-01-11 20:28:303446 // The simplest (and most future-compatible) way to tell if the config was
3447 // modified in an invalid way is to copy each property we do support
3448 // modifying, then use operator==. There are far more properties we don't
3449 // support modifying than those we do, and more could be added.
3450 RTCConfiguration modified_config = configuration_;
3451 modified_config.servers = configuration.servers;
3452 modified_config.type = configuration.type;
3453 modified_config.ice_candidate_pool_size =
3454 configuration.ice_candidate_pool_size;
3455 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:053456 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:143457 modified_config.ice_check_interval_strong_connectivity =
3458 configuration.ice_check_interval_strong_connectivity;
3459 modified_config.ice_check_interval_weak_connectivity =
3460 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:573461 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3462 modified_config.ice_unwritable_min_checks =
3463 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:173464 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:493465 modified_config.stun_candidate_keepalive_interval =
3466 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:403467 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:403468 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:113469 modified_config.active_reset_srtp_params =
3470 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453471 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:483472 modified_config.use_media_transport_for_data_channels =
3473 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 20:28:303474 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:253475 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:303476 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3477 }
3478
Steve Anton038834f2017-07-14 22:59:593479 // Validate the modified configuration.
3480 RTCError validate_error = ValidateConfiguration(modified_config);
3481 if (!validate_error.ok()) {
3482 return SafeSetError(std::move(validate_error), error);
3483 }
3484
deadbeef293e9262017-01-11 20:28:303485 // Note that this isn't possible through chromium, since it's an unsigned
3486 // short in WebIDL.
3487 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:173488 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:303489 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3490 }
3491
3492 // Parse ICE servers before hopping to network thread.
3493 cricket::ServerAddresses stun_servers;
3494 std::vector<cricket::RelayServerConfig> turn_servers;
3495 RTCErrorType parse_error =
3496 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3497 if (parse_error != RTCErrorType::NONE) {
3498 return SafeSetError(parse_error, error);
3499 }
Harald Alvestrand8ebba742018-05-31 12:00:343500 // Note if STUN or TURN servers were supplied.
3501 if (!stun_servers.empty()) {
3502 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3503 }
3504 if (!turn_servers.empty()) {
3505 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3506 }
deadbeef293e9262017-01-11 20:28:303507
3508 // In theory this shouldn't fail.
3509 if (!network_thread()->Invoke<bool>(
3510 RTC_FROM_HERE,
3511 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3512 stun_servers, turn_servers, modified_config.type,
3513 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:403514 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:493515 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:283516 modified_config.stun_candidate_keepalive_interval,
3517 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 10:09:253518 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:303519 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3520 }
Honghai Zhang4cedf2b2016-08-31 15:18:113521
deadbeefd1a38b52016-12-10 21:15:333522 // As described in JSEP, calling setConfiguration with new ICE servers or
3523 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3524 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:303525 if (modified_config.servers != configuration_.servers ||
3526 modified_config.type != configuration_.type ||
3527 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:293528 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:333529 }
skvladd1f5fda2017-02-04 00:54:053530
Qingsi Wang9c98f0c2018-02-15 23:10:593531 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 21:31:153532 transport_controller_->SetMediaTransportSettings(
3533 modified_config.use_media_transport,
3534 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-04 00:54:053535
Zhi Huangb57e1692018-06-12 18:41:113536 if (configuration_.active_reset_srtp_params !=
3537 modified_config.active_reset_srtp_params) {
3538 transport_controller_->SetActiveResetSrtpParams(
3539 modified_config.active_reset_srtp_params);
3540 }
3541
deadbeef293e9262017-01-11 20:28:303542 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 22:55:093543 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 20:28:303544 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453545}
3546
henrike@webrtc.org28e20752013-07-10 00:45:363547bool PeerConnection::AddIceCandidate(
3548 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 09:18:563549 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:173550 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:253551 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:103552 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:363553 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:253554 return false;
3555 }
Steve Antond25da372017-11-06 22:50:293556
3557 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103558 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:073559 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:363560 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:293561 return false;
3562 }
3563
3564 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:103565 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:363566 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:293567 return false;
3568 }
3569
3570 bool valid = false;
3571 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3572 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:363573 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:293574 return false;
3575 }
3576
3577 // Add this candidate to the remote session description.
3578 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:103579 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:363580 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:293581 return false;
3582 }
3583
3584 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:363585 bool result = UseCandidate(ice_candidate);
3586 if (result) {
3587 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 20:13:483588 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3589 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3590 }
3591 if (ice_candidate->candidate().address().IsPrivateIP()) {
3592 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3593 }
Harald Alvestrand76829d72018-07-18 21:24:363594 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3595 } else {
3596 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3597 }
3598 return result;
Steve Antond25da372017-11-06 22:50:293599 } else {
Steve Antonc79268f2018-04-24 16:54:103600 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:363601 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:293602 return true;
3603 }
henrike@webrtc.org28e20752013-07-10 00:45:363604}
3605
Honghai Zhang7fb69db2016-03-14 18:59:183606bool PeerConnection::RemoveIceCandidates(
3607 const std::vector<cricket::Candidate>& candidates) {
3608 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 09:31:563609 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 16:54:103610 if (IsClosed()) {
3611 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3612 return false;
3613 }
3614
Steve Antond25da372017-11-06 22:50:293615 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103616 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3617 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293618 return false;
3619 }
3620
3621 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103622 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293623 return false;
3624 }
3625
3626 size_t number_removed =
3627 mutable_remote_description()->RemoveCandidates(candidates);
3628 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253629 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103630 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073631 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253632 << " are removed.";
Steve Antond25da372017-11-06 22:50:293633 }
3634
3635 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353636 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3637 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103638 RTC_LOG(LS_ERROR)
3639 << "RemoveIceCandidates: Error when removing remote candidates: "
3640 << error.message();
Steve Antond25da372017-11-06 22:50:293641 }
3642 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183643}
3644
Niels Möller0c4f7be2018-05-07 12:01:373645RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023646 if (!worker_thread()->IsCurrent()) {
3647 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053648 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373649 }
Karl Wiberg6cab5c82019-03-26 08:57:013650 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 21:37:373651
Niels Möller0c4f7be2018-05-07 12:01:373652 const bool has_min = bitrate.min_bitrate_bps.has_value();
3653 const bool has_start = bitrate.start_bitrate_bps.has_value();
3654 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373655 if (has_min && *bitrate.min_bitrate_bps < 0) {
3656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3657 "min_bitrate_bps <= 0");
3658 }
Niels Möller0c4f7be2018-05-07 12:01:373659 if (has_start) {
3660 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373661 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373662 "start_bitrate_bps < min_bitrate_bps");
3663 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3665 "curent_bitrate_bps < 0");
3666 }
3667 }
3668 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053669 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373671 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373672 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3674 "max_bitrate_bps < min_bitrate_bps");
3675 } else if (*bitrate.max_bitrate_bps < 0) {
3676 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3677 "max_bitrate_bps < 0");
3678 }
3679 }
3680
zstein4b979802017-06-02 21:37:373681 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 17:31:543682 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373683
3684 return RTCError::OK();
3685}
3686
Alex Narest78609d52017-10-20 08:37:473687void PeerConnection::SetBitrateAllocationStrategy(
3688 std::unique_ptr<rtc::BitrateAllocationStrategy>
3689 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 08:57:013690 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 10:18:393691 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3692 // move-capture values in lambdas.
3693 struct Task {
3694 PeerConnection* const pc;
3695 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3696 void operator()() {
3697 RTC_DCHECK_RUN_ON(pc->worker_thread());
3698 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3699 }
3700 };
3701 worker_thread()->Invoke<void>(
3702 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 08:37:473703 return;
3704 }
Karl Wiberg6cab5c82019-03-26 08:57:013705 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 08:37:473706 RTC_DCHECK(call_.get());
3707 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3708}
3709
henrika5f6bf242017-11-01 10:06:563710void PeerConnection::SetAudioPlayout(bool playout) {
3711 if (!worker_thread()->IsCurrent()) {
3712 worker_thread()->Invoke<void>(
3713 RTC_FROM_HERE,
3714 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3715 return;
3716 }
3717 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553718 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563719 audio_state->SetPlayout(playout);
3720}
3721
3722void PeerConnection::SetAudioRecording(bool recording) {
3723 if (!worker_thread()->IsCurrent()) {
3724 worker_thread()->Invoke<void>(
3725 RTC_FROM_HERE,
3726 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3727 return;
3728 }
3729 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553730 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563731 audio_state->SetRecording(recording);
3732}
3733
Steve Anton8c0f7a72017-10-03 17:03:103734std::unique_ptr<rtc::SSLCertificate>
3735PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513736 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3737 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103738 return nullptr;
3739 }
Steve Antonf25303e2018-10-16 22:23:313740 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:103741}
3742
Zhi Huang70b820f2018-01-27 22:16:153743std::unique_ptr<rtc::SSLCertChain>
3744PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 12:33:433745 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 19:35:373746 auto audio_transceiver = GetFirstAudioTransceiver();
3747 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153748 return nullptr;
3749 }
Zhi Huang70b820f2018-01-27 22:16:153750 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373751 audio_transceiver->internal()->channel()->transport_name());
3752}
3753
3754rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3755PeerConnection::GetFirstAudioTransceiver() const {
3756 for (auto transceiver : transceivers_) {
3757 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3758 return transceiver;
3759 }
3760 }
3761 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153762}
3763
ivoc14d5dbe2016-07-04 14:06:553764bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3765 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403766 // TODO(eladalon): It would be better to not allow negative values into PC.
3767 const size_t max_size = (max_size_bytes < 0)
3768 ? RtcEventLog::kUnlimitedOutput
3769 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 14:43:013770 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3771 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3772 output_period_ms = 5000;
3773 }
Elad Alon99c3fe52017-10-13 14:29:403774 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333775 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 14:43:013776 output_period_ms);
Elad Alon99c3fe52017-10-13 14:29:403777}
3778
Bjorn Tereliusde939432017-11-20 16:38:143779bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3780 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063781 // TODO(eladalon): In C++14, this can be done with a lambda.
3782 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143783 bool operator()() {
3784 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3785 }
Karl Wibergd6b48192017-10-16 21:01:063786 PeerConnection* const pc;
3787 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143788 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403789 };
Bjorn Tereliusde939432017-11-20 16:38:143790 return worker_thread()->Invoke<bool>(
3791 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553792}
3793
3794void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023795 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553796 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3797}
3798
Harald Alvestrandad88c882018-11-28 15:47:463799rtc::scoped_refptr<DtlsTransportInterface>
3800PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:563801 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 15:47:463802 return transport_controller_->LookupDtlsTransportByMid(mid);
3803}
3804
Harald Alvestrand4a7b3ac2019-01-17 09:39:403805rtc::scoped_refptr<DtlsTransport>
3806PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:563807 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 09:39:403808 return transport_controller_->LookupDtlsTransportByMid(mid);
3809}
3810
Harald Alvestrandc85328f2019-02-28 06:51:003811rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3812 const {
Karl Wiberg2cc368f2019-04-02 09:31:563813 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 06:51:003814 return sctp_transport_;
3815}
3816
henrike@webrtc.org28e20752013-07-10 00:45:363817const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 09:37:283818 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173819 return pending_local_description_ ? pending_local_description_.get()
3820 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363821}
3822
3823const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 09:37:283824 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173825 return pending_remote_description_ ? pending_remote_description_.get()
3826 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363827}
3828
deadbeeffe4a8a42016-12-21 01:56:173829const SessionDescriptionInterface* PeerConnection::current_local_description()
3830 const {
Karl Wiberg739506e2019-04-03 09:37:283831 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173832 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173833}
3834
3835const SessionDescriptionInterface* PeerConnection::current_remote_description()
3836 const {
Karl Wiberg739506e2019-04-03 09:37:283837 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173838 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173839}
3840
3841const SessionDescriptionInterface* PeerConnection::pending_local_description()
3842 const {
Karl Wiberg739506e2019-04-03 09:37:283843 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173844 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173845}
3846
3847const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3848 const {
Karl Wiberg739506e2019-04-03 09:37:283849 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:173850 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173851}
3852
henrike@webrtc.org28e20752013-07-10 00:45:363853void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 09:18:563854 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:173855 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363856 // Update stats here so that we have the most recent stats for tracks and
3857 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263858 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363859
Steve Anton75737c02017-11-06 18:37:173860 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343861 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083862
Mirko Bonadei739baf02019-01-27 16:29:423863 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:133864 transceiver->Stop();
3865 }
Steve Anton25cfeb92018-04-26 18:44:003866
3867 // Ensure that all asynchronous stats requests are completed before destroying
3868 // the transport controller below.
3869 if (stats_collector_) {
3870 stats_collector_->WaitForPendingRequest();
3871 }
3872
3873 // Don't destroy BaseChannels until after stats has been cleaned up so that
3874 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133875 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173876
Qingsi Wang93a84392018-01-31 01:13:093877 // The event log is used in the transport controller, which must be outlived
3878 // by the former. CreateOffer by the peer connection is implemented
3879 // asynchronously and if the peer connection is closed without resetting the
3880 // WebRTC session description factory, the session description factory would
3881 // call the transport controller.
3882 webrtc_session_desc_factory_.reset();
3883 transport_controller_.reset();
3884
deadbeef42a42632017-03-10 23:18:003885 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053886 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3887 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023888
Steve Anton978b8762017-09-29 19:15:023889 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:573890 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:153891 call_.reset();
3892 // The event log must outlive call (and any other object that uses it).
3893 event_log_.reset();
3894 });
Harald Alvestrand8ebba742018-05-31 12:00:343895 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163896 // The .h file says that observer can be discarded after close() returns.
3897 // Make sure this is true.
3898 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:363899}
3900
Steve Antonad182762018-09-05 20:22:403901void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 09:18:563902 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:403903 switch (msg->message_id) {
3904 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3905 SetSessionDescriptionMsg* param =
3906 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3907 param->observer->OnSuccess();
3908 delete param;
3909 break;
3910 }
3911 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3912 SetSessionDescriptionMsg* param =
3913 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3914 param->observer->OnFailure(std::move(param->error));
3915 delete param;
3916 break;
3917 }
3918 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3919 CreateSessionDescriptionMsg* param =
3920 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3921 param->observer->OnFailure(std::move(param->error));
3922 delete param;
3923 break;
3924 }
3925 case MSG_GETSTATS: {
3926 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3927 StatsReports reports;
3928 stats_->GetStats(param->track, &reports);
3929 param->observer->OnComplete(reports);
3930 delete param;
3931 break;
3932 }
3933 case MSG_FREE_DATACHANNELS: {
3934 sctp_data_channels_to_free_.clear();
3935 break;
3936 }
3937 case MSG_REPORT_USAGE_PATTERN: {
3938 ReportUsagePattern();
3939 break;
3940 }
3941 default:
3942 RTC_NOTREACHED() << "Not implemented";
3943 break;
3944 }
3945}
3946
Steve Antonafb0bb72018-02-20 19:35:373947cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3948 RTC_DCHECK(!IsUnifiedPlan());
3949 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3950 GetAudioTransceiver()->internal()->channel());
3951 if (voice_channel) {
3952 return voice_channel->media_channel();
3953 } else {
3954 return nullptr;
3955 }
3956}
3957
3958cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3959 RTC_DCHECK(!IsUnifiedPlan());
3960 auto* video_channel = static_cast<cricket::VideoChannel*>(
3961 GetVideoTransceiver()->internal()->channel());
3962 if (video_channel) {
3963 return video_channel->media_channel();
3964 } else {
3965 return nullptr;
3966 }
3967}
3968
Steve Anton4171afb2017-11-20 18:20:223969void PeerConnection::CreateAudioReceiver(
3970 MediaStreamInterface* stream,
3971 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513972 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3973 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533974 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3975 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023976 auto* audio_receiver = new AudioRtpReceiver(
3977 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053978 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023979 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3980 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3981 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223982 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:123983 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:343984 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363985}
3986
Steve Anton4171afb2017-11-20 18:20:223987void PeerConnection::CreateVideoReceiver(
3988 MediaStreamInterface* stream,
3989 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513990 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3991 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533992 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3993 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023994 auto* video_receiver = new VideoRtpReceiver(
3995 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053996 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023997 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3998 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3999 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:224000 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:124001 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:344002 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:364003}
4004
deadbeef70ab1a12015-09-28 23:53:554005// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4006// description.
Henrik Boström933d8b02017-10-10 17:05:164007rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:224008 const RtpSenderInfo& remote_sender_info) {
4009 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4010 if (!receiver) {
4011 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4012 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:164013 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554014 }
Steve Anton4171afb2017-11-20 18:20:224015 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4016 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4017 } else {
4018 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4019 }
Henrik Boström933d8b02017-10-10 17:05:164020 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:364021}
4022
korniltsev.anatolyec390b52017-07-25 00:00:254023void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4024 MediaStreamInterface* stream) {
4025 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364026 RTC_DCHECK(track);
4027 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254028 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224029 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254030 // We already have a sender for this track, so just change the stream_id
4031 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:364032 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254033 return;
4034 }
4035
4036 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364037 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204038 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054039 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:224040 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:254041 // If the sender has already been configured in SDP, we call SetSsrc,
4042 // which will connect the sender to the underlying transport. This can
4043 // occur if a local session description that contains the ID of the sender
4044 // is set before AddStream is called. It can also occur if the local
4045 // session description is not changed and RemoveStream is called, and
4046 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:224047 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184048 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224049 if (sender_info) {
4050 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254051 }
4052}
4053
4054// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4055// indefinitely, when we have unified plan SDP.
4056void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4057 MediaStreamInterface* stream) {
4058 RTC_DCHECK(!IsClosed());
4059 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224060 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254061 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4062 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254063 return;
4064 }
Steve Anton4171afb2017-11-20 18:20:224065 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254066}
4067
4068void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4069 MediaStreamInterface* stream) {
4070 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364071 RTC_DCHECK(track);
4072 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254073 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224074 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254075 // We already have a sender for this track, so just change the stream_id
4076 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:364077 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254078 return;
4079 }
4080
4081 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364082 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204083 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054084 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:224085 GetVideoTransceiver()->internal()->AddSender(new_sender);
4086 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184087 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224088 if (sender_info) {
4089 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254090 }
4091}
4092
4093void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4094 MediaStreamInterface* stream) {
4095 RTC_DCHECK(!IsClosed());
4096 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224097 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254098 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4099 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254100 return;
4101 }
Steve Anton4171afb2017-11-20 18:20:224102 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254103}
4104
Steve Antonba818672017-11-06 18:21:574105void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 18:21:574106 if (ice_connection_state_ == new_state) {
4107 return;
4108 }
4109
deadbeefcbecd352015-09-23 18:50:274110 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:574111 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:114112 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:274113 return;
4114 }
Steve Antonba818672017-11-06 18:21:574115
Mirko Bonadei675513b2017-11-09 10:09:254116 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4117 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:574118 RTC_DCHECK(ice_connection_state_ !=
4119 PeerConnectionInterface::kIceConnectionClosed);
4120
henrike@webrtc.org28e20752013-07-10 00:45:364121 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164122 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364123}
4124
Alex Loiko9289eda2018-11-23 16:18:594125void PeerConnection::SetStandardizedIceConnectionState(
4126 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:594127 if (standardized_ice_connection_state_ == new_state)
4128 return;
4129 if (IsClosed())
4130 return;
4131 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 10:25:144132 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:594133}
4134
Jonas Olsson635474e2018-10-18 13:58:174135void PeerConnection::SetConnectionState(
4136 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 13:58:174137 if (connection_state_ == new_state)
4138 return;
4139 if (IsClosed())
4140 return;
4141 connection_state_ = new_state;
4142 Observer()->OnConnectionChange(new_state);
4143}
4144
henrike@webrtc.org28e20752013-07-10 00:45:364145void PeerConnection::OnIceGatheringChange(
4146 PeerConnectionInterface::IceGatheringState new_state) {
4147 if (IsClosed()) {
4148 return;
4149 }
4150 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164151 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364152}
4153
jbauch81bf7b02017-03-25 15:31:124154void PeerConnection::OnIceCandidate(
4155 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 18:07:254156 if (IsClosed()) {
4157 return;
4158 }
Harald Alvestrand8ebba742018-05-31 12:00:344159 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:584160 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4161 candidate->candidate().address().IsPrivateIP()) {
4162 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4163 }
Jeroen de Borstaf242c82019-04-24 20:13:484164 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4165 candidate->candidate().address().IsUnresolvedIP()) {
4166 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4167 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164168 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:364169}
4170
Honghai Zhang7fb69db2016-03-14 18:59:184171void PeerConnection::OnIceCandidatesRemoved(
4172 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 18:07:254173 if (IsClosed()) {
4174 return;
4175 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164176 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:184177}
4178
henrike@webrtc.org28e20752013-07-10 00:45:364179void PeerConnection::ChangeSignalingState(
4180 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:574181 if (signaling_state_ == signaling_state) {
4182 return;
4183 }
Mirko Bonadei675513b2017-11-09 10:09:254184 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4185 << GetSignalingStateString(signaling_state_)
4186 << " New state: "
4187 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:364188 signaling_state_ = signaling_state;
4189 if (signaling_state == kClosed) {
4190 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:164191 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:594192 standardized_ice_connection_state_ =
4193 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:174194 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4195 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364196 if (ice_gathering_state_ != kIceGatheringComplete) {
4197 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:164198 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364199 }
4200 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164201 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364202}
4203
deadbeefeb459812015-12-16 03:24:434204void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4205 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254206 if (IsClosed()) {
4207 return;
4208 }
korniltsev.anatolyec390b52017-07-25 00:00:254209 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144210 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434211}
4212
deadbeefeb459812015-12-16 03:24:434213void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4214 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254215 if (IsClosed()) {
4216 return;
4217 }
korniltsev.anatolyec390b52017-07-25 00:00:254218 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144219 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434220}
4221
4222void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4223 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254224 if (IsClosed()) {
4225 return;
4226 }
korniltsev.anatolyec390b52017-07-25 00:00:254227 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144228 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434229}
4230
4231void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4232 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254233 if (IsClosed()) {
4234 return;
4235 }
korniltsev.anatolyec390b52017-07-25 00:00:254236 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144237 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434238}
4239
Henrik Boström31638672017-11-23 16:48:324240void PeerConnection::PostSetSessionDescriptionSuccess(
4241 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:404242 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4243 signaling_thread()->Post(RTC_FROM_HERE, this,
4244 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:324245}
4246
deadbeefab9b2d12015-10-14 18:33:114247void PeerConnection::PostSetSessionDescriptionFailure(
4248 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:404249 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:034250 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404251 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4252 msg->error = std::move(error);
4253 signaling_thread()->Post(RTC_FROM_HERE, this,
4254 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114255}
4256
4257void PeerConnection::PostCreateSessionDescriptionFailure(
4258 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:034259 RTCError error) {
4260 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404261 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4262 msg->error = std::move(error);
4263 signaling_thread()->Post(RTC_FROM_HERE, this,
4264 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114265}
4266
zhihuang1c378ed2017-08-17 21:10:504267void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:544268 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:114269 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:544270 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:504271
Steve Antondcc3c022017-12-23 00:02:544272 if (IsUnifiedPlan()) {
4273 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4274 } else {
4275 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4276 }
4277
Steve Antonfa2260d2017-12-29 00:38:234278 // Intentionally unset the data channel type for RTP data channel with the
4279 // second condition. Otherwise the RTP data channels would be successfully
4280 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4281 // when building with chromium. We want to leave RTP data channels broken, so
4282 // people won't try to use them.
4283 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4284 session_options->data_channel_type = data_channel_type();
4285 }
4286
Steve Antondcc3c022017-12-23 00:02:544287 // Apply ICE restart flag and renomination flag.
4288 for (auto& options : session_options->media_description_options) {
4289 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4290 options.transport_options.enable_ice_renomination =
4291 configuration_.enable_ice_renomination;
4292 }
4293
4294 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444295 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:124296 session_options->pooled_ice_credentials =
4297 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4298 RTC_FROM_HERE,
4299 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4300 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 09:25:484301 session_options->offer_extmap_allow_mixed =
4302 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:054303
4304 if (configuration_.enable_dtls_srtp &&
4305 !configuration_.enable_dtls_srtp.value()) {
4306 session_options->media_transport_settings =
4307 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4308 }
Steve Antondcc3c022017-12-23 00:02:544309}
4310
4311void PeerConnection::GetOptionsForPlanBOffer(
4312 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4313 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504314 // Figure out transceiver directional preferences.
4315 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4316 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4317
4318 // By default, generate sendrecv/recvonly m= sections.
4319 bool recv_audio = true;
4320 bool recv_video = true;
4321
4322 // By default, only offer a new m= section if we have media to send with it.
4323 bool offer_new_audio_description = send_audio;
4324 bool offer_new_video_description = send_video;
4325 bool offer_new_data_description = HasDataChannels();
4326
4327 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544328 if (offer_answer_options.offer_to_receive_audio !=
4329 RTCOfferAnswerOptions::kUndefined) {
4330 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:504331 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:544332 offer_new_audio_description ||
4333 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:504334 }
Steve Antondcc3c022017-12-23 00:02:544335 if (offer_answer_options.offer_to_receive_video !=
4336 RTCOfferAnswerOptions::kUndefined) {
4337 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504338 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:544339 offer_new_video_description ||
4340 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504341 }
4342
Danil Chapovalov66cadcc2018-06-19 14:47:434343 absl::optional<size_t> audio_index;
4344 absl::optional<size_t> video_index;
4345 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:504346 // If a current description exists, generate m= sections in the same order,
4347 // using the first audio/video/data section that appears and rejecting
4348 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:174349 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:504350 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:174351 local_description(),
Steve Anton1d03a752017-11-27 22:30:094352 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4353 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4354 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:114355 }
4356
zhihuang1c378ed2017-08-17 21:10:504357 // Add audio/video/data m= sections to the end if needed.
4358 if (!audio_index && offer_new_audio_description) {
4359 session_options->media_description_options.push_back(
4360 cricket::MediaDescriptionOptions(
4361 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:094362 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4363 false));
Oskar Sundbom9b28a032017-11-16 09:53:304364 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:454365 }
zhihuang1c378ed2017-08-17 21:10:504366 if (!video_index && offer_new_video_description) {
4367 session_options->media_description_options.push_back(
4368 cricket::MediaDescriptionOptions(
4369 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:094370 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4371 false));
Oskar Sundbom9b28a032017-11-16 09:53:304372 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:454373 }
zhihuang1c378ed2017-08-17 21:10:504374 if (!data_index && offer_new_data_description) {
4375 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234376 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:304377 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504378 }
4379
4380 cricket::MediaDescriptionOptions* audio_media_description_options =
4381 !audio_index ? nullptr
4382 : &session_options->media_description_options[*audio_index];
4383 cricket::MediaDescriptionOptions* video_media_description_options =
4384 !video_index ? nullptr
4385 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:504386
Amit Hilbuchc63ddb22019-01-02 18:13:584387 AddPlanBRtpSenderOptions(GetSendersInternal(),
4388 audio_media_description_options,
4389 video_media_description_options,
4390 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544391}
4392
Steve Antondcc3c022017-12-23 00:02:544393static cricket::MediaDescriptionOptions
4394GetMediaDescriptionOptionsForTransceiver(
4395 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4396 transceiver,
4397 const std::string& mid) {
4398 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:084399 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:544400 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 17:25:514401 media_description_options.codec_preferences =
4402 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 18:58:304403 // This behavior is specified in JSEP. The gist is that:
4404 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4405 // sendrecv.
4406 // 2. If the MSID is included, then it must be included in any subsequent
4407 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-26 01:13:564408 if (transceiver->stopped() ||
4409 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4410 !transceiver->internal()->has_ever_been_used_to_send())) {
4411 return media_description_options;
Steve Anton5f94aa22018-02-01 18:58:304412 }
Amit Hilbuchbcd39d42019-01-26 01:13:564413
4414 cricket::SenderOptions sender_options;
4415 sender_options.track_id = transceiver->sender()->id();
4416 sender_options.stream_ids = transceiver->sender()->stream_ids();
4417
4418 // The following sets up RIDs and Simulcast.
4419 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 23:55:194420 RtpParameters send_parameters =
4421 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-26 01:13:564422 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4423 send_parameters.encodings.end(),
4424 [](const RtpEncodingParameters& encoding) {
4425 return !encoding.rid.empty();
4426 });
4427
Amit Hilbuchb7446ed2019-01-28 20:25:254428 std::vector<RidDescription> send_rids;
4429 SimulcastLayerList send_layers;
4430 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4431 if (encoding.rid.empty()) {
4432 continue;
4433 }
4434 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4435 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4436 }
4437
Amit Hilbuchbcd39d42019-01-26 01:13:564438 if (has_rids) {
4439 sender_options.rids = send_rids;
4440 }
4441
4442 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:564443 // When RIDs are configured, we must set num_sim_layers to 0 to.
4444 // Otherwise, num_sim_layers must be 1 because either there is no
4445 // simulcast, or simulcast is acheived by munging the SDP.
4446 sender_options.num_sim_layers = has_rids ? 0 : 1;
4447 media_description_options.sender_options.push_back(sender_options);
4448
Steve Antondcc3c022017-12-23 00:02:544449 return media_description_options;
4450}
4451
Steve Anton5c72e712018-12-10 22:25:304452// Returns the ContentInfo at mline index |i|, or null if none exists.
4453static const ContentInfo* GetContentByIndex(
4454 const SessionDescriptionInterface* sdesc,
4455 size_t i) {
4456 if (!sdesc) {
4457 return nullptr;
4458 }
4459 const ContentInfos& contents = sdesc->description()->contents();
4460 return (i < contents.size() ? &contents[i] : nullptr);
4461}
4462
Steve Antondcc3c022017-12-23 00:02:544463void PeerConnection::GetOptionsForUnifiedPlanOffer(
4464 const RTCOfferAnswerOptions& offer_answer_options,
4465 cricket::MediaSessionOptions* session_options) {
4466 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4467 // Offers) and 5.2.2 (Subsequent Offers).
4468 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4469 const ContentInfos& local_contents =
4470 (local_description() ? local_description()->description()->contents()
4471 : ContentInfos());
4472 const ContentInfos& remote_contents =
4473 (remote_description() ? remote_description()->description()->contents()
4474 : ContentInfos());
4475 // The mline indices that can be recycled. New transceivers should reuse these
4476 // slots first.
4477 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-23 00:02:544478 // First, go through each media section that exists in either the local or
4479 // remote description and generate a media section in this offer for the
4480 // associated transceiver. If a media section can be recycled, generate a
4481 // default, rejected media section here that can be later overwritten.
4482 for (size_t i = 0;
4483 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4484 // Either |local_content| or |remote_content| is non-null.
4485 const ContentInfo* local_content =
4486 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:304487 const ContentInfo* current_local_content =
4488 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-23 00:02:544489 const ContentInfo* remote_content =
4490 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:304491 const ContentInfo* current_remote_content =
4492 GetContentByIndex(current_remote_description(), i);
4493 bool had_been_rejected =
4494 (current_local_content && current_local_content->rejected) ||
4495 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-23 00:02:544496 const std::string& mid =
4497 (local_content ? local_content->name : remote_content->name);
4498 cricket::MediaType media_type =
4499 (local_content ? local_content->media_description()->type()
4500 : remote_content->media_description()->type());
4501 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4502 media_type == cricket::MEDIA_TYPE_VIDEO) {
4503 auto transceiver = GetAssociatedTransceiver(mid);
4504 RTC_CHECK(transceiver);
4505 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 22:25:304506 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 23:33:484507 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:544508 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:084509 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4510 RtpTransceiverDirection::kInactive,
4511 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:544512 recycleable_mline_indices.push(i);
4513 } else {
4514 session_options->media_description_options.push_back(
4515 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4516 // CreateOffer shouldn't really cause any state changes in
4517 // PeerConnection, but we need a way to match new transceivers to new
4518 // media sections in SetLocalDescription and JSEP specifies this is done
4519 // by recording the index of the media section generated for the
4520 // transceiver in the offer.
4521 transceiver->internal()->set_mline_index(i);
4522 }
4523 } else {
4524 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:234525 RTC_CHECK(GetDataMid());
4526 if (had_been_rejected || mid != *GetDataMid()) {
4527 session_options->media_description_options.push_back(
4528 GetMediaDescriptionOptionsForRejectedData(mid));
4529 } else {
4530 session_options->media_description_options.push_back(
4531 GetMediaDescriptionOptionsForActiveData(mid));
4532 }
Steve Antondcc3c022017-12-23 00:02:544533 }
4534 }
Amit Hilbuchae3df542019-01-07 20:13:084535
Steve Antondcc3c022017-12-23 00:02:544536 // Next, look for transceivers that are newly added (that is, are not stopped
4537 // and not associated). Reuse media sections marked as recyclable first,
4538 // otherwise append to the end of the offer. New media sections should be
4539 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 16:29:424540 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:544541 if (transceiver->mid() || transceiver->stopped()) {
4542 continue;
4543 }
4544 size_t mline_index;
4545 if (!recycleable_mline_indices.empty()) {
4546 mline_index = recycleable_mline_indices.front();
4547 recycleable_mline_indices.pop();
4548 session_options->media_description_options[mline_index] =
4549 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:084550 mid_generator_());
Steve Antondcc3c022017-12-23 00:02:544551 } else {
4552 mline_index = session_options->media_description_options.size();
4553 session_options->media_description_options.push_back(
4554 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:084555 mid_generator_()));
Steve Antondcc3c022017-12-23 00:02:544556 }
4557 // See comment above for why CreateOffer changes the transceiver's state.
4558 transceiver->internal()->set_mline_index(mline_index);
4559 }
Steve Antonfa2260d2017-12-29 00:38:234560 // Lastly, add a m-section if we have local data channels and an m section
4561 // does not already exist.
4562 if (!GetDataMid() && HasDataChannels()) {
4563 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 20:13:084564 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-29 00:38:234565 }
Steve Antondcc3c022017-12-23 00:02:544566}
4567
4568void PeerConnection::GetOptionsForAnswer(
4569 const RTCOfferAnswerOptions& offer_answer_options,
4570 cricket::MediaSessionOptions* session_options) {
4571 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4572
4573 if (IsUnifiedPlan()) {
4574 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4575 } else {
4576 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4577 }
4578
Steve Antonfa2260d2017-12-29 00:38:234579 // Intentionally unset the data channel type for RTP data channel. Otherwise
4580 // the RTP data channels would be successfully negotiated by default and the
4581 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4582 // We want to leave RTP data channels broken, so people won't try to use them.
4583 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4584 session_options->data_channel_type = data_channel_type();
4585 }
4586
Steve Antondcc3c022017-12-23 00:02:544587 // Apply ICE renomination flag.
4588 for (auto& options : session_options->media_description_options) {
4589 options.transport_options.enable_ice_renomination =
4590 configuration_.enable_ice_renomination;
4591 }
zhihuang8f65cdf2016-05-07 01:40:304592
4593 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444594 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:124595 session_options->pooled_ice_credentials =
4596 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4597 RTC_FROM_HERE,
4598 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4599 port_allocator_.get()));
deadbeefab9b2d12015-10-14 18:33:114600}
4601
Steve Antondcc3c022017-12-23 00:02:544602void PeerConnection::GetOptionsForPlanBAnswer(
4603 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:114604 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504605 // Figure out transceiver directional preferences.
4606 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4607 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4608
4609 // By default, generate sendrecv/recvonly m= sections. The direction is also
4610 // restricted by the direction in the offer.
4611 bool recv_audio = true;
4612 bool recv_video = true;
4613
4614 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544615 if (offer_answer_options.offer_to_receive_audio !=
4616 RTCOfferAnswerOptions::kUndefined) {
4617 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:524618 }
Steve Antondcc3c022017-12-23 00:02:544619 if (offer_answer_options.offer_to_receive_video !=
4620 RTCOfferAnswerOptions::kUndefined) {
4621 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504622 }
4623
Danil Chapovalov66cadcc2018-06-19 14:47:434624 absl::optional<size_t> audio_index;
4625 absl::optional<size_t> video_index;
4626 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:294627
4628 // Generate m= sections that match those in the offer.
4629 // Note that mediasession.cc will handle intersection our preferred
4630 // direction with the offered direction.
4631 GenerateMediaDescriptionOptions(
4632 remote_description(),
4633 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4634 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4635 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:504636
4637 cricket::MediaDescriptionOptions* audio_media_description_options =
4638 !audio_index ? nullptr
4639 : &session_options->media_description_options[*audio_index];
4640 cricket::MediaDescriptionOptions* video_media_description_options =
4641 !video_index ? nullptr
4642 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:504643
Amit Hilbuchc63ddb22019-01-02 18:13:584644 AddPlanBRtpSenderOptions(GetSendersInternal(),
4645 audio_media_description_options,
4646 video_media_description_options,
4647 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544648}
zhihuangaf388472016-11-02 23:49:484649
Steve Antondcc3c022017-12-23 00:02:544650void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4651 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4652 cricket::MediaSessionOptions* session_options) {
4653 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4654 // Answers) and 5.3.2 (Subsequent Answers).
4655 RTC_DCHECK(remote_description());
4656 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4657 for (const ContentInfo& content :
4658 remote_description()->description()->contents()) {
4659 cricket::MediaType media_type = content.media_description()->type();
4660 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4661 media_type == cricket::MEDIA_TYPE_VIDEO) {
4662 auto transceiver = GetAssociatedTransceiver(content.name);
4663 RTC_CHECK(transceiver);
4664 session_options->media_description_options.push_back(
4665 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4666 } else {
4667 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:404668 // Reject all data sections if data channels are disabled.
4669 // Reject a data section if it has already been rejected.
4670 // Reject all data sections except for the first one.
4671 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4672 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:234673 session_options->media_description_options.push_back(
4674 GetMediaDescriptionOptionsForRejectedData(content.name));
4675 } else {
4676 session_options->media_description_options.push_back(
4677 GetMediaDescriptionOptionsForActiveData(content.name));
4678 }
Steve Antondcc3c022017-12-23 00:02:544679 }
4680 }
htaa2a49d92016-03-04 10:51:394681}
4682
zhihuang1c378ed2017-08-17 21:10:504683void PeerConnection::GenerateMediaDescriptionOptions(
4684 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:094685 RtpTransceiverDirection audio_direction,
4686 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:434687 absl::optional<size_t>* audio_index,
4688 absl::optional<size_t>* video_index,
4689 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:394690 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504691 for (const cricket::ContentInfo& content :
4692 session_desc->description()->contents()) {
4693 if (IsAudioContent(&content)) {
4694 // If we already have an audio m= section, reject this extra one.
4695 if (*audio_index) {
4696 session_options->media_description_options.push_back(
4697 cricket::MediaDescriptionOptions(
4698 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 22:25:304699 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:504700 } else {
Steve Anton5c72e712018-12-10 22:25:304701 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:504702 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:304703 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4704 content.name, audio_direction,
4705 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:304706 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504707 }
4708 } else if (IsVideoContent(&content)) {
4709 // If we already have an video m= section, reject this extra one.
4710 if (*video_index) {
4711 session_options->media_description_options.push_back(
4712 cricket::MediaDescriptionOptions(
4713 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 22:25:304714 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:504715 } else {
Steve Anton5c72e712018-12-10 22:25:304716 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:504717 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:304718 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4719 content.name, video_direction,
4720 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:304721 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504722 }
4723 } else {
4724 RTC_DCHECK(IsDataContent(&content));
4725 // If we already have an data m= section, reject this extra one.
4726 if (*data_index) {
4727 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234728 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504729 } else {
4730 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234731 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304732 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504733 }
4734 }
htaa2a49d92016-03-04 10:51:394735 }
deadbeefab9b2d12015-10-14 18:33:114736}
4737
Steve Antonfa2260d2017-12-29 00:38:234738cricket::MediaDescriptionOptions
4739PeerConnection::GetMediaDescriptionOptionsForActiveData(
4740 const std::string& mid) const {
4741 // Direction for data sections is meaningless, but legacy endpoints might
4742 // expect sendrecv.
4743 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4744 RtpTransceiverDirection::kSendRecv,
4745 /*stopped=*/false);
4746 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4747 return options;
4748}
4749
4750cricket::MediaDescriptionOptions
4751PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4752 const std::string& mid) const {
4753 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4754 RtpTransceiverDirection::kInactive,
4755 /*stopped=*/true);
4756 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4757 return options;
4758}
4759
Danil Chapovalov66cadcc2018-06-19 14:47:434760absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234761 switch (data_channel_type_) {
4762 case cricket::DCT_RTP:
4763 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434764 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234765 }
4766 return rtp_data_channel_->content_name();
4767 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354768 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 19:23:224769 case cricket::DCT_MEDIA_TRANSPORT:
4770 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-29 00:38:234771 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434772 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234773 }
4774}
4775
Steve Anton4171afb2017-11-20 18:20:224776void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4777 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4778 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404779 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074780}
4781
Steve Anton4171afb2017-11-20 18:20:224782void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114783 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224784 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114785 cricket::MediaType media_type,
4786 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364787 RTC_DCHECK(!IsUnifiedPlan());
4788
Steve Anton4171afb2017-11-20 18:20:224789 std::vector<RtpSenderInfo>* current_senders =
4790 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114791
Steve Anton4171afb2017-11-20 18:20:224792 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014793 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224794 for (auto sender_it = current_senders->begin();
4795 sender_it != current_senders->end();
4796 /* incremented manually */) {
4797 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114798 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224799 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094800 std::string params_stream_id;
4801 if (params) {
4802 params_stream_id =
4803 (!params->first_stream_id().empty() ? params->first_stream_id()
4804 : kDefaultStreamId);
4805 }
Seth Hampson5b4f0752018-04-02 23:31:364806 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094807 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404808 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104809 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224810 sender_exists) {
4811 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404812 } else {
Steve Anton4171afb2017-11-20 18:20:224813 OnRemoteSenderRemoved(info, media_type);
4814 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114815 }
4816 }
4817
Steve Anton4171afb2017-11-20 18:20:224818 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114819 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334820 if (!params.has_ssrcs()) {
4821 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4822 // sender, this means it is coming from a Unified Plan endpoint,so we just
4823 // create a default.
4824 default_sender_needed = true;
4825 break;
4826 }
4827
Seth Hampson845e8782018-03-02 19:34:104828 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364829 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334830 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4831 // not supported in Plan B, we just take the first here and create the
4832 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104833 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094834 (!params.first_stream_id().empty() ? params.first_stream_id()
4835 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224836 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114837 uint32_t ssrc = params.first_ssrc();
4838
4839 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104840 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114841 if (!stream) {
4842 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194843 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104844 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114845 remote_streams_->AddStream(stream);
4846 new_streams->AddStream(stream);
4847 }
4848
Steve Anton4171afb2017-11-20 18:20:224849 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184850 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224851 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104852 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224853 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114854 }
4855 }
deadbeefbda7e0b2015-12-09 01:13:404856
Steve Anton4171afb2017-11-20 18:20:224857 // Add default sender if necessary.
4858 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404859 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104860 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404861 if (!default_stream) {
4862 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194863 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104864 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404865 remote_streams_->AddStream(default_stream);
4866 new_streams->AddStream(default_stream);
4867 }
Steve Anton4171afb2017-11-20 18:20:224868 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4869 ? kDefaultAudioSenderId
4870 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104871 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184872 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224873 if (!default_sender_info) {
4874 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 01:07:054875 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 18:20:224876 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404877 }
4878 }
deadbeefab9b2d12015-10-14 18:33:114879}
4880
Steve Anton4171afb2017-11-20 18:20:224881void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4882 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234883 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4884 << " receiver for track_id=" << sender_info.sender_id
4885 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114886
Steve Anton3d954a62018-04-02 18:27:234887 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114888 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224889 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114890 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224891 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114892 } else {
nisseeb4ca4e2017-01-12 10:24:274893 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114894 }
4895}
4896
Steve Anton4171afb2017-11-20 18:20:224897void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4898 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094899 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4900 << " receiver for track_id=" << sender_info.sender_id
4901 << " and stream_id=" << sender_info.stream_id;
4902
Seth Hampson845e8782018-03-02 19:34:104903 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114904
Henrik Boström933d8b02017-10-10 17:05:164905 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114906 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194907 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4908 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224909 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114910 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224911 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114912 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114913 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114914 }
4915 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194916 // Stopping or destroying a VideoRtpReceiver will end the
4917 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224918 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114919 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224920 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114921 if (video_track) {
perkjd61bf802016-03-24 10:16:194922 // There's no guarantee the track is still available, e.g. the track may
4923 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114924 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114925 }
4926 } else {
nisseede5da42017-01-12 13:15:364927 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114928 }
Henrik Boström933d8b02017-10-10 17:05:164929 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164930 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164931 }
deadbeefab9b2d12015-10-14 18:33:114932}
4933
4934void PeerConnection::UpdateEndedRemoteMediaStreams() {
4935 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4936 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4937 MediaStreamInterface* stream = remote_streams_->at(i);
4938 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4939 streams_to_remove.push_back(stream);
4940 }
4941 }
4942
Taylor Brandstetter98cde262016-05-31 20:02:214943 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114944 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164945 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114946 }
4947}
4948
Steve Anton4171afb2017-11-20 18:20:224949void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114950 const std::vector<cricket::StreamParams>& streams,
4951 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224952 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114953
Seth Hampson845e8782018-03-02 19:34:104954 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114955 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224956 for (auto sender_it = current_senders->begin();
4957 sender_it != current_senders->end();
4958 /* incremented manually */) {
4959 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114960 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224961 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4962 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104963 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224964 OnLocalSenderRemoved(info, media_type);
4965 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114966 } else {
Steve Anton4171afb2017-11-20 18:20:224967 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114968 }
4969 }
4970
Steve Anton4171afb2017-11-20 18:20:224971 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114972 for (const cricket::StreamParams& params : streams) {
4973 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224974 // sender id.
Seth Hampson845e8782018-03-02 19:34:104975 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224976 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114977 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224978 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184979 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224980 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104981 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224982 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114983 }
4984 }
4985}
4986
Steve Anton4171afb2017-11-20 18:20:224987void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4988 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364989 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224990 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014991 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224992 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4993 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254994 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114995 return;
4996 }
4997
deadbeeffac06552015-11-25 19:26:014998 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254999 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075000 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015001 return;
deadbeefab9b2d12015-10-14 18:33:115002 }
deadbeeffac06552015-11-25 19:26:015003
Seth Hampson5b4f0752018-04-02 23:31:365004 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:225005 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:115006}
5007
Steve Anton4171afb2017-11-20 18:20:225008void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5009 cricket::MediaType media_type) {
5010 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:015011 if (!sender) {
5012 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:115013 // SessionDescriptions has been renegotiated.
5014 return;
5015 }
deadbeeffac06552015-11-25 19:26:015016
5017 // A sender has been removed from the SessionDescription but it's still
5018 // associated with the PeerConnection. This only occurs if the SDP doesn't
5019 // match with the calls to CreateSender, AddStream and RemoveStream.
5020 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:255021 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075022 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015023 return;
deadbeefab9b2d12015-10-14 18:33:115024 }
deadbeeffac06552015-11-25 19:26:015025
Steve Anton4171afb2017-11-20 18:20:225026 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:115027}
5028
5029void PeerConnection::UpdateLocalRtpDataChannels(
5030 const cricket::StreamParamsVec& streams) {
5031 std::vector<std::string> existing_channels;
5032
5033 // Find new and active data channels.
5034 for (const cricket::StreamParams& params : streams) {
5035 // |it->sync_label| is actually the data channel label. The reason is that
5036 // we use the same naming of data channels as we do for
5037 // MediaStreams and Tracks.
5038 // For MediaStreams, the sync_label is the MediaStream label and the
5039 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:105040 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:115041 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:565042 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:255043 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:115044 continue;
5045 }
5046 // Set the SSRC the data channel should use for sending.
5047 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5048 existing_channels.push_back(data_channel_it->first);
5049 }
5050
5051 UpdateClosingRtpDataChannels(existing_channels, true);
5052}
5053
5054void PeerConnection::UpdateRemoteRtpDataChannels(
5055 const cricket::StreamParamsVec& streams) {
5056 std::vector<std::string> existing_channels;
5057
5058 // Find new and active data channels.
5059 for (const cricket::StreamParams& params : streams) {
5060 // The data channel label is either the mslabel or the SSRC if the mslabel
5061 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:105062 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:115063 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:105064 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:115065 auto data_channel_it = rtp_data_channels_.find(label);
5066 if (data_channel_it == rtp_data_channels_.end()) {
5067 // This is a new data channel.
5068 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5069 } else {
5070 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5071 }
5072 existing_channels.push_back(label);
5073 }
5074
5075 UpdateClosingRtpDataChannels(existing_channels, false);
5076}
5077
5078void PeerConnection::UpdateClosingRtpDataChannels(
5079 const std::vector<std::string>& active_channels,
5080 bool is_local_update) {
5081 auto it = rtp_data_channels_.begin();
5082 while (it != rtp_data_channels_.end()) {
5083 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-29 01:25:265084 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 18:33:115085 ++it;
5086 continue;
5087 }
5088
5089 if (is_local_update) {
5090 data_channel->SetSendSsrc(0);
5091 } else {
5092 data_channel->RemotePeerRequestClose();
5093 }
5094
5095 if (data_channel->state() == DataChannel::kClosed) {
5096 rtp_data_channels_.erase(it);
5097 it = rtp_data_channels_.begin();
5098 } else {
5099 ++it;
5100 }
5101 }
5102}
5103
5104void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5105 uint32_t remote_ssrc) {
5106 rtc::scoped_refptr<DataChannel> channel(
5107 InternalCreateDataChannel(label, nullptr));
5108 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:255109 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:075110 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:115111 return;
5112 }
5113 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:395114 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5115 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:165116 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:115117}
5118
5119rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5120 const std::string& label,
5121 const InternalDataChannelInit* config) {
5122 if (IsClosed()) {
5123 return nullptr;
5124 }
Steve Anton75737c02017-11-06 18:37:175125 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:255126 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:115127 << "InternalCreateDataChannel: Data is not supported in this call.";
5128 return nullptr;
5129 }
5130 InternalDataChannelInit new_config =
5131 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 19:23:225132 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 18:33:115133 if (new_config.id < 0) {
5134 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:175135 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:115136 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:255137 RTC_LOG(LS_ERROR)
5138 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:115139 return nullptr;
5140 }
5141 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:255142 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:075143 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:115144 return nullptr;
5145 }
5146 }
5147
Steve Anton75737c02017-11-06 18:37:175148 rtc::scoped_refptr<DataChannel> channel(
5149 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:115150 if (!channel) {
5151 sid_allocator_.ReleaseSid(new_config.id);
5152 return nullptr;
5153 }
5154
5155 if (channel->data_channel_type() == cricket::DCT_RTP) {
5156 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:255157 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5158 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:115159 return nullptr;
5160 }
5161 rtp_data_channels_[channel->label()] = channel;
5162 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:225163 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 18:33:115164 sctp_data_channels_.push_back(channel);
5165 channel->SignalClosed.connect(this,
5166 &PeerConnection::OnSctpDataChannelClosed);
5167 }
5168
Steve Anton2d8609c2018-01-24 00:38:465169 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:115170 return channel;
5171}
5172
5173bool PeerConnection::HasDataChannels() const {
5174 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5175}
5176
5177void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 10:29:385178 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 18:33:115179 for (const auto& channel : sctp_data_channels_) {
5180 if (channel->id() < 0) {
5181 int sid;
5182 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 10:29:385183 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5184 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 18:33:115185 continue;
5186 }
5187 channel->SetSctpSid(sid);
5188 }
5189 }
Harald Alvestrand1f928d32019-03-28 10:29:385190 // Since closing modifies the list of channels, we have to do the actual
5191 // closing outside the loop.
5192 for (const auto& channel : channels_to_close) {
5193 channel->CloseAbruptly();
5194 }
deadbeefab9b2d12015-10-14 18:33:115195}
5196
5197void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:295198 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:115199 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5200 ++it) {
5201 if (it->get() == channel) {
5202 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:325203 // After the closing procedure is done, it's safe to use this ID for
5204 // another data channel.
deadbeefab9b2d12015-10-14 18:33:115205 sid_allocator_.ReleaseSid(channel->id());
5206 }
deadbeefbd292462015-12-15 02:15:295207 // Since this method is triggered by a signal from the DataChannel,
5208 // we can't free it directly here; we need to free it asynchronously.
5209 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:115210 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:405211 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5212 nullptr);
deadbeefab9b2d12015-10-14 18:33:115213 return;
5214 }
5215 }
5216}
5217
deadbeefab9b2d12015-10-14 18:33:115218void PeerConnection::OnDataChannelDestroyed() {
5219 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5220 // DataChannel may callback to us and try to modify the list.
5221 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5222 temp_rtp_dcs.swap(rtp_data_channels_);
5223 for (const auto& kv : temp_rtp_dcs) {
5224 kv.second->OnTransportChannelDestroyed();
5225 }
5226
5227 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5228 temp_sctp_dcs.swap(sctp_data_channels_);
5229 for (const auto& channel : temp_sctp_dcs) {
5230 channel->OnTransportChannelDestroyed();
5231 }
5232}
5233
5234void PeerConnection::OnDataChannelOpenMessage(
5235 const std::string& label,
5236 const InternalDataChannelInit& config) {
5237 rtc::scoped_refptr<DataChannel> channel(
5238 InternalCreateDataChannel(label, &config));
5239 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:255240 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:115241 return;
5242 }
5243
deadbeefa601f5c2016-06-06 21:27:395244 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5245 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:165246 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:415247 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:115248}
5249
Bjorn Mellem175aa2e2018-11-08 19:23:225250bool PeerConnection::HandleOpenMessage_s(
5251 const cricket::ReceiveDataParams& params,
5252 const rtc::CopyOnWriteBuffer& buffer) {
5253 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5254 // Received OPEN message; parse and signal that a new data channel should
5255 // be created.
5256 std::string label;
5257 InternalDataChannelInit config;
5258 config.id = params.ssrc;
5259 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5260 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5261 << params.ssrc;
5262 return true;
5263 }
5264 config.open_handshake_role = InternalDataChannelInit::kAcker;
5265 OnDataChannelOpenMessage(label, config);
5266 return true;
5267 }
5268 return false;
5269}
5270
Steve Anton4171afb2017-11-20 18:20:225271rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5272PeerConnection::GetAudioTransceiver() const {
5273 // This method only works with Plan B SDP, where there is a single
5274 // audio/video transceiver.
5275 RTC_DCHECK(!IsUnifiedPlan());
5276 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085277 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:225278 return transceiver;
5279 }
5280 }
5281 RTC_NOTREACHED();
5282 return nullptr;
5283}
5284
5285rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5286PeerConnection::GetVideoTransceiver() const {
5287 // This method only works with Plan B SDP, where there is a single
5288 // audio/video transceiver.
5289 RTC_DCHECK(!IsUnifiedPlan());
5290 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085291 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:225292 return transceiver;
5293 }
5294 }
5295 RTC_NOTREACHED();
5296 return nullptr;
5297}
5298
5299// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5300// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:505301bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:225302 switch (type) {
5303 case cricket::MEDIA_TYPE_AUDIO:
5304 return !GetAudioTransceiver()->internal()->senders().empty();
5305 case cricket::MEDIA_TYPE_VIDEO:
5306 return !GetVideoTransceiver()->internal()->senders().empty();
5307 case cricket::MEDIA_TYPE_DATA:
5308 return false;
5309 }
5310 RTC_NOTREACHED();
5311 return false;
zhihuang1c378ed2017-08-17 21:10:505312}
5313
Steve Anton4171afb2017-11-20 18:20:225314rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5315PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 16:29:425316 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225317 for (auto sender : transceiver->internal()->senders()) {
5318 if (sender->track() == track) {
5319 return sender;
5320 }
5321 }
5322 }
5323 return nullptr;
deadbeeffac06552015-11-25 19:26:015324}
5325
Steve Anton4171afb2017-11-20 18:20:225326rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5327PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 16:29:425328 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225329 for (auto sender : transceiver->internal()->senders()) {
5330 if (sender->id() == sender_id) {
5331 return sender;
5332 }
5333 }
5334 }
5335 return nullptr;
deadbeef70ab1a12015-09-28 23:53:555336}
5337
Steve Anton4171afb2017-11-20 18:20:225338rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5339PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 16:29:425340 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225341 for (auto receiver : transceiver->internal()->receivers()) {
5342 if (receiver->id() == receiver_id) {
5343 return receiver;
5344 }
5345 }
5346 }
5347 return nullptr;
deadbeef70ab1a12015-09-28 23:53:555348}
5349
Steve Anton4171afb2017-11-20 18:20:225350std::vector<PeerConnection::RtpSenderInfo>*
5351PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5352 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5353 media_type == cricket::MEDIA_TYPE_VIDEO);
5354 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5355 ? &remote_audio_sender_infos_
5356 : &remote_video_sender_infos_;
5357}
5358
5359std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:115360 cricket::MediaType media_type) {
5361 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5362 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:225363 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5364 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:115365}
5366
Steve Anton4171afb2017-11-20 18:20:225367const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5368 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:185369 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:225370 const std::string sender_id) const {
5371 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:185372 if (sender_info.stream_id == stream_id &&
5373 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:225374 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:115375 }
5376 }
5377 return nullptr;
5378}
5379
5380DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5381 for (const auto& channel : sctp_data_channels_) {
5382 if (channel->id() == sid) {
5383 return channel;
5384 }
5385 }
5386 return nullptr;
5387}
5388
Karl Wibergfb3be392019-03-22 13:13:225389PeerConnection::InitializePortAllocatorResult
5390PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:075391 const cricket::ServerAddresses& stun_servers,
5392 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:115393 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 13:13:225394 RTC_DCHECK_RUN_ON(network_thread());
5395
Taylor Brandstetterf8e65772016-06-28 00:20:155396 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:115397 // To handle both internal and externally created port allocator, we will
5398 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 13:13:225399 int port_allocator_flags = port_allocator_->flags();
5400 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5401 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5402 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:115403 // If the disable-IPv6 flag was specified, we'll not override it
5404 // by experiment.
5405 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 13:13:225406 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:475407 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5408 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 13:13:225409 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:115410 }
5411
zhihuangb09b3f92017-03-07 22:40:515412 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 13:13:225413 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:255414 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:515415 }
5416
Taylor Brandstettera1c30352016-05-13 15:15:115417 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 13:13:225418 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:255419 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:115420 }
5421
honghaiz60347052016-06-01 01:29:125422 if (configuration.candidate_network_policy ==
5423 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 13:13:225424 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:255425 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:125426 }
5427
Daniel Lazarenko2870b0a2018-01-25 09:30:225428 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 13:13:225429 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:225430 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5431 }
5432
Karl Wibergfb3be392019-03-22 13:13:225433 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 15:15:115434 // No step delay is used while allocating ports.
5435 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 17:41:585436 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 15:15:115437 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:115438 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:115439
Harald Alvestrandb2a74782018-06-28 11:54:075440 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:265441 for (auto& turn_server : turn_servers_copy) {
5442 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:255443 }
Taylor Brandstettera1c30352016-05-13 15:15:115444 // Call this last since it may create pooled allocator sessions using the
5445 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:495446 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265447 stun_servers, std::move(turn_servers_copy),
5448 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5449 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:495450 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 13:13:225451
5452 InitializePortAllocatorResult res;
5453 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5454 return res;
Taylor Brandstettera1c30352016-05-13 15:15:115455}
5456
deadbeef91dd5672016-05-18 23:55:305457bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:305458 const cricket::ServerAddresses& stun_servers,
5459 const std::vector<cricket::RelayServerConfig>& turn_servers,
5460 IceTransportsType type,
5461 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:405462 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:495463 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:285464 absl::optional<int> stun_candidate_keepalive_interval,
5465 bool have_local_description) {
Qingsi Wangc129c352019-04-18 17:41:585466 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 20:28:305467 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:455468 // According to JSEP, after setLocalDescription, changing the candidate pool
5469 // size is not allowed, and changing the set of ICE servers will not result
5470 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 09:37:285471 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 23:57:455472 port_allocator_->FreezeCandidatePool();
5473 }
Benjamin Wright6f80f092018-08-14 00:06:265474 // Add the custom tls turn servers if they exist.
5475 auto turn_servers_copy = turn_servers;
5476 for (auto& turn_server : turn_servers_copy) {
5477 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5478 }
Taylor Brandstettera1c30352016-05-13 15:15:115479 // Call this last since it may create pooled allocator sessions using the
5480 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:325481 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265482 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5483 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:115484}
5485
Steve Antonba818672017-11-06 18:21:575486cricket::ChannelManager* PeerConnection::channel_manager() const {
5487 return factory_->channel_manager();
5488}
5489
Elad Alon99c3fe52017-10-13 14:29:405490bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:145491 std::unique_ptr<RtcEventLogOutput> output,
5492 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 10:59:575493 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:165494 if (!event_log_) {
5495 return false;
5496 }
Bjorn Tereliusde939432017-11-20 16:38:145497 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:555498}
5499
5500void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 10:59:575501 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:165502 if (event_log_) {
5503 event_log_->StopLogging();
5504 }
ivoc14d5dbe2016-07-04 14:06:555505}
nisseeaabdf62017-05-05 09:23:025506
Amit Hilbuchdd9390c2018-11-14 00:26:055507cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:175508 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 16:29:425509 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055510 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:545511 if (channel && channel->content_name() == content_name) {
5512 return channel;
5513 }
Steve Anton75737c02017-11-06 18:37:175514 }
5515 if (rtp_data_channel() &&
5516 rtp_data_channel()->content_name() == content_name) {
5517 return rtp_data_channel();
5518 }
5519 return nullptr;
5520}
5521
5522bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 19:23:225523 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175524 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255525 RTC_LOG(LS_INFO)
5526 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075527 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175528 return false;
5529 }
Bjorn Mellem175aa2e2018-11-08 19:23:225530 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255531 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:075532 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175533 return false;
5534 }
5535
Bjorn Mellem175aa2e2018-11-08 19:23:225536 absl::optional<rtc::SSLRole> dtls_role;
5537 if (sctp_mid_) {
5538 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5539 } else if (is_caller_) {
5540 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5541 }
Zhi Huange830e682018-03-30 17:48:355542 if (dtls_role) {
5543 *role = *dtls_role;
5544 return true;
5545 }
5546 return false;
Steve Anton75737c02017-11-06 18:37:175547}
5548
5549bool PeerConnection::GetSslRole(const std::string& content_name,
5550 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 09:31:565551 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175552 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255553 RTC_LOG(LS_INFO)
5554 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075555 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:175556 return false;
5557 }
5558
Zhi Huange830e682018-03-30 17:48:355559 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5560 if (dtls_role) {
5561 *role = *dtls_role;
5562 return true;
5563 }
5564 return false;
Steve Anton75737c02017-11-06 18:37:175565}
5566
Steve Antonf8470812017-12-04 18:46:215567void PeerConnection::SetSessionError(SessionError error,
5568 const std::string& error_desc) {
5569 RTC_DCHECK_RUN_ON(signaling_thread());
5570 if (error != session_error_) {
5571 session_error_ = error;
5572 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:175573 }
5574}
5575
Zhi Huange830e682018-03-30 17:48:355576RTCError PeerConnection::UpdateSessionState(
5577 SdpType type,
5578 cricket::ContentSource source,
5579 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:565580 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175581
5582 // If there's already a pending error then no state transition should happen.
5583 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:215584 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:475585
Steve Anton6d6a2ae2017-12-05 01:19:475586 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:515587 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:595588 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:475589 }
5590
5591 // Update the signaling state according to the specified state machine (see
5592 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:515593 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:475594 ChangeSignalingState(source == cricket::CS_LOCAL
5595 ? PeerConnectionInterface::kHaveLocalOffer
5596 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:515597 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:475598 ChangeSignalingState(source == cricket::CS_LOCAL
5599 ? PeerConnectionInterface::kHaveLocalPrAnswer
5600 : PeerConnectionInterface::kHaveRemotePrAnswer);
5601 } else {
Steve Anton3828c062017-12-06 18:34:515602 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:475603 ChangeSignalingState(PeerConnectionInterface::kStable);
5604 }
5605
5606 // Update internal objects according to the session description's media
5607 // descriptions.
Zhi Huange830e682018-03-30 17:48:355608 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:475609 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:425610 return error;
Steve Anton6d6a2ae2017-12-05 01:19:475611 }
5612
Steve Anton8a006912017-12-04 23:25:565613 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175614}
5615
Steve Anton8a006912017-12-04 23:25:565616RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:515617 SdpType type,
Steve Anton8a006912017-12-04 23:25:565618 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:595619 const SessionDescriptionInterface* sdesc =
5620 (source == cricket::CS_LOCAL ? local_description()
5621 : remote_description());
Steve Anton75737c02017-11-06 18:37:175622 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:595623
5624 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 16:29:425625 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:175626 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:595627 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:055628 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595629 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:175630 continue;
5631 }
5632 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:305633 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:595634 if (!content_desc) {
5635 continue;
5636 }
5637 std::string error;
Yves Gerey665174f2018-06-19 13:03:055638 bool success = (source == cricket::CS_LOCAL)
5639 ? channel->SetLocalContent(content_desc, type, &error)
5640 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595641 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:575642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:595643 }
5644 }
5645
5646 // If using the RtpDataChannel, push down the new SDP section for it too.
5647 if (rtp_data_channel_) {
5648 const ContentInfo* data_content =
5649 cricket::GetFirstDataContent(sdesc->description());
5650 if (data_content && !data_content->rejected) {
5651 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:305652 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:595653 if (data_desc) {
5654 std::string error;
5655 bool success =
5656 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:515657 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:055658 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595659 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:575660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:595661 }
Steve Anton75737c02017-11-06 18:37:175662 }
5663 }
5664 }
Steve Antoned10bd92017-12-05 18:52:595665
Steve Anton75737c02017-11-06 18:37:175666 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5667 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5668 if (sctp_transport_ && local_description() && remote_description() &&
5669 cricket::GetFirstDataContent(local_description()->description()) &&
5670 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:565671 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:175672 RTC_FROM_HERE,
Karl Wiberg739506e2019-04-03 09:37:285673 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source,
5674 GetSctpPort(local_description()->description()),
5675 GetSctpPort(remote_description()->description())));
Steve Anton8a006912017-12-04 23:25:565676 if (!success) {
5677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5678 "Failed to push down SCTP parameters.");
5679 }
Steve Anton75737c02017-11-06 18:37:175680 }
Steve Antoned10bd92017-12-05 18:52:595681
Steve Anton8a006912017-12-04 23:25:565682 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175683}
5684
Karl Wiberg739506e2019-04-03 09:37:285685bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source,
5686 int local_sctp_port,
5687 int remote_sctp_port) {
5688 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 18:37:175689 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5690 // When we support "max-message-size", that would also be pushed down here.
Karl Wiberg739506e2019-04-03 09:37:285691 return cricket_sctp_transport()->Start(local_sctp_port, remote_sctp_port);
Steve Anton75737c02017-11-06 18:37:175692}
5693
Steve Anton8a006912017-12-04 23:25:565694RTCError PeerConnection::PushdownTransportDescription(
5695 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:515696 SdpType type) {
Steve Anton8a006912017-12-04 23:25:565697 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175698
Zhi Huange830e682018-03-30 17:48:355699 if (source == cricket::CS_LOCAL) {
5700 const SessionDescriptionInterface* sdesc = local_description();
5701 RTC_DCHECK(sdesc);
5702 return transport_controller_->SetLocalDescription(type,
5703 sdesc->description());
5704 } else {
5705 const SessionDescriptionInterface* sdesc = remote_description();
5706 RTC_DCHECK(sdesc);
5707 return transport_controller_->SetRemoteDescription(type,
5708 sdesc->description());
Steve Anton75737c02017-11-06 18:37:175709 }
Steve Anton75737c02017-11-06 18:37:175710}
5711
5712bool PeerConnection::GetTransportDescription(
5713 const SessionDescription* description,
5714 const std::string& content_name,
5715 cricket::TransportDescription* tdesc) {
5716 if (!description || !tdesc) {
5717 return false;
5718 }
5719 const TransportInfo* transport_info =
5720 description->GetTransportInfoByName(content_name);
5721 if (!transport_info) {
5722 return false;
5723 }
5724 *tdesc = transport_info->description;
5725 return true;
5726}
5727
Steve Anton75737c02017-11-06 18:37:175728cricket::IceConfig PeerConnection::ParseIceConfig(
5729 const PeerConnectionInterface::RTCConfiguration& config) const {
5730 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:175731 switch (config.continual_gathering_policy) {
5732 case PeerConnectionInterface::GATHER_ONCE:
5733 gathering_policy = cricket::GATHER_ONCE;
5734 break;
5735 case PeerConnectionInterface::GATHER_CONTINUALLY:
5736 gathering_policy = cricket::GATHER_CONTINUALLY;
5737 break;
5738 default:
5739 RTC_NOTREACHED();
5740 gathering_policy = cricket::GATHER_ONCE;
5741 }
Qingsi Wang9a5c6f82018-02-01 18:38:405742
Steve Anton75737c02017-11-06 18:37:175743 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235744 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5745 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175746 ice_config.prioritize_most_likely_candidate_pairs =
5747 config.prioritize_most_likely_ice_candidate_pairs;
5748 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:235749 RTCConfigurationToIceConfigOptionalInt(
5750 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175751 ice_config.continual_gathering_policy = gathering_policy;
5752 ice_config.presume_writable_when_fully_relayed =
5753 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:145754 ice_config.ice_check_interval_strong_connectivity =
5755 config.ice_check_interval_strong_connectivity;
5756 ice_config.ice_check_interval_weak_connectivity =
5757 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:175758 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-30 07:08:515759 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5760 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:175761 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:495762 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175763 ice_config.regather_all_networks_interval_range =
5764 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405765 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175766 return ice_config;
5767}
5768
Steve Anton75737c02017-11-06 18:37:175769bool PeerConnection::SendData(const cricket::SendDataParams& params,
5770 const rtc::CopyOnWriteBuffer& payload,
5771 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 09:31:565772 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 19:23:225773 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5774 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5775 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175776 return false;
5777 }
Bjorn Mellem175aa2e2018-11-08 19:23:225778 if (media_transport_) {
5779 SendDataParams send_params;
5780 send_params.type = ToWebrtcDataMessageType(params.type);
5781 send_params.ordered = params.ordered;
5782 if (params.max_rtx_count >= 0) {
5783 send_params.max_rtx_count = params.max_rtx_count;
5784 } else if (params.max_rtx_ms >= 0) {
5785 send_params.max_rtx_ms = params.max_rtx_ms;
5786 }
5787 return media_transport_->SendData(params.sid, send_params, payload).ok();
5788 }
Steve Anton75737c02017-11-06 18:37:175789 return rtp_data_channel_
5790 ? rtp_data_channel_->SendData(params, payload, result)
5791 : network_thread()->Invoke<bool>(
5792 RTC_FROM_HERE,
5793 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 06:51:005794 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 18:37:175795}
5796
5797bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225798 RTC_DCHECK_RUN_ON(signaling_thread());
5799 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 18:37:175800 // Don't log an error here, because DataChannels are expected to call
5801 // ConnectDataChannel in this state. It's the only way to initially tell
5802 // whether or not the underlying transport is ready.
5803 return false;
5804 }
Bjorn Mellem175aa2e2018-11-08 19:23:225805 if (media_transport_) {
5806 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5807 &DataChannel::OnChannelReady);
5808 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5809 &DataChannel::OnDataReceived);
5810 SignalMediaTransportChannelClosing_s.connect(
5811 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5812 SignalMediaTransportChannelClosed_s.connect(
5813 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5814 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175815 rtp_data_channel_->SignalReadyToSendData.connect(
5816 webrtc_data_channel, &DataChannel::OnChannelReady);
5817 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5818 &DataChannel::OnDataReceived);
5819 } else {
5820 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5821 &DataChannel::OnChannelReady);
5822 SignalSctpDataReceived.connect(webrtc_data_channel,
5823 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325824 SignalSctpClosingProcedureStartedRemotely.connect(
5825 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5826 SignalSctpClosingProcedureComplete.connect(
5827 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175828 }
5829 return true;
5830}
5831
5832void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225833 RTC_DCHECK_RUN_ON(signaling_thread());
5834 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255835 RTC_LOG(LS_ERROR)
5836 << "DisconnectDataChannel called when rtp_data_channel_ and "
5837 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175838 return;
5839 }
Bjorn Mellem175aa2e2018-11-08 19:23:225840 if (media_transport_) {
5841 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5842 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5843 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5844 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5845 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175846 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5847 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5848 } else {
5849 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5850 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325851 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5852 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175853 }
5854}
5855
5856void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225857 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 18:31:485858 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 19:23:225859 return;
5860 }
Steve Anton75737c02017-11-06 18:37:175861 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255862 RTC_LOG(LS_ERROR)
5863 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175864 return;
5865 }
5866 network_thread()->Invoke<void>(
5867 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 06:51:005868 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 18:37:175869}
5870
5871void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225872 if (media_transport_) {
5873 media_transport_->CloseChannel(sid);
5874 return;
5875 }
Steve Anton75737c02017-11-06 18:37:175876 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255877 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075878 "NULL.";
Steve Anton75737c02017-11-06 18:37:175879 return;
5880 }
5881 network_thread()->Invoke<void>(
5882 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 06:51:005883 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 18:37:175884}
5885
5886bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 19:23:225887 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175888 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 19:23:225889 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 18:37:175890 sctp_ready_to_send_data_;
5891}
5892
Bjorn Mellem175aa2e2018-11-08 19:23:225893void PeerConnection::OnDataReceived(int channel_id,
5894 DataMessageType type,
5895 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 09:37:285896 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 19:23:225897 cricket::ReceiveDataParams params;
5898 params.sid = channel_id;
5899 params.type = ToCricketDataMessageType(type);
5900 media_transport_invoker_->AsyncInvoke<void>(
5901 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5902 RTC_DCHECK_RUN_ON(signaling_thread());
5903 if (!HandleOpenMessage_s(params, buffer)) {
5904 SignalMediaTransportReceivedData_s(params, buffer);
5905 }
5906 });
5907}
5908
5909void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 09:37:285910 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 19:23:225911 media_transport_invoker_->AsyncInvoke<void>(
5912 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5913 RTC_DCHECK_RUN_ON(signaling_thread());
5914 SignalMediaTransportChannelClosing_s(channel_id);
5915 });
5916}
5917
5918void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 09:37:285919 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 19:23:225920 media_transport_invoker_->AsyncInvoke<void>(
5921 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5922 RTC_DCHECK_RUN_ON(signaling_thread());
5923 SignalMediaTransportChannelClosed_s(channel_id);
5924 });
5925}
5926
Danil Chapovalov66cadcc2018-06-19 14:47:435927absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 09:31:565928 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 17:48:355929 if (sctp_mid_ && transport_controller_) {
5930 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5931 if (dtls_transport) {
5932 return dtls_transport->transport_name();
5933 }
Danil Chapovalov66cadcc2018-06-19 14:47:435934 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355935 }
Danil Chapovalov66cadcc2018-06-19 14:47:435936 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355937}
5938
Qingsi Wang72a43a12018-02-21 00:03:185939cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5940 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455941 network_thread()->Invoke<void>(
5942 RTC_FROM_HERE,
5943 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5944 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185945 return candidate_states_list;
5946}
5947
Steve Anton5dfde182018-02-06 18:34:405948std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5949 const {
Karl Wiberga58e1692019-03-26 12:33:435950 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 18:34:405951 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 16:29:425952 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055953 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:405954 if (channel) {
5955 transport_names_by_mid[channel->content_name()] =
5956 channel->transport_name();
5957 }
Steve Anton75737c02017-11-06 18:37:175958 }
Steve Anton5dfde182018-02-06 18:34:405959 if (rtp_data_channel_) {
5960 transport_names_by_mid[rtp_data_channel_->content_name()] =
5961 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175962 }
5963 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435964 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355965 RTC_DCHECK(transport_name);
5966 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175967 }
Steve Anton5dfde182018-02-06 18:34:405968 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175969}
5970
Steve Anton5dfde182018-02-06 18:34:405971std::map<std::string, cricket::TransportStats>
5972PeerConnection::GetTransportStatsByNames(
5973 const std::set<std::string>& transport_names) {
5974 if (!network_thread()->IsCurrent()) {
5975 return network_thread()
5976 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5977 RTC_FROM_HERE,
5978 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175979 }
Karl Wiberg2cc368f2019-04-02 09:31:565980 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 18:34:405981 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5982 for (const std::string& transport_name : transport_names) {
5983 cricket::TransportStats transport_stats;
5984 bool success =
5985 transport_controller_->GetStats(transport_name, &transport_stats);
5986 if (success) {
5987 transport_stats_by_name[transport_name] = std::move(transport_stats);
5988 } else {
5989 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5990 << transport_name;
5991 }
5992 }
5993 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175994}
5995
5996bool PeerConnection::GetLocalCertificate(
5997 const std::string& transport_name,
5998 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355999 if (!certificate) {
6000 return false;
6001 }
6002 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6003 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:176004}
6005
Taylor Brandstetterc3928662018-02-23 21:04:516006std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:176007 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:516008 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:176009}
6010
6011cricket::DataChannelType PeerConnection::data_channel_type() const {
6012 return data_channel_type_;
6013}
6014
6015bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 13:36:536016 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176017 return pending_ice_restarts_.find(content_name) !=
6018 pending_ice_restarts_.end();
6019}
6020
Steve Anton75737c02017-11-06 18:37:176021bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6022 return transport_controller_->NeedsIceRestart(content_name);
6023}
6024
6025void PeerConnection::OnCertificateReady(
6026 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6027 transport_controller_->SetLocalCertificate(certificate);
6028}
6029
6030void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:216031 SetSessionError(SessionError::kTransport,
6032 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:176033}
6034
Alex Loiko9289eda2018-11-23 16:18:596035void PeerConnection::OnTransportControllerConnectionState(
6036 cricket::IceConnectionState state) {
6037 switch (state) {
6038 case cricket::kIceConnectionConnecting:
6039 // If the current state is Connected or Completed, then there were
6040 // writable channels but now there are not, so the next state must
6041 // be Disconnected.
6042 // kIceConnectionConnecting is currently used as the default,
6043 // un-connected state by the TransportController, so its only use is
6044 // detecting disconnections.
6045 if (ice_connection_state_ ==
6046 PeerConnectionInterface::kIceConnectionConnected ||
6047 ice_connection_state_ ==
6048 PeerConnectionInterface::kIceConnectionCompleted) {
6049 SetIceConnectionState(
6050 PeerConnectionInterface::kIceConnectionDisconnected);
6051 }
6052 break;
6053 case cricket::kIceConnectionFailed:
6054 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6055 break;
6056 case cricket::kIceConnectionConnected:
6057 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6058 "all transports are writable.";
6059 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6060 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6061 break;
6062 case cricket::kIceConnectionCompleted:
6063 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6064 "all transports are complete.";
6065 if (ice_connection_state_ !=
6066 PeerConnectionInterface::kIceConnectionConnected) {
6067 // If jumping directly from "checking" to "connected",
6068 // signal "connected" first.
6069 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6070 }
6071 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6072 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6073 ReportTransportStats();
6074 break;
6075 default:
6076 RTC_NOTREACHED();
6077 }
6078}
6079
Steve Anton75737c02017-11-06 18:37:176080void PeerConnection::OnTransportControllerCandidatesGathered(
6081 const std::string& transport_name,
6082 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 18:37:176083 int sdp_mline_index;
6084 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:256085 RTC_LOG(LS_ERROR)
6086 << "OnTransportControllerCandidatesGathered: content name "
6087 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:176088 return;
6089 }
6090
6091 for (cricket::Candidates::const_iterator citer = candidates.begin();
6092 citer != candidates.end(); ++citer) {
6093 // Use transport_name as the candidate media id.
6094 std::unique_ptr<JsepIceCandidate> candidate(
6095 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6096 if (local_description()) {
6097 mutable_local_description()->AddCandidate(candidate.get());
6098 }
6099 OnIceCandidate(std::move(candidate));
6100 }
6101}
6102
6103void PeerConnection::OnTransportControllerCandidatesRemoved(
6104 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 18:37:176105 // Sanity check.
6106 for (const cricket::Candidate& candidate : candidates) {
6107 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:256108 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:076109 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:256110 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:176111 return;
6112 }
6113 }
6114
6115 if (local_description()) {
6116 mutable_local_description()->RemoveCandidates(candidates);
6117 }
6118 OnIceCandidatesRemoved(candidates);
6119}
6120
6121void PeerConnection::OnTransportControllerDtlsHandshakeError(
6122 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:536123 RTC_HISTOGRAM_ENUMERATION(
6124 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6125 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:176126}
6127
Steve Antoned10bd92017-12-05 18:52:596128void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 16:29:426129 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056130 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:596131 if (channel && !channel->enabled()) {
6132 channel->Enable(true);
6133 }
Steve Anton75737c02017-11-06 18:37:176134 }
6135
Steve Anton4171afb2017-11-20 18:20:226136 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:176137 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:226138 }
Steve Anton75737c02017-11-06 18:37:176139}
6140
6141// Returns the media index for a local ice candidate given the content name.
6142bool PeerConnection::GetLocalCandidateMediaIndex(
6143 const std::string& content_name,
6144 int* sdp_mline_index) {
6145 if (!local_description() || !sdp_mline_index) {
6146 return false;
6147 }
6148
6149 bool content_found = false;
6150 const ContentInfos& contents = local_description()->description()->contents();
6151 for (size_t index = 0; index < contents.size(); ++index) {
6152 if (contents[index].name == content_name) {
6153 *sdp_mline_index = static_cast<int>(index);
6154 content_found = true;
6155 break;
6156 }
6157 }
6158 return content_found;
6159}
6160
6161bool PeerConnection::UseCandidatesInSessionDescription(
6162 const SessionDescriptionInterface* remote_desc) {
6163 if (!remote_desc) {
6164 return true;
6165 }
6166 bool ret = true;
6167
6168 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6169 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6170 for (size_t n = 0; n < candidates->count(); ++n) {
6171 const IceCandidateInterface* candidate = candidates->at(n);
6172 bool valid = false;
6173 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6174 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:256175 RTC_LOG(LS_INFO)
6176 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:076177 "candidate.";
Steve Anton75737c02017-11-06 18:37:176178 }
6179 continue;
6180 }
6181 ret = UseCandidate(candidate);
6182 if (!ret) {
6183 break;
6184 }
6185 }
6186 }
6187 return ret;
6188}
6189
6190bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6191 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6192 size_t remote_content_size =
6193 remote_description()->description()->contents().size();
6194 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:256195 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:176196 return false;
6197 }
6198
6199 cricket::ContentInfo content =
6200 remote_description()->description()->contents()[mediacontent_index];
6201 std::vector<cricket::Candidate> candidates;
6202 candidates.push_back(candidate->candidate());
6203 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:356204 RTCError error =
6205 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:506206 if (error.ok()) {
6207 // Candidates successfully submitted for checking.
6208 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6209 ice_connection_state_ ==
6210 PeerConnectionInterface::kIceConnectionDisconnected) {
6211 // If state is New, then the session has just gotten its first remote ICE
6212 // candidates, so go to Checking.
6213 // If state is Disconnected, the session is re-using old candidates or
6214 // receiving additional ones, so go to Checking.
6215 // If state is Connected, stay Connected.
6216 // TODO(bemasc): If state is Connected, and the new candidates are for a
6217 // newly added transport, then the state actually _should_ move to
6218 // checking. Add a way to distinguish that case.
6219 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6220 }
6221 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:076222 } else {
Zhi Huange830e682018-03-30 17:48:356223 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:176224 }
6225 return true;
6226}
6227
6228void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:176229 // Destroy video channel first since it may have a pointer to the
6230 // voice channel.
6231 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:296232 if (!video_info || video_info->rejected) {
6233 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:176234 }
6235
Steve Anton6fec8802017-12-04 18:37:296236 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6237 if (!audio_info || audio_info->rejected) {
6238 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:176239 }
6240
6241 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6242 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:296243 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:176244 }
6245}
6246
Steve Antondcc3c022017-12-23 00:02:546247RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6248 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:176249 const cricket::ContentGroup* bundle_group = nullptr;
6250 if (configuration_.bundle_policy ==
6251 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:546252 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:176253 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:566254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6255 "max-bundle configured but session description "
6256 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:176257 }
6258 }
Mirko Bonadei9f3a44f2019-01-30 12:47:426259 return bundle_group;
Steve Antondcc3c022017-12-23 00:02:546260}
6261
6262RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:356263 // Creating the media channels. Transports should already have been created
6264 // at this point.
Steve Antondcc3c022017-12-23 00:02:546265 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:556266 if (voice && !voice->rejected &&
6267 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:356268 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:556269 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:566270 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6271 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:556272 }
6273 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6274 }
6275
Steve Antondcc3c022017-12-23 00:02:546276 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:556277 if (video && !video->rejected &&
6278 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:356279 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:556280 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:566281 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6282 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:176283 }
Steve Antoneda6ccd2017-12-04 18:21:556284 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:176285 }
6286
Steve Antondcc3c022017-12-23 00:02:546287 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:176288 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 19:23:226289 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:356290 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:566291 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6292 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:176293 }
6294 }
6295
Steve Anton8a006912017-12-04 23:25:566296 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176297}
6298
Steve Anton4171afb2017-11-20 18:20:226299// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:556300cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:356301 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:426302 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 16:07:486303 MediaTransportInterface* media_transport = nullptr;
6304 if (configuration_.use_media_transport) {
6305 media_transport = GetMediaTransport(mid);
6306 }
Anton Sukhanov98a462c2018-10-17 20:15:426307
Steve Anton75737c02017-11-06 18:37:176308 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 08:57:016309 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 17:16:446310 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-26 01:13:566311 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 18:37:176312 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:556313 return nullptr;
Steve Anton75737c02017-11-06 18:37:176314 }
Steve Anton75737c02017-11-06 18:37:176315 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6316 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:176317 voice_channel->SignalSentPacket.connect(this,
6318 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:356319 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:226320
Steve Antoneda6ccd2017-12-04 18:21:556321 return voice_channel;
Steve Anton75737c02017-11-06 18:37:176322}
6323
Steve Anton4171afb2017-11-20 18:20:226324// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:556325cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:356326 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:426327 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 14:54:476328 MediaTransportInterface* media_transport = nullptr;
6329 if (configuration_.use_media_transport) {
6330 media_transport = GetMediaTransport(mid);
6331 }
Anton Sukhanov98a462c2018-10-17 20:15:426332
Steve Anton75737c02017-11-06 18:37:176333 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 08:57:016334 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 17:16:446335 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Jonas Orelanda3aa9bd2019-04-17 05:38:406336 &ssrc_generator_, video_options_, video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 18:37:176337 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:556338 return nullptr;
Steve Anton75737c02017-11-06 18:37:176339 }
Steve Anton75737c02017-11-06 18:37:176340 video_channel->SignalDtlsSrtpSetupFailure.connect(
6341 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:176342 video_channel->SignalSentPacket.connect(this,
6343 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:356344 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:226345
Steve Antoneda6ccd2017-12-04 18:21:556346 return video_channel;
Steve Anton75737c02017-11-06 18:37:176347}
6348
Zhi Huange830e682018-03-30 17:48:356349bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 19:23:226350 switch (data_channel_type_) {
6351 case cricket::DCT_MEDIA_TRANSPORT:
6352 if (network_thread()->Invoke<bool>(
6353 RTC_FROM_HERE,
6354 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6355 this, mid))) {
6356 for (const auto& channel : sctp_data_channels_) {
6357 channel->OnTransportChannelCreated();
6358 }
6359 return true;
6360 }
Steve Anton75737c02017-11-06 18:37:176361 return false;
Bjorn Mellem175aa2e2018-11-08 19:23:226362 case cricket::DCT_SCTP:
6363 if (!sctp_factory_) {
6364 RTC_LOG(LS_ERROR)
6365 << "Trying to create SCTP transport, but didn't compile with "
6366 "SCTP support (HAVE_SCTP)";
6367 return false;
6368 }
6369 if (!network_thread()->Invoke<bool>(
6370 RTC_FROM_HERE,
6371 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6372 return false;
6373 }
6374 for (const auto& channel : sctp_data_channels_) {
6375 channel->OnTransportChannelCreated();
6376 }
6377 return true;
6378 case cricket::DCT_RTP:
6379 default:
6380 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6381 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6382 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-26 01:13:566383 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 19:23:226384 if (!rtp_data_channel_) {
6385 return false;
6386 }
6387 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6388 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6389 rtp_data_channel_->SignalSentPacket.connect(
6390 this, &PeerConnection::OnSentPacket_w);
6391 rtp_data_channel_->SetRtpTransport(rtp_transport);
6392 return true;
Steve Anton75737c02017-11-06 18:37:176393 }
6394
Steve Anton75737c02017-11-06 18:37:176395 return true;
6396}
6397
6398Call::Stats PeerConnection::GetCallStats() {
6399 if (!worker_thread()->IsCurrent()) {
6400 return worker_thread()->Invoke<Call::Stats>(
6401 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6402 }
Karl Wiberg6cab5c82019-03-26 08:57:016403 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:176404 if (call_) {
6405 return call_->GetStats();
6406 } else {
6407 return Call::Stats();
6408 }
6409}
6410
Zhi Huange830e682018-03-30 17:48:356411bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:566412 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 18:37:176413 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 06:51:006414 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6415 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-03 02:16:266416 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 06:51:006417 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-03 02:16:266418 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 06:51:006419 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6420 sctp_factory_->CreateSctpTransport(dtls_transport);
6421 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 18:37:176422 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 06:51:006423 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 18:37:176424 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 06:51:006425 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 18:37:176426 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:326427 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6428 // another thread. Would be nice if there was a helper class similar to
6429 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6430 // code.
Harald Alvestrandc85328f2019-02-28 06:51:006431 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 20:23:326432 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 06:51:006433 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 20:23:326434 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:356435 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 06:51:006436 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6437 std::move(cricket_sctp_transport));
6438 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 17:48:356439 return true;
Steve Anton75737c02017-11-06 18:37:176440}
6441
6442void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 11:00:466443 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 06:51:006444 sctp_transport_->Clear();
6445 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 17:48:356446 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:176447 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 18:37:176448}
6449
6450void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 11:00:466451 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 18:37:176452 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 18:37:176453 // Note: Cannot use rtc::Bind here because it will grab a reference to
6454 // PeerConnection and potentially cause PeerConnection to live longer than
6455 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6456 // be destroyed before PeerConnection is destroyed, and at that point all
6457 // pending tasks will be cleared.
6458 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6459 OnSctpTransportReadyToSendData_s(true);
6460 });
6461}
6462
6463void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 09:31:566464 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176465 sctp_ready_to_send_data_ = ready;
6466 SignalSctpReadyToSendData(ready);
6467}
6468
6469void PeerConnection::OnSctpTransportDataReceived_n(
6470 const cricket::ReceiveDataParams& params,
6471 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 11:00:466472 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 18:37:176473 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 18:37:176474 // Note: Cannot use rtc::Bind here because it will grab a reference to
6475 // PeerConnection and potentially cause PeerConnection to live longer than
6476 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6477 // be destroyed before PeerConnection is destroyed, and at that point all
6478 // pending tasks will be cleared.
6479 sctp_invoker_->AsyncInvoke<void>(
6480 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6481 OnSctpTransportDataReceived_s(params, payload);
6482 });
6483}
6484
6485void PeerConnection::OnSctpTransportDataReceived_s(
6486 const cricket::ReceiveDataParams& params,
6487 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 19:23:226488 RTC_DCHECK_RUN_ON(signaling_thread());
6489 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 18:37:176490 SignalSctpDataReceived(params, payload);
6491 }
6492}
6493
Taylor Brandstettercdd05f02018-05-31 20:23:326494void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 11:00:466495 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 18:37:176496 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 18:37:176497 sctp_invoker_->AsyncInvoke<void>(
6498 RTC_FROM_HERE, signaling_thread(),
6499 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:326500 &SignalSctpClosingProcedureStartedRemotely, sid));
6501}
6502
6503void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 11:00:466504 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 20:23:326505 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 20:23:326506 sctp_invoker_->AsyncInvoke<void>(
6507 RTC_FROM_HERE, signaling_thread(),
6508 rtc::Bind(&sigslot::signal1<int>::operator(),
6509 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:176510}
6511
Bjorn Mellem175aa2e2018-11-08 19:23:226512bool PeerConnection::SetupMediaTransportForDataChannels_n(
6513 const std::string& mid) {
6514 media_transport_ = transport_controller_->GetMediaTransport(mid);
6515 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:056516 RTC_LOG(LS_ERROR)
6517 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 19:23:226518 return false;
6519 }
6520
6521 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6522 media_transport_->SetDataSink(this);
6523 media_transport_data_mid_ = mid;
6524 transport_controller_->SignalMediaTransportStateChanged.connect(
6525 this, &PeerConnection::OnMediaTransportStateChanged_n);
6526 // Check the initial state right away, in case transport is already writable.
6527 OnMediaTransportStateChanged_n();
6528 return true;
6529}
6530
6531void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6532 if (!media_transport_) {
6533 return;
6534 }
6535 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6536 media_transport_data_mid_.reset();
6537 media_transport_->SetDataSink(nullptr);
6538 media_transport_invoker_ = nullptr;
6539 media_transport_ = nullptr;
6540}
6541
6542void PeerConnection::OnMediaTransportStateChanged_n() {
6543 if (!media_transport_data_mid_ ||
6544 transport_controller_->GetMediaTransportState(
6545 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6546 return;
6547 }
6548 media_transport_invoker_->AsyncInvoke<void>(
6549 RTC_FROM_HERE, signaling_thread(), [this] {
6550 RTC_DCHECK_RUN_ON(signaling_thread());
6551 media_transport_ready_to_send_data_ = true;
6552 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6553 });
6554}
6555
Steve Anton75737c02017-11-06 18:37:176556// Returns false if bundle is enabled and rtcp_mux is disabled.
6557bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6558 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6559 if (!bundle_enabled)
6560 return true;
6561
6562 const cricket::ContentGroup* bundle_group =
6563 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6564 RTC_DCHECK(bundle_group != NULL);
6565
6566 const cricket::ContentInfos& contents = desc->contents();
6567 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6568 citer != contents.end(); ++citer) {
6569 const cricket::ContentInfo* content = (&*citer);
6570 RTC_DCHECK(content != NULL);
6571 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:006572 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:176573 if (!HasRtcpMuxEnabled(content))
6574 return false;
6575 }
6576 }
6577 // RTCP-MUX is enabled in all the contents.
6578 return true;
6579}
6580
6581bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:306582 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:176583}
6584
Steve Anton06817cd2018-12-18 23:55:306585static RTCError ValidateMids(const cricket::SessionDescription& description) {
6586 std::set<std::string> mids;
6587 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 19:32:206588 if (content.name.empty()) {
6589 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6590 "A media section is missing a MID attribute.");
6591 }
Steve Anton06817cd2018-12-18 23:55:306592 if (!mids.insert(content.name).second) {
6593 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6594 "Duplicate a=mid value '" + content.name + "'.");
6595 }
6596 }
6597 return RTCError::OK();
6598}
6599
Steve Anton8a006912017-12-04 23:25:566600RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:176601 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:566602 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:216603 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:566604 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:176605 }
6606
6607 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:566608 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:176609 }
6610
Steve Anton3828c062017-12-06 18:34:516611 SdpType type = sdesc->GetType();
6612 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6613 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:566614 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:036615 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:566616 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:176617 }
6618
Steve Anton06817cd2018-12-18 23:55:306619 RTCError error = ValidateMids(*sdesc->description());
6620 if (!error.ok()) {
6621 return error;
6622 }
6623
Steve Anton75737c02017-11-06 18:37:176624 // Verify crypto settings.
6625 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:566626 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6627 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:536628 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:566629 if (!crypto_error.ok()) {
6630 return crypto_error;
6631 }
Steve Anton75737c02017-11-06 18:37:176632 }
6633
6634 // Verify ice-ufrag and ice-pwd.
6635 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566636 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6637 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:176638 }
6639
6640 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566641 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6642 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:176643 }
6644
6645 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6646 // m-lines that do not rtcp-mux enabled.
6647
6648 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:516649 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:486650 // With an answer we want to compare the new answer session description with
6651 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:176652 const cricket::SessionDescription* offer_desc =
6653 (source == cricket::CS_LOCAL) ? remote_description()->description()
6654 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:486655 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6656 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6657 type)) {
Steve Anton8a006912017-12-04 23:25:566658 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6659 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:176660 }
6661 } else {
Steve Anton75737c02017-11-06 18:37:176662 // The re-offers should respect the order of m= sections in current
6663 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:486664 // With a re-offer, either the current local or current remote descriptions
6665 // could be the most up to date, so we would like to check against both of
6666 // them if they exist. It could be the case that one of them has a 0 port
6667 // for a media section, but the other does not. This is important to check
6668 // against in the case that we are recycling an m= section.
6669 const cricket::SessionDescription* current_desc = nullptr;
6670 const cricket::SessionDescription* secondary_current_desc = nullptr;
6671 if (local_description()) {
6672 current_desc = local_description()->description();
6673 if (remote_description()) {
6674 secondary_current_desc = remote_description()->description();
6675 }
6676 } else if (remote_description()) {
6677 current_desc = remote_description()->description();
6678 }
Steve Anton75737c02017-11-06 18:37:176679 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:486680 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6681 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:566682 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6683 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:176684 }
6685 }
6686
Steve Antonba42e992018-04-09 21:10:016687 if (IsUnifiedPlan()) {
6688 // Ensure that each audio and video media section has at most one
6689 // "StreamParams". This will return an error if receiving a session
6690 // description from a "Plan B" endpoint which adds multiple tracks of the
6691 // same type. With Unified Plan, there can only be at most one track per
6692 // media section.
6693 for (const ContentInfo& content : sdesc->description()->contents()) {
6694 const MediaContentDescription& desc = *content.description;
6695 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6696 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6697 desc.streams().size() > 1u) {
6698 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6699 "Media section has more than one track specified "
6700 "with a=ssrc lines which is not supported with "
6701 "Unified Plan.");
6702 }
6703 }
6704 }
6705
Steve Anton8a006912017-12-04 23:25:566706 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176707}
6708
Steve Anton3828c062017-12-06 18:34:516709bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176710 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516711 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176712 return (state == PeerConnectionInterface::kStable) ||
6713 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:526714 } else {
Steve Anton3828c062017-12-06 18:34:516715 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176716 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6717 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6718 }
6719}
6720
Steve Anton3828c062017-12-06 18:34:516721bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176722 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516723 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176724 return (state == PeerConnectionInterface::kStable) ||
6725 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:526726 } else {
Steve Anton3828c062017-12-06 18:34:516727 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176728 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6729 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6730 }
6731}
6732
Steve Antonf8470812017-12-04 18:46:216733const char* PeerConnection::SessionErrorToString(SessionError error) const {
6734 switch (error) {
6735 case SessionError::kNone:
6736 return "ERROR_NONE";
6737 case SessionError::kContent:
6738 return "ERROR_CONTENT";
6739 case SessionError::kTransport:
6740 return "ERROR_TRANSPORT";
6741 }
6742 RTC_NOTREACHED();
6743 return "";
6744}
6745
Steve Anton75737c02017-11-06 18:37:176746std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:306747 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:216748 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6749 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:326750 return desc.Release();
Steve Anton75737c02017-11-06 18:37:176751}
6752
Steve Anton8e20f172018-03-06 18:55:046753void PeerConnection::ReportSdpFormatReceived(
6754 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:046755 int num_audio_mlines = 0;
6756 int num_video_mlines = 0;
6757 int num_audio_tracks = 0;
6758 int num_video_tracks = 0;
6759 for (const ContentInfo& content : remote_offer.description()->contents()) {
6760 cricket::MediaType media_type = content.media_description()->type();
6761 int num_tracks = std::max(
6762 1, static_cast<int>(content.media_description()->streams().size()));
6763 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6764 num_audio_mlines += 1;
6765 num_audio_tracks += num_tracks;
6766 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6767 num_video_mlines += 1;
6768 num_video_tracks += num_tracks;
6769 }
6770 }
6771 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6772 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6773 format = kSdpFormatReceivedComplexUnifiedPlan;
6774 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6775 format = kSdpFormatReceivedComplexPlanB;
6776 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6777 format = kSdpFormatReceivedSimple;
6778 }
Qingsi Wang7fc821d2018-07-12 19:54:536779 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6780 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:046781}
6782
Harald Alvestrand8ebba742018-05-31 12:00:346783void PeerConnection::NoteUsageEvent(UsageEvent event) {
6784 RTC_DCHECK_RUN_ON(signaling_thread());
6785 usage_event_accumulator_ |= static_cast<int>(event);
6786}
6787
6788void PeerConnection::ReportUsagePattern() const {
6789 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:536790 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6791 usage_event_accumulator_,
6792 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:556793 const int bad_bits =
6794 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6795 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6796 const int good_bits =
6797 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6798 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6799 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6800 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6801 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:166802 // If called after close(), we can't report, because observer may have
6803 // been deallocated, and therefore pointer is null. Write to log instead.
6804 if (observer_) {
6805 Observer()->OnInterestingUsage(usage_event_accumulator_);
6806 } else {
6807 RTC_LOG(LS_INFO) << "Interesting usage signature "
6808 << usage_event_accumulator_
6809 << " observed after observer shutdown";
6810 }
Harald Alvestrandc0e97252018-07-26 08:39:556811 }
Harald Alvestrand8ebba742018-05-31 12:00:346812}
6813
Steve Anton0ffaaa22018-02-23 18:31:306814void PeerConnection::ReportNegotiatedSdpSemantics(
6815 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:536816 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:306817 switch (answer.description()->msid_signaling()) {
6818 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:536819 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:306820 break;
6821 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:536822 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:306823 break;
6824 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536825 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:306826 break;
6827 case cricket::kMsidSignalingMediaSection |
6828 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536829 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:306830 break;
6831 default:
6832 RTC_NOTREACHED();
6833 }
Qingsi Wang7fc821d2018-07-12 19:54:536834 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6835 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:306836}
6837
Steve Anton75737c02017-11-06 18:37:176838// We need to check the local/remote description for the Transport instead of
6839// the session, because a new Transport added during renegotiation may have
6840// them unset while the session has them set from the previous negotiation.
6841// Not doing so may trigger the auto generation of transport description and
6842// mess up DTLS identity information, ICE credential, etc.
6843bool PeerConnection::ReadyToUseRemoteCandidate(
6844 const IceCandidateInterface* candidate,
6845 const SessionDescriptionInterface* remote_desc,
6846 bool* valid) {
6847 *valid = true;
6848
6849 const SessionDescriptionInterface* current_remote_desc =
6850 remote_desc ? remote_desc : remote_description();
6851
6852 if (!current_remote_desc) {
6853 return false;
6854 }
6855
6856 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6857 size_t remote_content_size =
6858 current_remote_desc->description()->contents().size();
6859 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:256860 RTC_LOG(LS_ERROR)
6861 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6862 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176863
6864 *valid = false;
6865 return false;
6866 }
6867
6868 cricket::ContentInfo content =
6869 current_remote_desc->description()->contents()[mediacontent_index];
6870
6871 const std::string transport_name = GetTransportName(content.name);
6872 if (transport_name.empty()) {
6873 return false;
6874 }
Zhi Huange830e682018-03-30 17:48:356875 return true;
Steve Anton75737c02017-11-06 18:37:176876}
6877
6878bool PeerConnection::SrtpRequired() const {
6879 return dtls_enabled_ ||
6880 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6881}
6882
6883void PeerConnection::OnTransportControllerGatheringState(
6884 cricket::IceGatheringState state) {
6885 RTC_DCHECK(signaling_thread()->IsCurrent());
6886 if (state == cricket::kIceGatheringGathering) {
6887 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6888 } else if (state == cricket::kIceGatheringComplete) {
6889 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6890 }
6891}
6892
6893void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:456894 std::map<std::string, std::set<cricket::MediaType>>
6895 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 16:29:426896 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 22:39:456897 if (transceiver->internal()->channel()) {
6898 const std::string& transport_name =
6899 transceiver->internal()->channel()->transport_name();
6900 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086901 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456902 }
Steve Anton75737c02017-11-06 18:37:176903 }
6904 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456905 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6906 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176907 }
Zhi Huange830e682018-03-30 17:48:356908
Danil Chapovalov66cadcc2018-06-19 14:47:436909 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356910 if (transport_name) {
6911 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456912 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176913 }
Zhi Huange830e682018-03-30 17:48:356914
Steve Antonc7b964c2018-02-01 22:39:456915 for (const auto& entry : media_types_by_transport_name) {
6916 const std::string& transport_name = entry.first;
6917 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176918 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456919 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176920 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456921 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176922 }
6923 }
6924}
6925// Walk through the ConnectionInfos to gather best connection usage
6926// for IPv4 and IPv6.
6927void PeerConnection::ReportBestConnectionState(
6928 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:456929 for (const cricket::TransportChannelStats& channel_stats :
6930 stats.channel_stats) {
6931 for (const cricket::ConnectionInfo& connection_info :
6932 channel_stats.connection_infos) {
6933 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176934 continue;
6935 }
6936
Steve Antonc7b964c2018-02-01 22:39:456937 const cricket::Candidate& local = connection_info.local_candidate;
6938 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176939
6940 // Increment the counter for IceCandidatePairType.
6941 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6942 (local.type() == RELAY_PORT_TYPE &&
6943 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:536944 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6945 GetIceCandidatePairCounter(local, remote),
6946 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176947 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536948 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6949 GetIceCandidatePairCounter(local, remote),
6950 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176951 } else {
6952 RTC_CHECK(0);
6953 }
Steve Anton75737c02017-11-06 18:37:176954
6955 // Increment the counter for IP type.
6956 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536957 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6958 kBestConnections_IPv4,
6959 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176960 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536961 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6962 kBestConnections_IPv6,
6963 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176964 } else {
Qingsi Wang1dac6d82018-12-12 23:28:476965 RTC_CHECK(!local.address().hostname().empty() &&
6966 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 18:37:176967 }
6968
6969 return;
6970 }
6971 }
6972}
6973
6974void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456975 const cricket::TransportStats& stats,
6976 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176977 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6978 return;
6979 }
6980
6981 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6982 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6983 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6984 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6985 return;
6986 }
6987
Qingsi Wang7fc821d2018-07-12 19:54:536988 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6989 for (cricket::MediaType media_type : media_types) {
6990 switch (media_type) {
6991 case cricket::MEDIA_TYPE_AUDIO:
6992 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6993 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6994 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6995 break;
6996 case cricket::MEDIA_TYPE_VIDEO:
6997 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6998 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6999 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7000 break;
7001 case cricket::MEDIA_TYPE_DATA:
7002 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7003 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7004 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7005 break;
7006 default:
7007 RTC_NOTREACHED();
7008 continue;
7009 }
Steve Antonc7b964c2018-02-01 22:39:457010 }
Qingsi Wang7fc821d2018-07-12 19:54:537011 }
7012
7013 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7014 for (cricket::MediaType media_type : media_types) {
7015 switch (media_type) {
7016 case cricket::MEDIA_TYPE_AUDIO:
7017 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7018 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7019 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7020 break;
7021 case cricket::MEDIA_TYPE_VIDEO:
7022 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7023 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7024 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7025 break;
7026 case cricket::MEDIA_TYPE_DATA:
7027 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7028 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7029 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7030 break;
7031 default:
7032 RTC_NOTREACHED();
7033 continue;
7034 }
Steve Antonc7b964c2018-02-01 22:39:457035 }
Steve Anton75737c02017-11-06 18:37:177036 }
7037}
7038
7039void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 08:57:017040 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:177041 RTC_DCHECK(call_);
7042 call_->OnSentPacket(sent_packet);
7043}
7044
7045const std::string PeerConnection::GetTransportName(
7046 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-14 00:26:057047 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:297048 if (channel) {
7049 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:177050 }
Steve Anton6fec8802017-12-04 18:37:297051 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:357052 RTC_DCHECK(sctp_mid_);
7053 if (content_name == *sctp_mid_) {
7054 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:297055 }
7056 }
7057 // Return an empty string if failed to retrieve the transport name.
7058 return "";
Steve Anton75737c02017-11-06 18:37:177059}
7060
Steve Anton6fec8802017-12-04 18:37:297061void PeerConnection::DestroyTransceiverChannel(
7062 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7063 transceiver) {
7064 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:177065
Amit Hilbuchdd9390c2018-11-14 00:26:057066 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:297067 if (channel) {
7068 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:057069 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:177070 }
7071}
7072
7073void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:297074 if (rtp_data_channel_) {
7075 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-14 00:26:057076 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 18:37:297077 rtp_data_channel_ = nullptr;
7078 }
7079
7080 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7081 // grab a reference to this PeerConnection. If this is called from the
7082 // PeerConnection destructor, the RefCountedObject vtable will have already
7083 // been destroyed (since it is a subclass of PeerConnection) and using
7084 // rtc::Bind will cause "Pure virtual function called" error to appear.
7085
7086 if (sctp_transport_) {
7087 OnDataChannelDestroyed();
7088 network_thread()->Invoke<void>(RTC_FROM_HERE,
7089 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 09:31:567090 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 18:37:297091 }
Bjorn Mellem175aa2e2018-11-08 19:23:227092
7093 if (media_transport_) {
7094 OnDataChannelDestroyed();
7095 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7096 RTC_DCHECK_RUN_ON(network_thread());
7097 TeardownMediaTransportForDataChannels_n();
7098 });
7099 }
Steve Anton6fec8802017-12-04 18:37:297100}
7101
Amit Hilbuchdd9390c2018-11-14 00:26:057102void PeerConnection::DestroyChannelInterface(
7103 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:297104 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:297105 switch (channel->media_type()) {
7106 case cricket::MEDIA_TYPE_AUDIO:
7107 channel_manager()->DestroyVoiceChannel(
7108 static_cast<cricket::VoiceChannel*>(channel));
7109 break;
7110 case cricket::MEDIA_TYPE_VIDEO:
7111 channel_manager()->DestroyVideoChannel(
7112 static_cast<cricket::VideoChannel*>(channel));
7113 break;
7114 case cricket::MEDIA_TYPE_DATA:
7115 channel_manager()->DestroyRtpDataChannel(
7116 static_cast<cricket::RtpDataChannel*>(channel));
7117 break;
7118 default:
7119 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7120 break;
7121 }
Zhi Huange830e682018-03-30 17:48:357122}
Steve Anton6fec8802017-12-04 18:37:297123
Taylor Brandstettercbaa2542018-04-16 23:42:147124bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:357125 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:147126 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 06:51:007127 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:197128 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 12:08:377129 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 22:55:097130 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 23:42:147131 bool ret = true;
Zhi Huange830e682018-03-30 17:48:357132 auto base_channel = GetChannel(mid);
7133 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:147134 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:357135 }
Taylor Brandstettercbaa2542018-04-16 23:42:147136 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:267137 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:177138 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:197139
Karl Wiberg5966c502019-02-21 22:55:097140 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 21:31:157141 // Only pass media transport to call object if media transport is used
7142 // for media (and not data channel).
Karl Wibergac025892019-03-26 12:08:377143 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 21:31:157144 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:197145
Taylor Brandstettercbaa2542018-04-16 23:42:147146 return ret;
Steve Anton75737c02017-11-06 18:37:177147}
7148
Harald Alvestrand7a1c7f72018-08-01 08:50:167149PeerConnectionObserver* PeerConnection::Observer() const {
7150 // In earlier production code, the pointer was not cleared on close,
7151 // which might have led to undefined behavior if the observer was not
7152 // deallocated, or strange crashes if it was.
7153 // We use CHECK in order to catch such behavior if it exists.
7154 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7155 RTC_CHECK(observer_);
7156 return observer_;
7157}
7158
Benjamin Wright8c27cca2018-10-25 17:16:447159CryptoOptions PeerConnection::GetCryptoOptions() {
7160 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7161 // after it has been removed.
7162 return configuration_.crypto_options.has_value()
7163 ? *configuration_.crypto_options
7164 : factory_->options().crypto_options;
7165}
7166
Harald Alvestrand89061872018-01-02 13:08:347167void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 08:57:017168 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 13:08:347169 if (stats_collector_) {
7170 stats_collector_->ClearCachedStatsReport();
7171 }
7172}
7173
Harald Alvestrand7a1c7f72018-08-01 08:50:167174void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:407175 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7176 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:167177}
7178
Guido Urdaneta70c2db12019-04-16 10:24:147179void PeerConnection::UpdateNegotiationNeeded() {
7180 RTC_DCHECK_RUN_ON(signaling_thread());
7181 if (!IsUnifiedPlan()) {
7182 Observer()->OnRenegotiationNeeded();
7183 return;
7184 }
7185
7186 // If connection's [[IsClosed]] slot is true, abort these steps.
7187 if (IsClosed())
7188 return;
7189
7190 // If connection's signaling state is not "stable", abort these steps.
7191 if (signaling_state() != kStable)
7192 return;
7193
7194 // NOTE
7195 // The negotiation-needed flag will be updated once the state transitions to
7196 // "stable", as part of the steps for setting an RTCSessionDescription.
7197
7198 // If the result of checking if negotiation is needed is false, clear the
7199 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7200 // to false, and abort these steps.
7201 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7202 if (!is_negotiation_needed) {
7203 is_negotiation_needed_ = false;
7204 return;
7205 }
7206
7207 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7208 // steps.
7209 if (is_negotiation_needed_)
7210 return;
7211
7212 // Set connection's [[NegotiationNeeded]] slot to true.
7213 is_negotiation_needed_ = true;
7214
7215 // Queue a task that runs the following steps:
7216 // If connection's [[IsClosed]] slot is true, abort these steps.
7217 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7218 // Fire an event named negotiationneeded at connection.
7219 Observer()->OnRenegotiationNeeded();
7220}
7221
7222bool PeerConnection::CheckIfNegotiationIsNeeded() {
7223 RTC_DCHECK_RUN_ON(signaling_thread());
7224 // 1. If any implementation-specific negotiation is required, as described at
7225 // the start of this section, return true.
7226
7227 // 2. Let description be connection.[[CurrentLocalDescription]].
7228 const SessionDescriptionInterface* description = current_local_description();
7229 if (!description)
7230 return true;
7231
7232 // 3. If connection has created any RTCDataChannels, and no m= section in
7233 // description has been negotiated yet for data, return true.
7234 if (!sctp_data_channels_.empty()) {
7235 if (!cricket::GetFirstDataContent(description->description()->contents()))
7236 return true;
7237 }
7238
7239 // 4. For each transceiver in connection's set of transceivers, perform the
7240 // following checks:
7241 for (const auto& transceiver : transceivers_) {
7242 const ContentInfo* current_local_msection =
7243 FindTransceiverMSection(transceiver.get(), description);
7244
7245 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7246 transceiver.get(), current_remote_description());
7247
7248 // 4.3 If transceiver is stopped and is associated with an m= section,
7249 // but the associated m= section is not yet rejected in
7250 // connection.[[CurrentLocalDescription]] or
7251 // connection.[[CurrentRemoteDescription]], return true.
7252 if (transceiver->stopped()) {
7253 if (current_local_msection && !current_local_msection->rejected &&
7254 ((current_remote_msection && !current_remote_msection->rejected) ||
7255 !current_remote_msection)) {
7256 return true;
7257 }
7258 continue;
7259 }
7260
7261 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7262 // section in description, return true.
7263 if (!current_local_msection)
7264 return true;
7265
7266 const MediaContentDescription* current_local_media_description =
7267 current_local_msection->media_description();
7268 // 4.2 If transceiver isn't stopped and is associated with an m= section
7269 // in description then perform the following checks:
7270
7271 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7272 // associated m= section in description either doesn't contain a single
7273 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7274 // m= section, or the MSID values themselves, differ from what is in
7275 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7276 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7277 if (current_local_media_description->streams().size() == 0)
7278 return true;
7279
7280 std::vector<std::string> msection_msids;
7281 for (const auto& stream : current_local_media_description->streams()) {
7282 for (const std::string& msid : stream.stream_ids())
7283 msection_msids.push_back(msid);
7284 }
7285
7286 std::vector<std::string> transceiver_msids =
7287 transceiver->sender()->stream_ids();
7288 if (msection_msids.size() != transceiver_msids.size())
7289 return true;
7290
7291 absl::c_sort(transceiver_msids);
7292 absl::c_sort(msection_msids);
7293 if (transceiver_msids != msection_msids)
7294 return true;
7295 }
7296
7297 // 4.2.2 If description is of type "offer", and the direction of the
7298 // associated m= section in neither connection.[[CurrentLocalDescription]]
7299 // nor connection.[[CurrentRemoteDescription]] matches
7300 // transceiver.[[Direction]], return true.
7301 if (description->GetType() == SdpType::kOffer) {
7302 if (!current_remote_description())
7303 return true;
7304
7305 if (!current_remote_msection)
7306 return true;
7307
7308 RtpTransceiverDirection current_local_direction =
7309 current_local_media_description->direction();
7310 RtpTransceiverDirection current_remote_direction =
7311 current_remote_msection->media_description()->direction();
7312 if (transceiver->direction() != current_local_direction &&
7313 transceiver->direction() !=
7314 RtpTransceiverDirectionReversed(current_remote_direction)) {
7315 return true;
7316 }
7317 }
7318
7319 // 4.2.3 If description is of type "answer", and the direction of the
7320 // associated m= section in the description does not match
7321 // transceiver.[[Direction]] intersected with the offered direction (as
7322 // described in [JSEP] (section 5.3.1.)), return true.
7323 if (description->GetType() == SdpType::kAnswer) {
7324 if (!remote_description())
7325 return true;
7326
7327 const ContentInfo* offered_remote_msection =
7328 FindTransceiverMSection(transceiver.get(), remote_description());
7329
7330 RtpTransceiverDirection offered_direction =
7331 offered_remote_msection
7332 ? offered_remote_msection->media_description()->direction()
7333 : RtpTransceiverDirection::kInactive;
7334
7335 if (current_local_media_description->direction() !=
7336 (RtpTransceiverDirectionIntersection(
7337 transceiver->direction(),
7338 RtpTransceiverDirectionReversed(offered_direction)))) {
7339 return true;
7340 }
7341 }
7342 }
7343
7344 // If all the preceding checks were performed and true was not returned,
7345 // nothing remains to be negotiated; return false.
7346 return false;
7347}
7348
henrike@webrtc.org28e20752013-07-10 00:45:367349} // namespace webrtc