blob: 059d5dd9e053fb71558821b6ce6323162c274eee [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:369 */
10
Steve Anton10542f22019-01-11 17:11:0011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Harald Alvestrand8ebba742018-05-31 12:00:3414#include <limits>
Mirko Bonadei317a1f02019-09-17 15:06:1815#include <memory>
Steve Antondcc3c022017-12-23 00:02:5416#include <queue>
Steve Anton75737c02017-11-06 18:37:1717#include <set>
kwiberg0eb15ed2015-12-17 11:04:1518#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3620
Steve Anton64b626b2019-01-29 01:25:2621#include "absl/algorithm/container.h"
Fredrik Solenberg41f3a432018-12-17 20:02:2222#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 17:11:0023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 21:11:5727#include "api/rtc_error.h"
Danil Chapovalov83bbe912019-08-07 10:24:5328#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 11:53:5129#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 21:11:5730#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 17:11:0031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 05:38:4032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3133#include "call/call.h"
Steve Anton10542f22019-01-11 17:11:0034#include "logging/rtc_event_log/ice_logger.h"
Amit Hilbuchf4770402019-04-08 21:11:5735#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 17:11:0036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 09:29:1937#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 17:11:0038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 18:37:1739#include "pc/channel.h"
Steve Anton10542f22019-01-11 17:11:0040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 06:51:0048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 17:11:0049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 09:29:1952#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 17:11:0053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3154#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 11:41:3058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3159#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 19:54:5362#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3663
Steve Anton75737c02017-11-06 18:37:1764using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-21 00:34:0067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-26 01:13:5668using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 18:13:5870using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-26 01:13:5671using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 18:13:5873using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-26 01:13:5674using cricket::StreamParams;
Steve Anton75737c02017-11-06 18:37:1775using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 18:37:1778using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 20:13:4879using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 18:37:1781
Steve Antonba818672017-11-06 18:21:5782namespace webrtc {
83
Steve Anton75737c02017-11-06 18:37:1784// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1788const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1796const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36107
Steve Anton75737c02017-11-06 18:37:17108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36109
Bjorn A Mellem5985a042019-06-28 21:19:38110// Field trials.
111// Controls datagram transport support.
112const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
Bjorn A Mellemb689af42019-08-21 17:44:59113// Controls datagram transport data channel support.
114const char kDatagramTransportDataChannelFieldTrial[] =
115 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 21:19:38116
Amit Hilbuche2a284d2019-03-05 20:36:31117// UMA metric names.
118const char kSimulcastVersionApplyLocalDescription[] =
119 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
120const char kSimulcastVersionApplyRemoteDescription[] =
121 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
122const char kSimulcastNumberOfEncodings[] =
123 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
124const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
125
Seth Hampson845e8782018-03-02 19:34:10126static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:22127static const char kDefaultAudioSenderId[] = "defaulta0";
128static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11129
zhihuang8f65cdf2016-05-07 01:40:30130// The length of RTCP CNAMEs.
131static const int kRtcpCnameLength = 16;
132
Steve Antonad182762018-09-05 20:22:40133enum {
134 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
135 MSG_SET_SESSIONDESCRIPTION_FAILED,
136 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
137 MSG_GETSTATS,
Steve Antonad182762018-09-05 20:22:40138 MSG_REPORT_USAGE_PATTERN,
139};
140
Harald Alvestrand19793842018-06-25 10:03:50141static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
142
Steve Antonad182762018-09-05 20:22:40143struct SetSessionDescriptionMsg : public rtc::MessageData {
144 explicit SetSessionDescriptionMsg(
145 webrtc::SetSessionDescriptionObserver* observer)
146 : observer(observer) {}
147
148 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
149 RTCError error;
150};
151
152struct CreateSessionDescriptionMsg : public rtc::MessageData {
153 explicit CreateSessionDescriptionMsg(
154 webrtc::CreateSessionDescriptionObserver* observer)
155 : observer(observer) {}
156
157 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
158 RTCError error;
159};
160
161struct GetStatsMsg : public rtc::MessageData {
162 GetStatsMsg(webrtc::StatsObserver* observer,
163 webrtc::MediaStreamTrackInterface* track)
164 : observer(observer), track(track) {}
165 rtc::scoped_refptr<webrtc::StatsObserver> observer;
166 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
167};
168
deadbeefab9b2d12015-10-14 18:33:11169// Check if we can send |new_stream| on a PeerConnection.
170bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
171 webrtc::MediaStreamInterface* new_stream) {
172 if (!new_stream || !current_streams) {
173 return false;
174 }
Seth Hampson13b8bad2018-03-13 23:05:28175 if (current_streams->find(new_stream->id()) != nullptr) {
176 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25177 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11178 return false;
179 }
180 return true;
181}
182
deadbeef5e97fb52015-10-15 19:49:08183// If the direction is "recvonly" or "inactive", treat the description
184// as containing no streams.
185// See: https://code.google.com/p/webrtc/issues/detail?id=5054
186std::vector<cricket::StreamParams> GetActiveStreams(
187 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10188 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08189 ? desc->streams()
190 : std::vector<cricket::StreamParams>();
191}
192
deadbeefab9b2d12015-10-14 18:33:11193bool IsValidOfferToReceiveMedia(int value) {
194 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
195 return (value >= Options::kUndefined) &&
196 (value <= Options::kMaxOfferToReceiveMedia);
197}
198
zhihuang1c378ed2017-08-17 21:10:50199// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 18:13:58200void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39201 const std::vector<rtc::scoped_refptr<
202 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50203 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37204 cricket::MediaDescriptionOptions* video_media_description_options,
205 int num_sim_layers) {
olka3c747662017-08-17 13:50:32206 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50207 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
208 if (audio_media_description_options) {
209 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38210 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50211 }
212 } else {
213 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
214 if (video_media_description_options) {
215 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 18:13:58216 sender->id(), sender->internal()->stream_ids(), {},
217 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50218 }
219 }
zhihuanga77e6bb2017-08-15 01:17:48220 }
zhihuang1c378ed2017-08-17 21:10:50221}
olka3c747662017-08-17 13:50:32222
zhihuang1c378ed2017-08-17 21:10:50223// Add options to |session_options| from |rtp_data_channels|.
224void AddRtpDataChannelOptions(
225 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
226 rtp_data_channels,
227 cricket::MediaDescriptionOptions* data_media_description_options) {
228 if (!data_media_description_options) {
229 return;
230 }
deadbeefab9b2d12015-10-14 18:33:11231 // Check for data channels.
232 for (const auto& kv : rtp_data_channels) {
233 const DataChannel* channel = kv.second;
234 if (channel->state() == DataChannel::kConnecting ||
235 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50236 // Legacy RTP data channels are signaled with the track/stream ID set to
237 // the data channel's label.
238 data_media_description_options->AddRtpDataChannel(channel->label(),
239 channel->label());
deadbeefab9b2d12015-10-14 18:33:11240 }
241 }
242}
243
Taylor Brandstettera1c30352016-05-13 15:15:11244uint32_t ConvertIceTransportTypeToCandidateFilter(
245 PeerConnectionInterface::IceTransportsType type) {
246 switch (type) {
247 case PeerConnectionInterface::kNone:
248 return cricket::CF_NONE;
249 case PeerConnectionInterface::kRelay:
250 return cricket::CF_RELAY;
251 case PeerConnectionInterface::kNoHost:
252 return (cricket::CF_ALL & ~cricket::CF_HOST);
253 case PeerConnectionInterface::kAll:
254 return cricket::CF_ALL;
255 default:
nissec80e7412017-01-11 13:56:46256 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11257 }
258 return cricket::CF_NONE;
259}
260
Steve Antonba818672017-11-06 18:21:57261std::string GetSignalingStateString(
262 PeerConnectionInterface::SignalingState state) {
263 switch (state) {
264 case PeerConnectionInterface::kStable:
265 return "kStable";
266 case PeerConnectionInterface::kHaveLocalOffer:
267 return "kHaveLocalOffer";
268 case PeerConnectionInterface::kHaveLocalPrAnswer:
269 return "kHavePrAnswer";
270 case PeerConnectionInterface::kHaveRemoteOffer:
271 return "kHaveRemoteOffer";
272 case PeerConnectionInterface::kHaveRemotePrAnswer:
273 return "kHaveRemotePrAnswer";
274 case PeerConnectionInterface::kClosed:
275 return "kClosed";
276 }
277 RTC_NOTREACHED();
278 return "";
279}
deadbeef0a6c4ca2015-10-06 18:38:28280
Steve Anton75737c02017-11-06 18:37:17281IceCandidatePairType GetIceCandidatePairCounter(
282 const cricket::Candidate& local,
283 const cricket::Candidate& remote) {
284 const auto& l = local.type();
285 const auto& r = remote.type();
286 const auto& host = LOCAL_PORT_TYPE;
287 const auto& srflx = STUN_PORT_TYPE;
288 const auto& relay = RELAY_PORT_TYPE;
289 const auto& prflx = PRFLX_PORT_TYPE;
290 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 16:25:54291 bool local_hostname =
292 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
293 bool remote_hostname = !remote.address().hostname().empty() &&
294 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 18:37:17295 bool local_private = IPIsPrivate(local.address().ipaddr());
296 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 16:25:54297 if (local_hostname) {
298 if (remote_hostname) {
299 return kIceCandidatePairHostNameHostName;
300 } else if (remote_private) {
301 return kIceCandidatePairHostNameHostPrivate;
302 } else {
303 return kIceCandidatePairHostNameHostPublic;
304 }
305 } else if (local_private) {
306 if (remote_hostname) {
307 return kIceCandidatePairHostPrivateHostName;
308 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17309 return kIceCandidatePairHostPrivateHostPrivate;
310 } else {
311 return kIceCandidatePairHostPrivateHostPublic;
312 }
313 } else {
Jeroen de Borst833979f2018-12-13 16:25:54314 if (remote_hostname) {
315 return kIceCandidatePairHostPublicHostName;
316 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17317 return kIceCandidatePairHostPublicHostPrivate;
318 } else {
319 return kIceCandidatePairHostPublicHostPublic;
320 }
321 }
322 }
323 if (l == host && r == srflx)
324 return kIceCandidatePairHostSrflx;
325 if (l == host && r == relay)
326 return kIceCandidatePairHostRelay;
327 if (l == host && r == prflx)
328 return kIceCandidatePairHostPrflx;
329 if (l == srflx && r == host)
330 return kIceCandidatePairSrflxHost;
331 if (l == srflx && r == srflx)
332 return kIceCandidatePairSrflxSrflx;
333 if (l == srflx && r == relay)
334 return kIceCandidatePairSrflxRelay;
335 if (l == srflx && r == prflx)
336 return kIceCandidatePairSrflxPrflx;
337 if (l == relay && r == host)
338 return kIceCandidatePairRelayHost;
339 if (l == relay && r == srflx)
340 return kIceCandidatePairRelaySrflx;
341 if (l == relay && r == relay)
342 return kIceCandidatePairRelayRelay;
343 if (l == relay && r == prflx)
344 return kIceCandidatePairRelayPrflx;
345 if (l == prflx && r == host)
346 return kIceCandidatePairPrflxHost;
347 if (l == prflx && r == srflx)
348 return kIceCandidatePairPrflxSrflx;
349 if (l == prflx && r == relay)
350 return kIceCandidatePairPrflxRelay;
351 return kIceCandidatePairMax;
352}
353
Seth Hampsonae8a90a2018-02-13 23:33:48354// Logic to decide if an m= section can be recycled. This means that the new
355// m= section is not rejected, but the old local or remote m= section is
356// rejected. |old_content_one| and |old_content_two| refer to the m= section
357// of the old remote and old local descriptions in no particular order.
358// We need to check both the old local and remote because either
359// could be the most current from the latest negotation.
360bool IsMediaSectionBeingRecycled(SdpType type,
361 const ContentInfo& content,
362 const ContentInfo* old_content_one,
363 const ContentInfo* old_content_two) {
364 return type == SdpType::kOffer && !content.rejected &&
365 ((old_content_one && old_content_one->rejected) ||
366 (old_content_two && old_content_two->rejected));
367}
368
Steve Anton75737c02017-11-06 18:37:17369// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48370// |current_desc|. The number of m= sections in |new_desc| should be no
371// less than |current_desc|. In the case of checking an answer's
372// |new_desc|, the |current_desc| is the last offer that was set as the
373// local or remote. In the case of checking an offer's |new_desc| we
374// check against the local and remote descriptions stored from the last
375// negotiation, because either of these could be the most up to date for
376// possible rejected m sections. These are the |current_desc| and
377// |secondary_current_desc|.
378bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
379 const SessionDescription* secondary_current_desc,
380 const SessionDescription& new_desc,
381 const SdpType type) {
382 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 18:37:17383 return false;
384 }
385
Seth Hampsonae8a90a2018-02-13 23:33:48386 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
387 const cricket::ContentInfo* secondary_content_info = nullptr;
388 if (secondary_current_desc &&
389 i < secondary_current_desc->contents().size()) {
390 secondary_content_info = &secondary_current_desc->contents()[i];
391 }
392 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
393 &current_desc.contents()[i],
394 secondary_content_info)) {
395 // For new offer descriptions, if the media section can be recycled, it's
396 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-23 00:02:54397 continue;
398 }
Seth Hampsonae8a90a2018-02-13 23:33:48399 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17400 return false;
401 }
402 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48403 new_desc.contents()[i].media_description();
404 const MediaContentDescription* current_desc_mdesc =
405 current_desc.contents()[i].media_description();
406 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 18:37:17407 return false;
408 }
409 }
410 return true;
411}
412
Seth Hampsonae8a90a2018-02-13 23:33:48413bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
414 const SessionDescription& desc2) {
415 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17416}
417
Qingsi Wang7fc821d2018-07-12 19:54:53418void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
419 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20420 // Array of structs needed to map {KeyExchangeProtocolType,
421 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
422 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
423 static constexpr struct {
424 KeyExchangeProtocolType protocol_type;
425 cricket::MediaType media_type;
426 KeyExchangeProtocolMedia protocol_media;
427 } kEnumCounterKeyProtocolMediaMap[] = {
428 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
429 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
431 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
433 kEnumCounterKeyProtocolMediaTypeDtlsData},
434 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
435 kEnumCounterKeyProtocolMediaTypeSdesAudio},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
437 kEnumCounterKeyProtocolMediaTypeSdesVideo},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
439 kEnumCounterKeyProtocolMediaTypeSdesData},
440 };
441
Qingsi Wang7fc821d2018-07-12 19:54:53442 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
443 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26444
Mirko Bonadeiab499822018-09-11 08:43:20445 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
446 if (i.protocol_type == protocol_type && i.media_type == media_type) {
447 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
448 i.protocol_media,
449 kEnumCounterKeyProtocolMediaTypeMax);
450 }
Harald Alvestrandf9d0f1d2018-03-02 13:15:26451 }
452}
453
Harald Alvestrand76829d72018-07-18 21:24:36454void NoteAddIceCandidateResult(int result) {
455 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
456 kAddIceCandidateMax);
457}
458
Steve Anton75737c02017-11-06 18:37:17459// Checks that each non-rejected content has SDES crypto keys or a DTLS
460// fingerprint, unless it's in a BUNDLE group, in which case only the
461// BUNDLE-tag section (first media section/description in the BUNDLE group)
462// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
463// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
464// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 19:54:53465RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17466 const cricket::ContentGroup* bundle =
467 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56468 for (const cricket::ContentInfo& content_info : desc->contents()) {
469 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17470 continue;
471 }
Harald Alvestrand2e180612018-03-07 09:56:14472 // Note what media is used with each crypto protocol, for all sections.
473 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
474 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 19:54:53475 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56476 const std::string& mid = content_info.name;
477 if (bundle && bundle->HasContentName(mid) &&
478 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17479 // This isn't the first media section in the BUNDLE group, so it's not
480 // required to have crypto attributes, since only the crypto attributes
481 // from the first section actually get used.
482 continue;
483 }
484
485 // If the content isn't rejected or bundled into another m= section, crypto
486 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30487 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56488 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17489 if (!media || !tinfo) {
490 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17492 }
493 if (dtls_enabled) {
494 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25495 RTC_LOG(LS_WARNING)
496 << "Session description must have DTLS fingerprint if "
497 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56498 return RTCError(RTCErrorType::INVALID_PARAMETER,
499 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17500 }
501 } else {
502 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25503 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17504 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56505 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17506 }
507 }
508 }
Steve Anton8a006912017-12-04 23:25:56509 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17510}
511
512// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
513// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
514// media section/description in the BUNDLE group) needs a ufrag and pwd.
515bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
516 const cricket::ContentGroup* bundle =
517 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56518 for (const cricket::ContentInfo& content_info : desc->contents()) {
519 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17520 continue;
521 }
Steve Anton8a006912017-12-04 23:25:56522 const std::string& mid = content_info.name;
523 if (bundle && bundle->HasContentName(mid) &&
524 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17525 // This isn't the first media section in the BUNDLE group, so it's not
526 // required to have ufrag/password, since only the ufrag/password from
527 // the first section actually get used.
528 continue;
529 }
530
531 // If the content isn't rejected or bundled into another m= section,
532 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56533 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17534 if (!tinfo) {
535 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25536 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17537 return false;
538 }
539 if (tinfo->description.ice_ufrag.empty() ||
540 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25541 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17542 return false;
543 }
544 }
545 return true;
546}
547
Steve Anton75737c02017-11-06 18:37:17548// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
549bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
550 const SessionDescriptionInterface* new_desc,
551 const std::string& content_name) {
552 if (!old_desc) {
553 return false;
554 }
555 const SessionDescription* new_sd = new_desc->description();
556 const SessionDescription* old_sd = old_desc->description();
557 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
558 if (!cinfo || cinfo->rejected) {
559 return false;
560 }
561 // If the content isn't rejected, check if ufrag and password has changed.
562 const cricket::TransportDescription* new_transport_desc =
563 new_sd->GetTransportDescriptionByName(content_name);
564 const cricket::TransportDescription* old_transport_desc =
565 old_sd->GetTransportDescriptionByName(content_name);
566 if (!new_transport_desc || !old_transport_desc) {
567 // No transport description exists. This is not an ICE restart.
568 return false;
569 }
570 if (cricket::IceCredentialsChanged(
571 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
572 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25573 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
574 << ".";
Steve Anton75737c02017-11-06 18:37:17575 return true;
576 }
577 return false;
578}
579
Steve Anton80dd7b52018-02-17 01:08:42580// Generates a string error message for SetLocalDescription/SetRemoteDescription
581// from an RTCError.
582std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
583 SdpType type,
584 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 11:41:30585 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42586 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
587 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32588 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42589}
590
Seth Hampson5b4f0752018-04-02 23:31:36591std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
592 std::string output = "streams=[";
593 const char* separator = "";
594 for (const auto& stream_id : stream_ids) {
595 output.append(separator).append(stream_id);
596 separator = ", ";
597 }
598 output.append("]");
599 return output;
600}
601
Danil Chapovalov66cadcc2018-06-19 14:47:43602absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23603 int rtc_configuration_parameter) {
604 if (rtc_configuration_parameter ==
605 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43606 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23607 }
608 return rtc_configuration_parameter;
609}
610
Amit Hilbuche2a284d2019-03-05 20:36:31611void ReportSimulcastApiVersion(const char* name,
612 const SessionDescription& session) {
613 bool has_legacy = false;
614 bool has_spec_compliant = false;
615 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 18:35:45616 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 20:36:31617 continue;
618 }
Harald Alvestrand1716d392019-06-03 18:35:45619 has_spec_compliant |= content.media_description()->HasSimulcast();
620 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 20:36:31621 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
622 }
623 }
624
625 if (has_legacy) {
626 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
627 kSimulcastApiVersionMax);
628 }
629 if (has_spec_compliant) {
630 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
631 kSimulcastApiVersionMax);
632 }
633 if (!has_legacy && !has_spec_compliant) {
634 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
635 kSimulcastApiVersionMax);
636 }
637}
638
Guido Urdaneta70c2db12019-04-16 10:24:14639const ContentInfo* FindTransceiverMSection(
640 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
641 const SessionDescriptionInterface* session_description) {
642 return transceiver->mid()
643 ? session_description->description()->GetContentByName(
644 *transceiver->mid())
645 : nullptr;
646}
647
Henrik Boströma3728d32019-10-28 11:09:49648// Wraps a CreateSessionDescriptionObserver and an OperationsChain operation
649// complete callback. When the observer is invoked, the wrapped observer is
650// invoked followed by invoking the completion callback.
651class CreateSessionDescriptionObserverOperationWrapper
652 : public CreateSessionDescriptionObserver {
653 public:
654 CreateSessionDescriptionObserverOperationWrapper(
655 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer,
656 std::function<void()> operation_complete_callback)
657 : observer_(std::move(observer)),
658 operation_complete_callback_(std::move(operation_complete_callback)) {
659 RTC_DCHECK(observer_);
660 }
661 ~CreateSessionDescriptionObserverOperationWrapper() override {
662 RTC_DCHECK(was_called_);
663 }
664
665 void OnSuccess(SessionDescriptionInterface* desc) override {
666 RTC_DCHECK(!was_called_);
667#ifdef RTC_DCHECK_IS_ON
668 was_called_ = true;
669#endif // RTC_DCHECK_IS_ON
670 // Completing the operation before invoking the observer allows the observer
671 // to execute SetLocalDescription() without delay.
672 operation_complete_callback_();
673 observer_->OnSuccess(desc);
674 }
675
676 void OnFailure(RTCError error) override {
677 RTC_DCHECK(!was_called_);
678#ifdef RTC_DCHECK_IS_ON
679 was_called_ = true;
680#endif // RTC_DCHECK_IS_ON
681 operation_complete_callback_();
682 observer_->OnFailure(std::move(error));
683 }
684
685 private:
686#ifdef RTC_DCHECK_IS_ON
687 bool was_called_ = false;
688#endif // RTC_DCHECK_IS_ON
689 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_;
690 std::function<void()> operation_complete_callback_;
691};
692
Jonas Orelande3096512020-05-27 07:01:05693// Check if the changes of IceTransportsType motives an ice restart.
694bool NeedIceRestart(bool surface_ice_candidates_on_ice_transport_type_changed,
695 PeerConnectionInterface::IceTransportsType current,
696 PeerConnectionInterface::IceTransportsType modified) {
697 if (current == modified) {
698 return false;
699 }
700
701 if (!surface_ice_candidates_on_ice_transport_type_changed) {
702 return true;
703 }
704
705 auto current_filter = ConvertIceTransportTypeToCandidateFilter(current);
706 auto modified_filter = ConvertIceTransportTypeToCandidateFilter(modified);
707
708 // If surface_ice_candidates_on_ice_transport_type_changed is true and we
709 // extend the filter, then no ice restart is needed.
710 return (current_filter & modified_filter) != current_filter;
711}
712
Steve Anton75737c02017-11-06 18:37:17713} // namespace
714
Henrik Boström4e196702019-10-30 09:35:50715// Used by parameterless SetLocalDescription() to create an offer or answer.
716// Upon completion of creating the session description, SetLocalDescription() is
717// invoked with the result.
718// For consistency with DoSetLocalDescription(), if the PeerConnection is
719// destroyed midst operation, we DO NOT inform the
720// |set_local_description_observer| that the operation failed.
721// TODO(hbos): If/when we process SLD messages in ~PeerConnection, the
722// consistent thing would be to inform the observer here.
723class PeerConnection::ImplicitCreateSessionDescriptionObserver
724 : public CreateSessionDescriptionObserver {
725 public:
726 ImplicitCreateSessionDescriptionObserver(
727 rtc::WeakPtr<PeerConnection> pc,
728 rtc::scoped_refptr<SetSessionDescriptionObserver>
729 set_local_description_observer)
730 : pc_(std::move(pc)),
731 set_local_description_observer_(
732 std::move(set_local_description_observer)) {}
733 ~ImplicitCreateSessionDescriptionObserver() override {
734 RTC_DCHECK(was_called_);
735 }
736
737 void SetOperationCompleteCallback(
738 std::function<void()> operation_complete_callback) {
739 operation_complete_callback_ = std::move(operation_complete_callback);
740 }
741
742 bool was_called() const { return was_called_; }
743
744 void OnSuccess(SessionDescriptionInterface* desc_ptr) override {
745 RTC_DCHECK(!was_called_);
746 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
747 was_called_ = true;
748
749 // Abort early if |pc_| is no longer valid.
750 if (!pc_) {
751 operation_complete_callback_();
752 return;
753 }
754 // DoSetLocalDescription() is currently implemented as a synchronous
755 // operation but where the |set_local_description_observer_|'s callbacks are
756 // invoked asynchronously in a post to PeerConnection::OnMessage().
757 pc_->DoSetLocalDescription(std::move(desc),
758 std::move(set_local_description_observer_));
759 // For backwards-compatability reasons, we declare the operation as
760 // completed here (rather than in PeerConnection::OnMessage()). This ensures
761 // that subsequent offer/answer operations can start immediately (without
762 // waiting for OnMessage()).
763 operation_complete_callback_();
764 }
765
766 void OnFailure(RTCError error) override {
767 RTC_DCHECK(!was_called_);
768 was_called_ = true;
769
770 // Abort early if |pc_| is no longer valid.
771 if (!pc_) {
772 operation_complete_callback_();
773 return;
774 }
775 // DoSetLocalDescription() reports its failures in a post. We do the
776 // same thing here for consistency.
777 pc_->PostSetSessionDescriptionFailure(
778 set_local_description_observer_,
779 RTCError(error.type(),
780 std::string("SetLocalDescription failed to create "
781 "session description - ") +
782 error.message()));
783 operation_complete_callback_();
784 }
785
786 private:
787 bool was_called_ = false;
788 rtc::WeakPtr<PeerConnection> pc_;
789 rtc::scoped_refptr<SetSessionDescriptionObserver>
790 set_local_description_observer_;
791 std::function<void()> operation_complete_callback_;
792};
793
Henrik Boström79b69802019-07-18 09:16:56794class PeerConnection::LocalIceCredentialsToReplace {
795 public:
796 // Sets the ICE credentials that need restarting to the ICE credentials of
797 // the current and pending descriptions.
798 void SetIceCredentialsFromLocalDescriptions(
799 const SessionDescriptionInterface* current_local_description,
800 const SessionDescriptionInterface* pending_local_description) {
801 ice_credentials_.clear();
802 if (current_local_description) {
803 AppendIceCredentialsFromSessionDescription(*current_local_description);
804 }
805 if (pending_local_description) {
806 AppendIceCredentialsFromSessionDescription(*pending_local_description);
807 }
808 }
809
810 void ClearIceCredentials() { ice_credentials_.clear(); }
811
812 // Returns true if we have ICE credentials that need restarting.
813 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
814
815 // Returns true if |local_description| shares no ICE credentials with the
816 // ICE credentials that need restarting.
817 bool SatisfiesIceRestart(
818 const SessionDescriptionInterface& local_description) const {
819 for (const auto& transport_info :
820 local_description.description()->transport_infos()) {
821 if (ice_credentials_.find(std::make_pair(
822 transport_info.description.ice_ufrag,
823 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
824 return false;
825 }
826 }
827 return true;
828 }
829
830 private:
831 void AppendIceCredentialsFromSessionDescription(
832 const SessionDescriptionInterface& desc) {
833 for (const auto& transport_info : desc.description()->transport_infos()) {
834 ice_credentials_.insert(
835 std::make_pair(transport_info.description.ice_ufrag,
836 transport_info.description.ice_pwd));
837 }
838 }
839
840 std::set<std::pair<std::string, std::string>> ice_credentials_;
841};
842
Henrik Boström31638672017-11-23 16:48:32843// Upon completion, posts a task to execute the callback of the
844// SetSessionDescriptionObserver asynchronously on the same thread. At this
845// point, the state of the peer connection might no longer reflect the effects
846// of the SetRemoteDescription operation, as the peer connection could have been
847// modified during the post.
848// TODO(hbos): Remove this class once we remove the version of
849// PeerConnectionInterface::SetRemoteDescription() that takes a
850// SetSessionDescriptionObserver as an argument.
851class PeerConnection::SetRemoteDescriptionObserverAdapter
852 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
853 public:
854 SetRemoteDescriptionObserverAdapter(
855 rtc::scoped_refptr<PeerConnection> pc,
856 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
857 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
858
859 // SetRemoteDescriptionObserverInterface implementation.
860 void OnSetRemoteDescriptionComplete(RTCError error) override {
861 if (error.ok())
862 pc_->PostSetSessionDescriptionSuccess(wrapper_);
863 else
Harald Alvestrand5081c0c2018-03-09 14:18:03864 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32865 }
866
867 private:
868 rtc::scoped_refptr<PeerConnection> pc_;
869 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
870};
871
deadbeef293e9262017-01-11 20:28:30872bool PeerConnectionInterface::RTCConfiguration::operator==(
873 const PeerConnectionInterface::RTCConfiguration& o) const {
874 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10875 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30876 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56877 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10878 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30879 BundlePolicy bundle_policy;
880 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10881 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
882 int ice_candidate_pool_size;
883 bool disable_ipv6;
884 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11885 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22886 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10887 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43888 absl::optional<int> screencast_min_bitrate;
889 absl::optional<bool> combined_audio_video_bwe;
890 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30891 TcpCandidatePolicy tcp_candidate_policy;
892 CandidateNetworkPolicy candidate_network_policy;
893 int audio_jitter_buffer_max_packets;
894 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 14:45:20895 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 14:58:36896 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 20:28:30897 int ice_connection_receiving_timeout;
898 int ice_backup_candidate_pair_ping_interval;
899 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30900 bool prioritize_most_likely_ice_candidate_pairs;
901 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30902 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 18:27:50903 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 20:28:30904 bool presume_writable_when_fully_relayed;
905 bool enable_ice_renomination;
906 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 23:55:33907 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 14:47:43908 absl::optional<int> ice_check_interval_strong_connectivity;
909 absl::optional<int> ice_check_interval_weak_connectivity;
910 absl::optional<int> ice_check_min_interval;
911 absl::optional<int> ice_unwritable_timeout;
912 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:17913 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 14:47:43914 absl::optional<int> stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:40915 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56916 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43917 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11918 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21919 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48920 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 21:19:38921 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 17:44:59922 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 18:02:11923 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 17:16:44924 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48925 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 14:16:35926 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 15:29:44927 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 10:23:02928 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 20:28:30929 };
930 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
931 "Did you add something to RTCConfiguration and forget to "
932 "update operator==?");
933 return type == o.type && servers == o.servers &&
934 bundle_policy == o.bundle_policy &&
935 rtcp_mux_policy == o.rtcp_mux_policy &&
936 tcp_candidate_policy == o.tcp_candidate_policy &&
937 candidate_network_policy == o.candidate_network_policy &&
938 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
939 audio_jitter_buffer_fast_accelerate ==
940 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 14:45:20941 audio_jitter_buffer_min_delay_ms ==
942 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 14:58:36943 audio_jitter_buffer_enable_rtx_handling ==
944 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 20:28:30945 ice_connection_receiving_timeout ==
946 o.ice_connection_receiving_timeout &&
947 ice_backup_candidate_pair_ping_interval ==
948 o.ice_backup_candidate_pair_ping_interval &&
949 continual_gathering_policy == o.continual_gathering_policy &&
950 certificates == o.certificates &&
951 prioritize_most_likely_ice_candidate_pairs ==
952 o.prioritize_most_likely_ice_candidate_pairs &&
953 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51954 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11955 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22956 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30957 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30958 screencast_min_bitrate == o.screencast_min_bitrate &&
959 combined_audio_video_bwe == o.combined_audio_video_bwe &&
960 enable_dtls_srtp == o.enable_dtls_srtp &&
961 ice_candidate_pool_size == o.ice_candidate_pool_size &&
962 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 18:27:50963 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 20:28:30964 presume_writable_when_fully_relayed ==
965 o.presume_writable_when_fully_relayed &&
966 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14967 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 23:55:33968 surface_ice_candidates_on_ice_transport_type_changed ==
969 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 22:55:14970 ice_check_interval_strong_connectivity ==
971 o.ice_check_interval_strong_connectivity &&
972 ice_check_interval_weak_connectivity ==
973 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10974 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57975 ice_unwritable_timeout == o.ice_unwritable_timeout &&
976 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-07 07:30:17977 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 22:45:49978 stun_candidate_keepalive_interval ==
979 o.stun_candidate_keepalive_interval &&
Steve Anton79e79602017-11-20 18:25:56980 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40981 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11982 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21983 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44984 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48985 use_media_transport_for_data_channels ==
986 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 22:50:38987 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 17:44:59988 use_datagram_transport_for_data_channels ==
989 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 18:02:11990 use_datagram_transport_for_data_channels_receive_only ==
991 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 09:25:48992 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 14:16:35993 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 15:29:44994 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 10:23:02995 enable_implicit_rollback == o.enable_implicit_rollback &&
Eldar Rello9276e2c2020-06-10 14:53:39996 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 20:28:30997}
998
999bool PeerConnectionInterface::RTCConfiguration::operator!=(
1000 const PeerConnectionInterface::RTCConfiguration& o) const {
1001 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:261002}
1003
Eldar Rello353a7182019-11-25 16:49:441004void PeerConnection::TransceiverStableState::set_newly_created() {
1005 RTC_DCHECK(!has_m_section_);
1006 newly_created_ = true;
1007}
1008
1009void PeerConnection::TransceiverStableState::SetMSectionIfUnset(
1010 absl::optional<std::string> mid,
1011 absl::optional<size_t> mline_index) {
1012 if (!has_m_section_) {
1013 mid_ = mid;
1014 mline_index_ = mline_index;
1015 has_m_section_ = true;
1016 }
1017}
1018
1019void PeerConnection::TransceiverStableState::SetRemoteStreamIdsIfUnset(
1020 const std::vector<std::string>& ids) {
1021 if (!remote_stream_ids_.has_value()) {
1022 remote_stream_ids_ = ids;
1023 }
1024}
1025
zhihuang8f65cdf2016-05-07 01:40:301026// Generate a RTCP CNAME when a PeerConnection is created.
1027std::string GenerateRtcpCname() {
1028 std::string cname;
1029 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:251030 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:271031 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:301032 }
1033 return cname;
1034}
1035
zhihuang1c378ed2017-08-17 21:10:501036bool ValidateOfferAnswerOptions(
1037 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
1038 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
1039 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:321040}
1041
zhihuang1c378ed2017-08-17 21:10:501042// From |rtc_options|, fill parts of |session_options| shared by all generated
1043// m= sections (in other words, nothing that involves a map/array).
1044void ExtractSharedMediaSessionOptions(
1045 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1046 cricket::MediaSessionOptions* session_options) {
1047 session_options->vad_enabled = rtc_options.voice_activity_detection;
1048 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 13:38:501049 session_options->raw_packetization_for_video =
1050 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 21:10:501051}
zhihuanga77e6bb2017-08-15 01:17:481052
zhihuang38ede132017-06-15 19:52:321053PeerConnection::PeerConnection(PeerConnectionFactory* factory,
1054 std::unique_ptr<RtcEventLog> event_log,
1055 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:361056 : factory_(factory),
zhihuang38ede132017-06-15 19:52:321057 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 10:59:571058 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 11:09:491059 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 21:19:381060 datagram_transport_config_(
1061 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 17:44:591062 datagram_transport_data_channel_config_(
1063 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-07 01:40:301064 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:111065 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:321066 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 08:57:011067 call_(std::move(call)),
Henrik Boström79b69802019-07-18 09:16:561068 call_ptr_(call_.get()),
Henrik Boströma3728d32019-10-28 11:09:491069 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
Harald Alvestrand00cf34c2019-12-02 08:56:021070 data_channel_controller_(this),
Henrik Boströma3728d32019-10-28 11:09:491071 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:361072
1073PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:171074 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:221075 RTC_DCHECK_RUN_ON(signaling_thread());
1076
Henrik Boströma3728d32019-10-28 11:09:491077 weak_ptr_factory_.InvalidateWeakPtrs();
1078
Steve Anton8af21862017-12-15 19:20:131079 // Need to stop transceivers before destroying the stats collector because
1080 // AudioRtpSender has a reference to the StatsCollector it will update when
1081 // stopping.
Mirko Bonadei739baf02019-01-27 16:29:421082 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:131083 transceiver->Stop();
1084 }
Steve Anton4171afb2017-11-20 18:20:221085
Taylor Brandstettera1c30352016-05-13 15:15:111086 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:571087 if (stats_collector_) {
1088 stats_collector_->WaitForPendingRequest();
1089 stats_collector_ = nullptr;
1090 }
Steve Anton75737c02017-11-06 18:37:171091
Steve Anton8af21862017-12-15 19:20:131092 // Don't destroy BaseChannels until after stats has been cleaned up so that
1093 // the last stats request can still read from the channels.
1094 DestroyAllChannels();
1095
Mirko Bonadei675513b2017-11-09 10:09:251096 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:171097
1098 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 18:37:171099 sctp_factory_.reset();
1100 transport_controller_.reset();
1101
deadbeef91dd5672016-05-18 23:55:301102 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 13:13:221103 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1104 RTC_DCHECK_RUN_ON(network_thread());
1105 port_allocator_.reset();
1106 });
eladalon248fd4f2017-09-06 12:18:151107 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:021108 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:571109 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:151110 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:091111 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:151112 event_log_.reset();
1113 });
Henrik Boströma3728d32019-10-28 11:09:491114
1115 // Process all pending notifications in the message queue. If we don't do
1116 // this, requests will linger and not know they succeeded or failed.
1117 rtc::MessageList list;
1118 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1119 for (auto& msg : list) {
1120 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1121 // Processing CreateOffer() and CreateAnswer() messages ensures their
1122 // observers are invoked even if the PeerConnection is destroyed early.
1123 OnMessage(&msg);
1124 } else {
1125 // TODO(hbos): Consider processing all pending messages. This would mean
1126 // that SetLocalDescription() and SetRemoteDescription() observers are
1127 // informed of successes and failures; this is currently NOT the case.
1128 delete msg.pdata;
1129 }
1130 }
henrike@webrtc.org28e20752013-07-10 00:45:361131}
1132
Steve Anton8af21862017-12-15 19:20:131133void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:081134 // Destroy video channels first since they may have a pointer to a voice
1135 // channel.
Mirko Bonadei739baf02019-01-27 16:29:421136 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081137 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:081138 DestroyTransceiverChannel(transceiver);
1139 }
1140 }
Mirko Bonadei739baf02019-01-27 16:29:421141 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081142 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:081143 DestroyTransceiverChannel(transceiver);
1144 }
1145 }
Harald Alvestrand408cb4b2019-11-16 11:09:081146 DestroyDataChannelTransport();
Steve Anton3fe1b152017-12-12 18:20:081147}
1148
henrike@webrtc.org28e20752013-07-10 00:45:361149bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:451150 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:471151 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 09:18:561152 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:171153 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:591154
1155 RTCError config_error = ValidateConfiguration(configuration);
1156 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:251157 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:591158 return false;
1159 }
1160
Benjamin Wrightcab588882018-05-02 22:12:471161 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:251162 RTC_LOG(LS_ERROR)
1163 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:071164 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:301165 return false;
1166 }
Jonas Orelandbdcee282017-10-10 12:01:401167
Benjamin Wrightcab588882018-05-02 22:12:471168 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:301169 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:251170 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:071171 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:101172 return false;
1173 }
Benjamin Wrightd6f86e82018-05-08 20:12:251174
Benjamin Wrightcab588882018-05-02 22:12:471175 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:151176 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:471177 port_allocator_ = std::move(dependencies.allocator);
Jorge E. Moreira00b46f72020-03-28 01:01:191178 packet_socket_factory_ = std::move(dependencies.packet_socket_factory);
Qingsi Wang25ec8882019-11-15 20:33:051179 ice_transport_factory_ = std::move(dependencies.ice_transport_factory);
Benjamin Wrightd6f86e82018-05-08 20:12:251180 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:101181
Harald Alvestrandb2a74782018-06-28 11:54:071182 cricket::ServerAddresses stun_servers;
1183 std::vector<cricket::RelayServerConfig> turn_servers;
1184
1185 RTCErrorType parse_error =
1186 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1187 if (parse_error != RTCErrorType::NONE) {
1188 return false;
1189 }
1190
Jonas Oreland3c028422019-08-22 14:16:351191 // Add the turn logging id to all turn servers
1192 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1193 turn_server.turn_logging_id = configuration.turn_logging_id;
1194 }
1195
deadbeef91dd5672016-05-18 23:55:301196 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:111197 // there.
Karl Wibergfb3be392019-03-22 13:13:221198 const auto pa_result =
1199 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 11:54:071200 RTC_FROM_HERE,
1201 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 13:13:221202 stun_servers, turn_servers, configuration));
1203
Harald Alvestrandb2a74782018-06-28 11:54:071204 // If initialization was successful, note if STUN or TURN servers
1205 // were supplied.
1206 if (!stun_servers.empty()) {
1207 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1208 }
1209 if (!turn_servers.empty()) {
1210 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1211 }
henrike@webrtc.org28e20752013-07-10 00:45:361212
Qingsi Wang7fc821d2018-07-12 19:54:531213 // Send information about IPv4/IPv6 status.
1214 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 13:13:221215 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 19:54:531216 address_family = kPeerConnection_IPv6;
1217 } else {
1218 address_family = kPeerConnection_IPv4;
1219 }
1220 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1221 kPeerConnectionAddressFamilyCounter_Max);
1222
Zhi Huange830e682018-03-30 17:48:351223 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1224
Steve Anton75737c02017-11-06 18:37:171225 // RFC 3264: The numeric value of the session id and version in the
1226 // o line MUST be representable with a "64 bit signed integer".
1227 // Due to this constraint session id |session_id_| is max limited to
1228 // LLONG_MAX.
1229 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:351230 JsepTransportController::Config config;
1231 config.redetermine_role_on_ice_restart =
1232 configuration.redetermine_role_on_ice_restart;
1233 config.ssl_max_version = factory_->options().ssl_max_version;
1234 config.disable_encryption = options.disable_encryption;
1235 config.bundle_policy = configuration.bundle_policy;
1236 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 17:16:441237 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1238 // stub.
1239 config.crypto_options = configuration.crypto_options.has_value()
1240 ? *configuration.crypto_options
1241 : options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:341242 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 16:22:121243 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1244 // since the JsepTransportController instance is owned by this PeerConnection
1245 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1246 // pointer.
1247 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1248 int64_t packet_time_us) {
1249 RTC_DCHECK_RUN_ON(network_thread());
1250 rtcp_invoker_.AsyncInvoke<void>(
1251 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1252 RTC_DCHECK_RUN_ON(worker_thread());
1253 // |call_| is reset on the worker thread in the PeerConnection
1254 // destructor, so we check that it's still valid before propagating
1255 // the packet.
1256 if (call_) {
1257 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1258 packet_time_us);
1259 }
1260 });
1261 };
Karl Wibergb03ab712019-02-14 10:59:571262 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 17:48:351263#if defined(ENABLE_EXTERNAL_AUTH)
1264 config.enable_external_auth = true;
1265#endif
Zhi Huangb57e1692018-06-12 18:41:111266 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:421267
Bjorn A Mellem5985a042019-06-28 21:19:381268 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 18:06:001269 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 21:19:381270 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 17:44:591271 use_datagram_transport_for_data_channels_ =
1272 datagram_transport_data_channel_config_.enabled &&
1273 configuration.use_datagram_transport_for_data_channels.value_or(
1274 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 18:02:111275 use_datagram_transport_for_data_channels_receive_only_ =
1276 configuration.use_datagram_transport_for_data_channels_receive_only
1277 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellem7a9a0922019-11-26 17:19:401278 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Anton Sukhanov98a462c2018-10-17 20:15:421279 if (!factory_->media_transport_factory()) {
1280 RTC_DCHECK(false)
Bjorn A Mellem7a9a0922019-11-26 17:19:401281 << "PeerConnecton is initialized with use_datagram_transport = true "
1282 "or use_datagram_transport_for_data_channels = true "
Jonas Olssonb2b20312020-01-14 11:11:311283 "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 20:15:421284 return false;
1285 }
1286
Bjorn A Mellem5985a042019-06-28 21:19:381287 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 17:44:591288 config.use_datagram_transport_for_data_channels =
1289 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 18:02:111290 config.use_datagram_transport_for_data_channels_receive_only =
1291 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 20:15:421292 config.media_transport_factory = factory_->media_transport_factory();
1293 }
1294
Bjorn A Mellembc3eebc2019-09-23 21:53:541295 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1296 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1297 if (!configuration.certificates.empty()) {
1298 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1299 // just picking the first one. The decision should be made based on the DTLS
1300 // handshake. The DTLS negotiations need to know about all certificates.
1301 certificate = configuration.certificates[0];
1302 }
1303
1304 if (options.disable_encryption) {
1305 dtls_enabled_ = false;
1306 } else {
1307 // Enable DTLS by default if we have an identity store or a certificate.
1308 dtls_enabled_ = (dependencies.cert_generator || certificate);
1309 // |configuration| can override the default |dtls_enabled_| value.
1310 if (configuration.enable_dtls_srtp) {
1311 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1312 }
1313 }
1314
1315 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1316
1317 if (use_datagram_transport_for_data_channels_) {
1318 if (configuration.enable_rtp_data_channel) {
1319 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1320 "use_datagram_transport_for_data_channels are "
1321 "incompatible and cannot both be set to true";
1322 return false;
1323 }
1324 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1325 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
Harald Alvestrand05e4d082019-12-03 13:04:211326 data_channel_controller_.set_data_channel_type(
1327 cricket::DCT_DATA_CHANNEL_TRANSPORT);
Bjorn A Mellembc3eebc2019-09-23 21:53:541328 } else {
1329 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
Harald Alvestrand05e4d082019-12-03 13:04:211330 data_channel_controller_.set_data_channel_type(
1331 cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Bjorn A Mellembc3eebc2019-09-23 21:53:541332 config.sctp_factory = sctp_factory_.get();
1333 }
Bjorn A Mellembc3eebc2019-09-23 21:53:541334 } else if (configuration.enable_rtp_data_channel) {
1335 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1336 // set. It takes precendence over the disable_sctp_data_channels
1337 // PeerConnectionFactoryInterface::Options.
Harald Alvestrand05e4d082019-12-03 13:04:211338 data_channel_controller_.set_data_channel_type(cricket::DCT_RTP);
Bjorn A Mellembc3eebc2019-09-23 21:53:541339 } else {
1340 // DTLS has to be enabled to use SCTP.
1341 if (!options.disable_sctp_data_channels && dtls_enabled_) {
Harald Alvestrand05e4d082019-12-03 13:04:211342 data_channel_controller_.set_data_channel_type(cricket::DCT_SCTP);
Bjorn A Mellembc3eebc2019-09-23 21:53:541343 config.sctp_factory = sctp_factory_.get();
1344 }
1345 }
1346
Qingsi Wang25ec8882019-11-15 20:33:051347 config.ice_transport_factory = ice_transport_factory_.get();
1348
Zhi Huange830e682018-03-30 17:48:351349 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:151350 signaling_thread(), network_thread(), port_allocator_.get(),
1351 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:351352 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:591353 this, &PeerConnection::OnTransportControllerConnectionState);
1354 transport_controller_->SignalStandardizedIceConnectionState.connect(
1355 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:171356 transport_controller_->SignalConnectionState.connect(
1357 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:351358 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:171359 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:351360 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:171361 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 09:23:431362 transport_controller_->SignalIceCandidateError.connect(
1363 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 17:48:351364 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:171365 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1366 transport_controller_->SignalDtlsHandshakeError.connect(
1367 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 17:54:471368 transport_controller_->SignalIceCandidatePairChanged.connect(
1369 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 18:37:171370
deadbeefab9b2d12015-10-14 18:33:111371 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:011372 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:361373
Steve Antonba818672017-11-06 18:21:571374 configuration_ = configuration;
1375
Steve Antond25da372017-11-06 22:50:291376 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171377
Steve Anton75737c02017-11-06 18:37:171378 video_options_.screencast_min_bitrate_kbps =
1379 configuration.screencast_min_bitrate;
1380 audio_options_.combined_audio_video_bwe =
1381 configuration.combined_audio_video_bwe;
1382
1383 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301384 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171385
1386 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301387 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171388
Jakob Ivarsson10403ae2018-11-27 14:45:201389 audio_options_.audio_jitter_buffer_min_delay_ms =
1390 configuration.audio_jitter_buffer_min_delay_ms;
1391
Jakob Ivarsson53eae872019-01-10 14:58:361392 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1393 configuration.audio_jitter_buffer_enable_rtx_handling;
1394
Steve Anton75737c02017-11-06 18:37:171395 // Whether the certificate generator/certificate is null or not determines
1396 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1397 // the right instructions by clearing the variables if needed.
1398 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471399 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171400 certificate = nullptr;
1401 } else if (certificate) {
1402 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471403 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171404 }
1405
1406 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1407 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-26 01:13:561408 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 18:37:171409 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1410 this, &PeerConnection::OnCertificateReady);
1411
1412 if (options.disable_encryption) {
1413 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1414 }
1415
1416 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 17:16:441417 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-11 00:08:051418 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:361419
Steve Anton4171afb2017-11-20 18:20:221420 // Add default audio/video transceivers for Plan B SDP.
1421 if (!IsUnifiedPlan()) {
1422 transceivers_.push_back(
1423 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1424 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1425 transceivers_.push_back(
1426 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1427 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1428 }
Harald Alvestrand183e09d2018-06-28 10:04:411429 int delay_ms =
1430 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401431 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1432 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 05:38:401433
1434 if (dependencies.video_bitrate_allocator_factory) {
1435 video_bitrate_allocator_factory_ =
1436 std::move(dependencies.video_bitrate_allocator_factory);
1437 } else {
1438 video_bitrate_allocator_factory_ =
1439 CreateBuiltinVideoBitrateAllocatorFactory();
1440 }
henrike@webrtc.org28e20752013-07-10 00:45:361441 return true;
1442}
1443
Steve Anton038834f2017-07-14 22:59:591444RTCError PeerConnection::ValidateConfiguration(
1445 const RTCConfiguration& config) const {
Steve Antonf4172382020-01-27 23:45:021446 return cricket::P2PTransportChannel::ValidateIceConfig(
1447 ParseIceConfig(config));
Steve Anton038834f2017-07-14 22:59:591448}
1449
Yves Gerey665174f2018-06-19 13:03:051450rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 22:55:091451 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581452 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1453 "Plan SdpSemantics. Please use GetSenders "
1454 "instead.";
deadbeefab9b2d12015-10-14 18:33:111455 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361456}
1457
Yves Gerey665174f2018-06-19 13:03:051458rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 22:55:091459 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581460 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1461 "Plan SdpSemantics. Please use GetReceivers "
1462 "instead.";
deadbeefab9b2d12015-10-14 18:33:111463 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361464}
1465
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291466bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561467 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581468 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1469 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171470 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361471 if (IsClosed()) {
1472 return false;
1473 }
deadbeefab9b2d12015-10-14 18:33:111474 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361475 return false;
1476 }
deadbeefab9b2d12015-10-14 18:33:111477
1478 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431479 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1480 observer->SignalAudioTrackAdded.connect(this,
1481 &PeerConnection::OnAudioTrackAdded);
1482 observer->SignalAudioTrackRemoved.connect(
1483 this, &PeerConnection::OnAudioTrackRemoved);
1484 observer->SignalVideoTrackAdded.connect(this,
1485 &PeerConnection::OnVideoTrackAdded);
1486 observer->SignalVideoTrackRemoved.connect(
1487 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291488 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111489
deadbeefab9b2d12015-10-14 18:33:111490 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251491 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111492 }
1493 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251494 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111495 }
1496
tommi@webrtc.org03505bc2014-07-14 20:15:261497 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 10:24:141498 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361499 return true;
1500}
1501
1502void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 09:18:561503 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581504 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1505 "Plan SdpSemantics. Please use RemoveTrack "
1506 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171507 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251508 if (!IsClosed()) {
1509 for (const auto& track : local_stream->GetAudioTracks()) {
1510 RemoveAudioTrack(track.get(), local_stream);
1511 }
1512 for (const auto& track : local_stream->GetVideoTracks()) {
1513 RemoveVideoTrack(track.get(), local_stream);
1514 }
deadbeefab9b2d12015-10-14 18:33:111515 }
deadbeefab9b2d12015-10-14 18:33:111516 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431517 stream_observers_.erase(
1518 std::remove_if(
1519 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291520 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281521 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431522 }),
1523 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111524
henrike@webrtc.org28e20752013-07-10 00:45:361525 if (IsClosed()) {
1526 return;
1527 }
Guido Urdaneta70c2db12019-04-16 10:24:141528 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361529}
1530
Steve Anton2d6c76a2018-01-06 01:10:521531RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571532 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101533 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 09:18:561534 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-06 01:10:521535 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571536 if (!track) {
1537 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1538 }
1539 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1540 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1541 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1542 "Track has invalid kind: " + track->kind());
1543 }
Steve Antonf9381f02017-12-14 18:23:571544 if (IsClosed()) {
1545 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1546 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421547 }
Steve Anton4171afb2017-11-20 18:20:221548 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571549 LOG_AND_RETURN_ERROR(
1550 RTCErrorType::INVALID_PARAMETER,
1551 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421552 }
Steve Antonf9381f02017-12-14 18:23:571553 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361554 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1555 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571556 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 10:24:141557 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171558 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571559 }
1560 return sender_or_error;
1561}
deadbeefe1f9d832016-01-14 23:35:421562
Steve Antonf9381f02017-12-14 18:23:571563RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1564PeerConnection::AddTrackPlanB(
1565 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101566 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361567 if (stream_ids.size() > 1u) {
1568 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1569 "AddTrack with more than one stream is not "
1570 "supported with Plan B semantics.");
1571 }
1572 std::vector<std::string> adjusted_stream_ids = stream_ids;
1573 if (adjusted_stream_ids.empty()) {
1574 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1575 }
Steve Anton02ee47c2018-01-11 00:26:061576 cricket::MediaType media_type =
1577 (track->kind() == MediaStreamTrackInterface::kAudioKind
1578 ? cricket::MEDIA_TYPE_AUDIO
1579 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361580 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201581 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421582 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051583 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221584 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221585 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181586 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361587 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221588 if (sender_info) {
1589 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421590 }
Steve Antonf9381f02017-12-14 18:23:571591 } else {
1592 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051593 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221594 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221595 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181596 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361597 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221598 if (sender_info) {
1599 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421600 }
deadbeefe1f9d832016-01-14 23:35:421601 }
Steve Anton02ee47c2018-01-11 00:26:061602 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571603}
deadbeefe1f9d832016-01-14 23:35:421604
Steve Antonf9381f02017-12-14 18:23:571605RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1606PeerConnection::AddTrackUnifiedPlan(
1607 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101608 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571609 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1610 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231611 RTC_LOG(LS_INFO) << "Reusing an existing "
1612 << cricket::MediaTypeToString(transceiver->media_type())
1613 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571614 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121615 transceiver->internal()->set_direction(
1616 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571617 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121618 transceiver->internal()->set_direction(
1619 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571620 }
Steve Anton02ee47c2018-01-11 00:26:061621 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:381622 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Eldar Rello353a7182019-11-25 16:49:441623 transceiver->internal()->set_reused_for_addtrack(true);
Steve Antonf9381f02017-12-14 18:23:571624 } else {
1625 cricket::MediaType media_type =
1626 (track->kind() == MediaStreamTrackInterface::kAudioKind
1627 ? cricket::MEDIA_TYPE_AUDIO
1628 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231629 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1630 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501631 std::string sender_id = track->id();
1632 // Avoid creating a sender with an existing ID by generating a random ID.
1633 // This can happen if this is the second time AddTrack has created a sender
1634 // for this track.
1635 if (FindSenderById(sender_id)) {
1636 sender_id = rtc::CreateRandomUuid();
1637 }
Florent Castelli892acf02018-10-01 20:47:201638 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061639 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1640 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571641 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121642 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571643 }
Steve Antonf9381f02017-12-14 18:23:571644 return transceiver->sender();
1645}
1646
1647rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1648PeerConnection::FindFirstTransceiverForAddedTrack(
1649 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1650 RTC_DCHECK(track);
1651 for (auto transceiver : transceivers_) {
1652 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081653 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571654 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421655 !transceiver->internal()->has_ever_been_used_to_send() &&
1656 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571657 return transceiver;
1658 }
1659 }
1660 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421661}
1662
1663bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1664 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331665 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571666}
1667
Steve Anton24db5732018-07-23 17:27:331668RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571669 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 09:18:561670 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 18:23:571671 if (!sender) {
1672 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1673 }
deadbeefe1f9d832016-01-14 23:35:421674 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1676 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421677 }
Steve Antonf9381f02017-12-14 18:23:571678 if (IsUnifiedPlan()) {
1679 auto transceiver = FindTransceiverBySender(sender);
1680 if (!transceiver || !sender->track()) {
1681 return RTCError::OK();
1682 }
1683 sender->SetTrack(nullptr);
1684 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121685 transceiver->internal()->set_direction(
1686 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571687 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121688 transceiver->internal()->set_direction(
1689 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571690 }
Steve Anton4171afb2017-11-20 18:20:221691 } else {
Steve Antonf9381f02017-12-14 18:23:571692 bool removed;
1693 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1694 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1695 } else {
1696 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1697 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1698 }
1699 if (!removed) {
1700 LOG_AND_RETURN_ERROR(
1701 RTCErrorType::INVALID_PARAMETER,
1702 "Couldn't find sender " + sender->id() + " to remove.");
1703 }
Steve Anton4171afb2017-11-20 18:20:221704 }
Guido Urdaneta70c2db12019-04-16 10:24:141705 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571706 return RTCError::OK();
1707}
1708
1709rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1710PeerConnection::FindTransceiverBySender(
1711 rtc::scoped_refptr<RtpSenderInterface> sender) {
1712 for (auto transceiver : transceivers_) {
1713 if (transceiver->sender() == sender) {
1714 return transceiver;
1715 }
1716 }
1717 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421718}
1719
Steve Anton9158ef62017-11-27 21:01:521720RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1721PeerConnection::AddTransceiver(
1722 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1723 return AddTransceiver(track, RtpTransceiverInit());
1724}
1725
1726RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1727PeerConnection::AddTransceiver(
1728 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1729 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561730 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581731 RTC_CHECK(IsUnifiedPlan())
1732 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521733 if (!track) {
1734 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1735 }
1736 cricket::MediaType media_type;
1737 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1738 media_type = cricket::MEDIA_TYPE_AUDIO;
1739 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1740 media_type = cricket::MEDIA_TYPE_VIDEO;
1741 } else {
1742 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1743 "Track kind is not audio or video");
1744 }
1745 return AddTransceiver(media_type, track, init);
1746}
1747
1748RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1749PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1750 return AddTransceiver(media_type, RtpTransceiverInit());
1751}
1752
1753RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1754PeerConnection::AddTransceiver(cricket::MediaType media_type,
1755 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 09:18:561756 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581757 RTC_CHECK(IsUnifiedPlan())
1758 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521759 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1760 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1761 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1762 "media type is not audio or video");
1763 }
1764 return AddTransceiver(media_type, nullptr, init);
1765}
1766
1767RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1768PeerConnection::AddTransceiver(
1769 cricket::MediaType media_type,
1770 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071771 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 10:24:141772 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 21:01:521773 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1774 media_type == cricket::MEDIA_TYPE_VIDEO));
1775 if (track) {
1776 RTC_DCHECK_EQ(media_type,
1777 (track->kind() == MediaStreamTrackInterface::kAudioKind
1778 ? cricket::MEDIA_TYPE_AUDIO
1779 : cricket::MEDIA_TYPE_VIDEO));
1780 }
1781
Amit Hilbuche2a284d2019-03-05 20:36:311782 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1783 init.send_encodings.size(), 0, 7, 8);
1784
Amit Hilbuchaa584152019-02-07 01:09:521785 size_t num_rids = absl::c_count_if(init.send_encodings,
1786 [](const RtpEncodingParameters& encoding) {
1787 return !encoding.rid.empty();
1788 });
1789 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-07 01:09:521790 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-07 01:09:521791 RTCErrorType::INVALID_PARAMETER,
1792 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:391793 }
1794
Amit Hilbuchf4770402019-04-08 21:11:571795 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1796 [](const RtpEncodingParameters& encoding) {
1797 return !IsLegalRsidName(encoding.rid);
1798 })) {
1799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1800 "Invalid RID value provided.");
1801 }
1802
Amit Hilbuchaa584152019-02-07 01:09:521803 if (absl::c_any_of(init.send_encodings,
1804 [](const RtpEncodingParameters& encoding) {
1805 return encoding.ssrc.has_value();
1806 })) {
1807 LOG_AND_RETURN_ERROR(
1808 RTCErrorType::UNSUPPORTED_PARAMETER,
1809 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 20:47:201810 }
1811
1812 RtpParameters parameters;
1813 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-07 01:09:521814
1815 // Encodings are dropped from the tail if too many are provided.
1816 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1817 parameters.encodings.erase(
1818 parameters.encodings.begin() + kMaxSimulcastStreams,
1819 parameters.encodings.end());
1820 }
1821
1822 // Single RID should be removed.
1823 if (parameters.encodings.size() == 1 &&
1824 !parameters.encodings[0].rid.empty()) {
1825 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1826 parameters.encodings[0].rid.clear();
1827 }
1828
1829 // If RIDs were not provided, they are generated for simulcast scenario.
1830 if (parameters.encodings.size() > 1 && num_rids == 0) {
1831 rtc::UniqueStringGenerator rid_generator;
1832 for (RtpEncodingParameters& encoding : parameters.encodings) {
1833 encoding.rid = rid_generator();
1834 }
1835 }
1836
Florent Castelli892acf02018-10-01 20:47:201837 if (UnimplementedRtpParameterHasValue(parameters)) {
1838 LOG_AND_RETURN_ERROR(
1839 RTCErrorType::UNSUPPORTED_PARAMETER,
1840 "Attempted to set an unimplemented parameter of RtpParameters.");
1841 }
Steve Anton9158ef62017-11-27 21:01:521842
Florent Castellic1a0bcb2019-01-29 13:26:481843 auto result = cricket::CheckRtpParametersValues(parameters);
1844 if (!result.ok()) {
1845 LOG_AND_RETURN_ERROR(result.type(), result.message());
1846 }
1847
Steve Anton3d954a62018-04-02 18:27:231848 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1849 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501850 // Set the sender ID equal to the track ID if the track is specified unless
1851 // that sender ID is already in use.
1852 std::string sender_id =
1853 (track && !FindSenderById(track->id()) ? track->id()
1854 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 20:47:201855 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-07 01:09:521856 parameters.encodings);
Steve Anton02ee47c2018-01-11 00:26:061857 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1858 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1859 transceiver->internal()->set_direction(init.direction);
1860
Guido Urdaneta70c2db12019-04-16 10:24:141861 if (update_negotiation_needed) {
1862 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071863 }
Steve Antonf9381f02017-12-14 18:23:571864
1865 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1866}
1867
Steve Anton02ee47c2018-01-11 00:26:061868rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1869PeerConnection::CreateSender(
1870 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361871 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061872 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201873 const std::vector<std::string>& stream_ids,
1874 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 08:57:011875 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 21:01:521876 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061877 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1878 RTC_DCHECK(!track ||
1879 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1880 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1881 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 17:31:531882 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 12:00:341883 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061884 } else {
1885 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1886 RTC_DCHECK(!track ||
1887 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1888 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 17:31:531889 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 12:00:341890 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061891 }
Steve Anton111fdfd2018-06-25 20:03:361892 bool set_track_succeeded = sender->SetTrack(track);
1893 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:381894 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 20:47:201895 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061896 return sender;
1897}
1898
1899rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1900PeerConnection::CreateReceiver(cricket::MediaType media_type,
1901 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521902 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1903 receiver;
Steve Anton9158ef62017-11-27 21:01:521904 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521905 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531906 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1907 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341908 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521909 } else {
Steve Anton02ee47c2018-01-11 00:26:061910 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521911 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531912 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1913 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341914 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521915 }
Steve Anton02ee47c2018-01-11 00:26:061916 return receiver;
1917}
1918
1919rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1920PeerConnection::CreateAndAddTransceiver(
1921 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1922 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1923 receiver) {
Steve Anton07563732018-06-26 18:13:501924 // Ensure that the new sender does not have an ID that is already in use by
1925 // another sender.
1926 // Allow receiver IDs to conflict since those come from remote SDP (which
1927 // could be invalid, but should not cause a crash).
1928 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061929 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 17:25:511930 signaling_thread(),
Markus Handell0357b3e2020-03-16 12:40:511931 new RtpTransceiver(
1932 sender, receiver, channel_manager(),
1933 sender->media_type() == cricket::MEDIA_TYPE_AUDIO
1934 ? channel_manager()->GetSupportedAudioRtpHeaderExtensions()
1935 : channel_manager()->GetSupportedVideoRtpHeaderExtensions()));
Steve Anton9158ef62017-11-27 21:01:521936 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121937 transceiver->internal()->SignalNegotiationNeeded.connect(
1938 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571939 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521940}
1941
Steve Anton52d86772018-02-20 23:48:121942void PeerConnection::OnNegotiationNeeded() {
1943 RTC_DCHECK_RUN_ON(signaling_thread());
1944 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 10:24:141945 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121946}
1947
deadbeeffac06552015-11-25 19:26:011948rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441949 const std::string& kind,
1950 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 22:55:091951 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:581952 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1953 "Plan SdpSemantics. Please use AddTransceiver "
1954 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171955 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251956 if (IsClosed()) {
1957 return nullptr;
1958 }
Steve Anton4171afb2017-11-20 18:20:221959
Seth Hampson5b4f0752018-04-02 23:31:361960 // Internally we need to have one stream with Plan B semantics, so we
1961 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101962 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361963 if (stream_id.empty()) {
1964 stream_ids.push_back(rtc::CreateRandomUuid());
1965 RTC_LOG(LS_INFO)
1966 << "No stream_id specified for sender. Generated stream ID: "
1967 << stream_ids[0];
1968 } else {
Seth Hampson845e8782018-03-02 19:34:101969 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061970 }
1971
Steve Anton4171afb2017-11-20 18:20:221972 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391973 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011974 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211975 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 17:31:531976 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-14 00:26:051977 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391978 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061979 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221980 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011981 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 23:20:211982 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 17:31:531983 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-14 00:26:051984 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391985 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061986 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221987 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011988 } else {
Mirko Bonadei675513b2017-11-09 10:09:251989 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221990 return nullptr;
deadbeeffac06552015-11-25 19:26:011991 }
Henrik Andreasssoncc189172019-05-20 09:01:381992 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221993
deadbeefe1f9d832016-01-14 23:35:421994 return new_sender;
deadbeeffac06552015-11-25 19:26:011995}
1996
deadbeef70ab1a12015-09-28 23:53:551997std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1998 const {
Karl Wiberga58e1692019-03-26 12:33:431999 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:392000 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 16:29:422001 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 18:20:222002 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:392003 }
2004 return ret;
deadbeef70ab1a12015-09-28 23:53:552005}
2006
Steve Anton4171afb2017-11-20 18:20:222007std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2008PeerConnection::GetSendersInternal() const {
2009 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
2010 all_senders;
Mirko Bonadei739baf02019-01-27 16:29:422011 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:222012 auto senders = transceiver->internal()->senders();
2013 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
2014 }
2015 return all_senders;
2016}
2017
deadbeef70ab1a12015-09-28 23:53:552018std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
2019PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 12:33:432020 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 21:27:392021 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:222022 for (const auto& receiver : GetReceiversInternal()) {
2023 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:392024 }
2025 return ret;
deadbeef70ab1a12015-09-28 23:53:552026}
2027
Steve Anton4171afb2017-11-20 18:20:222028std::vector<
2029 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2030PeerConnection::GetReceiversInternal() const {
2031 std::vector<
2032 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2033 all_receivers;
Mirko Bonadei739baf02019-01-27 16:29:422034 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:222035 auto receivers = transceiver->internal()->receivers();
2036 all_receivers.insert(all_receivers.end(), receivers.begin(),
2037 receivers.end());
2038 }
2039 return all_receivers;
2040}
2041
Steve Anton9158ef62017-11-27 21:01:522042std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2043PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 22:55:092044 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 21:48:582045 RTC_CHECK(IsUnifiedPlan())
2046 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:522047 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:422048 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 21:01:522049 all_transceivers.push_back(transceiver);
2050 }
2051 return all_transceivers;
2052}
2053
henrike@webrtc.org28e20752013-07-10 00:45:362054bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:492055 MediaStreamTrackInterface* track,
2056 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:172057 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012058 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 08:57:562059 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252060 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362061 return false;
2062 }
2063
tommi@webrtc.org03505bc2014-07-14 20:15:262064 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:152065 // The StatsCollector is used to tell if a track is valid because it may
2066 // remember tracks that the PeerConnection previously removed.
2067 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:252068 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
2069 << track->id();
zhihuange9e94c32016-11-04 18:38:152070 return false;
2071 }
Steve Antonad182762018-09-05 20:22:402072 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
2073 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:362074 return true;
2075}
2076
hbos74e1a4f2016-09-16 06:33:012077void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:202078 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012079 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-16 06:33:012080 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:202081 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:012082 stats_collector_->GetStatsReport(callback);
2083}
2084
Henrik Boström1df1bf82018-03-20 12:24:202085void PeerConnection::GetStats(
2086 rtc::scoped_refptr<RtpSenderInterface> selector,
2087 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2088 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012089 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:202090 RTC_DCHECK(callback);
2091 RTC_DCHECK(stats_collector_);
2092 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2093 if (selector) {
2094 for (const auto& proxy_transceiver : transceivers_) {
2095 for (const auto& proxy_sender :
2096 proxy_transceiver->internal()->senders()) {
2097 if (proxy_sender == selector) {
2098 internal_sender = proxy_sender->internal();
2099 break;
2100 }
2101 }
2102 if (internal_sender)
2103 break;
2104 }
2105 }
Sebastian Jansson6eb8a162018-11-16 10:29:552106 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:202107 // belong to the PeerConnection (in Plan B, senders can be removed from the
2108 // PeerConnection). This means that "all the stats objects representing the
2109 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2110 // produces an empty stats report.
2111 stats_collector_->GetStatsReport(internal_sender, callback);
2112}
2113
2114void PeerConnection::GetStats(
2115 rtc::scoped_refptr<RtpReceiverInterface> selector,
2116 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2117 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 08:57:012118 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 12:24:202119 RTC_DCHECK(callback);
2120 RTC_DCHECK(stats_collector_);
2121 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2122 if (selector) {
2123 for (const auto& proxy_transceiver : transceivers_) {
2124 for (const auto& proxy_receiver :
2125 proxy_transceiver->internal()->receivers()) {
2126 if (proxy_receiver == selector) {
2127 internal_receiver = proxy_receiver->internal();
2128 break;
2129 }
2130 }
2131 if (internal_receiver)
2132 break;
2133 }
2134 }
Sebastian Jansson6eb8a162018-11-16 10:29:552135 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:202136 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2137 // the PeerConnection). This means that "all the stats objects representing
2138 // the selector" is an empty set. Invoking GetStatsReport() with a null
2139 // selector produces an empty stats report.
2140 stats_collector_->GetStatsReport(internal_receiver, callback);
2141}
2142
henrike@webrtc.org28e20752013-07-10 00:45:362143PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072144 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362145 return signaling_state_;
2146}
2147
henrike@webrtc.org28e20752013-07-10 00:45:362148PeerConnectionInterface::IceConnectionState
2149PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072150 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362151 return ice_connection_state_;
2152}
2153
Alex Loiko9289eda2018-11-23 16:18:592154PeerConnectionInterface::IceConnectionState
2155PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072156 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:592157 return standardized_ice_connection_state_;
2158}
2159
Jonas Olsson635474e2018-10-18 13:58:172160PeerConnectionInterface::PeerConnectionState
2161PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072162 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 13:58:172163 return connection_state_;
2164}
2165
henrike@webrtc.org28e20752013-07-10 00:45:362166PeerConnectionInterface::IceGatheringState
2167PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 12:00:072168 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:362169 return ice_gathering_state_;
2170}
2171
Harald Alvestrand61f74d92020-03-02 10:20:002172absl::optional<bool> PeerConnection::can_trickle_ice_candidates() {
2173 RTC_DCHECK_RUN_ON(signaling_thread());
2174 SessionDescriptionInterface* description = current_remote_description_.get();
2175 if (!description) {
2176 description = pending_remote_description_.get();
2177 }
2178 if (!description) {
2179 return absl::nullopt;
2180 }
2181 // TODO(bugs.webrtc.org/7443): Change to retrieve from session-level option.
2182 if (description->description()->transport_infos().size() < 1) {
2183 return absl::nullopt;
2184 }
2185 return description->description()->transport_infos()[0].description.HasOption(
2186 "trickle");
2187}
2188
Yves Gerey665174f2018-06-19 13:03:052189rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:362190 const std::string& label,
2191 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 09:17:472192 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:172193 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:502194
Harald Alvestrand05e4d082019-12-03 13:04:212195 bool first_datachannel = !data_channel_controller_.HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:112196
kwibergd1fe2812016-04-27 13:47:292197 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:582198 if (config) {
2199 internal_config.reset(new InternalDataChannelInit(*config));
2200 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:522201 rtc::scoped_refptr<DataChannelInterface> channel(
Harald Alvestrand00cf34c2019-12-02 08:56:022202 data_channel_controller_.InternalCreateDataChannel(
2203 label, internal_config.get()));
deadbeefab9b2d12015-10-14 18:33:112204 if (!channel.get()) {
2205 return nullptr;
2206 }
henrike@webrtc.org28e20752013-07-10 00:45:362207
jiayl@webrtc.org001fd2d2014-05-29 15:31:112208 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2209 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:172210 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 10:24:142211 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:112212 }
Harald Alvestrand8ebba742018-05-31 12:00:342213 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:362214 return DataChannelProxy::Create(signaling_thread(), channel.get());
2215}
2216
Henrik Boström79b69802019-07-18 09:16:562217void PeerConnection::RestartIce() {
2218 RTC_DCHECK_RUN_ON(signaling_thread());
2219 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2220 current_local_description_.get(), pending_local_description_.get());
2221 UpdateNegotiationNeeded();
2222}
2223
henrike@webrtc.org28e20752013-07-10 00:45:362224void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:162225 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 22:55:092226 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492227 // Chain this operation. If asynchronous operations are pending on the chain,
2228 // this operation will be queued to be invoked, otherwise the contents of the
2229 // lambda will execute immediately.
2230 operations_chain_->ChainOperation(
2231 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2232 observer_refptr =
2233 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2234 options](std::function<void()> operations_chain_callback) {
2235 // Abort early if |this_weak_ptr| is no longer valid.
2236 if (!this_weak_ptr) {
2237 observer_refptr->OnFailure(
2238 RTCError(RTCErrorType::INTERNAL_ERROR,
2239 "CreateOffer failed because the session was shut down"));
2240 operations_chain_callback();
2241 return;
2242 }
2243 // The operation completes asynchronously when the wrapper is invoked.
2244 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2245 observer_wrapper(new rtc::RefCountedObject<
2246 CreateSessionDescriptionObserverOperationWrapper>(
2247 std::move(observer_refptr),
2248 std::move(operations_chain_callback)));
2249 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2250 });
2251}
2252
2253void PeerConnection::DoCreateOffer(
2254 const RTCOfferAnswerOptions& options,
2255 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2256 RTC_DCHECK_RUN_ON(signaling_thread());
2257 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 22:30:512258
nisse7ce109a2017-01-31 08:57:562259 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252260 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:162261 return;
2262 }
deadbeefab9b2d12015-10-14 18:33:112263
Steve Anton8d3444d2017-10-20 22:30:512264 if (IsClosed()) {
2265 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:252266 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032267 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102268 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:512269 return;
2270 }
2271
Steve Anton25ca0ac2019-06-25 17:40:482272 // If a session error has occurred the PeerConnection is in a possibly
2273 // inconsistent state so fail right away.
2274 if (session_error() != SessionError::kNone) {
2275 std::string error_message = GetSessionErrorMsg();
2276 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2277 PostCreateSessionDescriptionFailure(
2278 observer,
2279 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2280 return;
2281 }
2282
zhihuang1c378ed2017-08-17 21:10:502283 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:112284 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:252285 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032286 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102287 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:112288 return;
2289 }
2290
Steve Anton22da89f2018-01-25 21:58:072291 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2292 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2293 if (IsUnifiedPlan()) {
2294 RTCError error = HandleLegacyOfferOptions(options);
2295 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:032296 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:072297 return;
2298 }
2299 }
2300
zhihuang1c378ed2017-08-17 21:10:502301 cricket::MediaSessionOptions session_options;
2302 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:292303 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362304}
2305
Steve Anton22da89f2018-01-25 21:58:072306RTCError PeerConnection::HandleLegacyOfferOptions(
2307 const RTCOfferAnswerOptions& options) {
2308 RTC_DCHECK(IsUnifiedPlan());
2309
2310 if (options.offer_to_receive_audio == 0) {
2311 RemoveRecvDirectionFromReceivingTransceiversOfType(
2312 cricket::MEDIA_TYPE_AUDIO);
2313 } else if (options.offer_to_receive_audio == 1) {
2314 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2315 } else if (options.offer_to_receive_audio > 1) {
2316 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2317 "offer_to_receive_audio > 1 is not supported.");
2318 }
2319
2320 if (options.offer_to_receive_video == 0) {
2321 RemoveRecvDirectionFromReceivingTransceiversOfType(
2322 cricket::MEDIA_TYPE_VIDEO);
2323 } else if (options.offer_to_receive_video == 1) {
2324 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2325 } else if (options.offer_to_receive_video > 1) {
2326 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2327 "offer_to_receive_video > 1 is not supported.");
2328 }
2329
2330 return RTCError::OK();
2331}
2332
2333void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2334 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 16:29:422335 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:232336 RtpTransceiverDirection new_direction =
2337 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2338 if (new_direction != transceiver->direction()) {
2339 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2340 << " transceiver (MID="
2341 << transceiver->mid().value_or("<not set>") << ") from "
2342 << RtpTransceiverDirectionToString(
2343 transceiver->direction())
2344 << " to "
2345 << RtpTransceiverDirectionToString(new_direction)
2346 << " since CreateOffer specified offer_to_receive=0";
2347 transceiver->internal()->set_direction(new_direction);
2348 }
Steve Anton22da89f2018-01-25 21:58:072349 }
2350}
2351
2352void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2353 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 09:18:562354 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 21:58:072355 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:232356 RTC_LOG(LS_INFO)
2357 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2358 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:072359 RtpTransceiverInit init;
2360 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 10:24:142361 AddTransceiver(media_type, nullptr, init,
2362 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 21:58:072363 }
2364}
2365
2366std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2367PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2368 std::vector<
2369 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2370 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 16:29:422371 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082372 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:072373 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2374 receiving_transceivers.push_back(transceiver);
2375 }
2376 }
2377 return receiving_transceivers;
2378}
2379
htaa2a49d92016-03-04 10:51:392380void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2381 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 12:00:072382 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492383 // Chain this operation. If asynchronous operations are pending on the chain,
2384 // this operation will be queued to be invoked, otherwise the contents of the
2385 // lambda will execute immediately.
2386 operations_chain_->ChainOperation(
2387 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2388 observer_refptr =
2389 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2390 options](std::function<void()> operations_chain_callback) {
2391 // Abort early if |this_weak_ptr| is no longer valid.
2392 if (!this_weak_ptr) {
2393 observer_refptr->OnFailure(RTCError(
2394 RTCErrorType::INTERNAL_ERROR,
2395 "CreateAnswer failed because the session was shut down"));
2396 operations_chain_callback();
2397 return;
2398 }
2399 // The operation completes asynchronously when the wrapper is invoked.
2400 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2401 observer_wrapper(new rtc::RefCountedObject<
2402 CreateSessionDescriptionObserverOperationWrapper>(
2403 std::move(observer_refptr),
2404 std::move(operations_chain_callback)));
2405 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2406 });
2407}
2408
2409void PeerConnection::DoCreateAnswer(
2410 const RTCOfferAnswerOptions& options,
2411 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2412 RTC_DCHECK_RUN_ON(signaling_thread());
2413 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 08:57:562414 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252415 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:392416 return;
2417 }
2418
Steve Anton25ca0ac2019-06-25 17:40:482419 // If a session error has occurred the PeerConnection is in a possibly
2420 // inconsistent state so fail right away.
2421 if (session_error() != SessionError::kNone) {
2422 std::string error_message = GetSessionErrorMsg();
2423 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2424 PostCreateSessionDescriptionFailure(
2425 observer,
2426 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2427 return;
2428 }
2429
Steve Antondffead82018-02-06 18:31:292430 if (!(signaling_state_ == kHaveRemoteOffer ||
2431 signaling_state_ == kHaveLocalPrAnswer)) {
2432 std::string error =
2433 "PeerConnection cannot create an answer in a state other than "
2434 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:252435 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:032436 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:102437 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:512438 return;
2439 }
2440
Steve Antondffead82018-02-06 18:31:292441 // The remote description should be set if we're in the right state.
2442 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:512443
Steve Anton22da89f2018-01-25 21:58:072444 if (IsUnifiedPlan()) {
2445 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2446 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2447 "supported with Unified Plan semantics. Use the "
2448 "RtpTransceiver API instead.";
2449 }
2450 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2451 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2452 "supported with Unified Plan semantics. Use the "
2453 "RtpTransceiver API instead.";
2454 }
2455 }
2456
htaa2a49d92016-03-04 10:51:392457 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:502458 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:392459
Steve Antond25da372017-11-06 22:50:292460 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:362461}
2462
2463void PeerConnection::SetLocalDescription(
2464 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:422465 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 22:55:092466 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492467 // Chain this operation. If asynchronous operations are pending on the chain,
2468 // this operation will be queued to be invoked, otherwise the contents of the
2469 // lambda will execute immediately.
2470 operations_chain_->ChainOperation(
2471 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2472 observer_refptr =
2473 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2474 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2475 std::function<void()> operations_chain_callback) mutable {
2476 // Abort early if |this_weak_ptr| is no longer valid.
2477 if (!this_weak_ptr) {
2478 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2479 // |observer_refptr| that the operation failed in this case.
2480 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2481 // the consistent thing would be to inform the observer here.
2482 operations_chain_callback();
2483 return;
2484 }
2485 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2486 std::move(observer_refptr));
2487 // DoSetLocalDescription() is currently implemented as a synchronous
2488 // operation but where the |observer|'s callbacks are invoked
2489 // asynchronously in a post to OnMessage().
2490 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 09:35:502491 // completed here (rather than in OnMessage()). This ensures that
2492 // subsequent offer/answer operations can start immediately (without
2493 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 11:09:492494 operations_chain_callback();
2495 });
2496}
Steve Anton8a006912017-12-04 23:25:562497
Henrik Boström4e196702019-10-30 09:35:502498void PeerConnection::SetLocalDescription(
2499 SetSessionDescriptionObserver* observer) {
2500 RTC_DCHECK_RUN_ON(signaling_thread());
2501 // The |create_sdp_observer| handles performing DoSetLocalDescription() with
2502 // the resulting description as well as completing the operation.
2503 rtc::scoped_refptr<ImplicitCreateSessionDescriptionObserver>
2504 create_sdp_observer(
2505 new rtc::RefCountedObject<ImplicitCreateSessionDescriptionObserver>(
2506 weak_ptr_factory_.GetWeakPtr(),
2507 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer)));
2508 // Chain this operation. If asynchronous operations are pending on the chain,
2509 // this operation will be queued to be invoked, otherwise the contents of the
2510 // lambda will execute immediately.
2511 operations_chain_->ChainOperation(
2512 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2513 create_sdp_observer](std::function<void()> operations_chain_callback) {
2514 // The |create_sdp_observer| is responsible for completing the
2515 // operation.
2516 create_sdp_observer->SetOperationCompleteCallback(
2517 std::move(operations_chain_callback));
2518 // Abort early if |this_weak_ptr| is no longer valid. This triggers the
2519 // same code path as if DoCreateOffer() or DoCreateAnswer() failed.
2520 if (!this_weak_ptr) {
2521 create_sdp_observer->OnFailure(RTCError(
2522 RTCErrorType::INTERNAL_ERROR,
2523 "SetLocalDescription failed because the session was shut down"));
2524 return;
2525 }
2526 switch (this_weak_ptr->signaling_state()) {
2527 case PeerConnectionInterface::kStable:
2528 case PeerConnectionInterface::kHaveLocalOffer:
2529 case PeerConnectionInterface::kHaveRemotePrAnswer:
2530 // TODO(hbos): If [LastCreatedOffer] exists and still represents the
2531 // current state of the system, use that instead of creating another
2532 // offer.
2533 this_weak_ptr->DoCreateOffer(RTCOfferAnswerOptions(),
2534 create_sdp_observer);
2535 break;
2536 case PeerConnectionInterface::kHaveLocalPrAnswer:
2537 case PeerConnectionInterface::kHaveRemoteOffer:
2538 // TODO(hbos): If [LastCreatedAnswer] exists and still represents
2539 // the current state of the system, use that instead of creating
2540 // another answer.
2541 this_weak_ptr->DoCreateAnswer(RTCOfferAnswerOptions(),
2542 create_sdp_observer);
2543 break;
2544 case PeerConnectionInterface::kClosed:
2545 create_sdp_observer->OnFailure(RTCError(
2546 RTCErrorType::INVALID_STATE,
2547 "SetLocalDescription called when PeerConnection is closed."));
2548 break;
2549 }
2550 });
2551}
2552
Henrik Boströma3728d32019-10-28 11:09:492553void PeerConnection::DoSetLocalDescription(
2554 std::unique_ptr<SessionDescriptionInterface> desc,
2555 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2556 RTC_DCHECK_RUN_ON(signaling_thread());
2557 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-17 01:08:422558
nisse7ce109a2017-01-31 08:57:562559 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252560 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362561 return;
2562 }
Steve Anton8a006912017-12-04 23:25:562563
henrike@webrtc.org28e20752013-07-10 00:45:362564 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:032565 PostSetSessionDescriptionFailure(
2566 observer,
2567 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362568 return;
2569 }
Steve Anton8d3444d2017-10-20 22:30:512570
Steve Anton80dd7b52018-02-17 01:08:422571 // If a session error has occurred the PeerConnection is in a possibly
2572 // inconsistent state so fail right away.
2573 if (session_error() != SessionError::kNone) {
2574 std::string error_message = GetSessionErrorMsg();
2575 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032576 PostSetSessionDescriptionFailure(
2577 observer,
2578 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422579 return;
2580 }
Steve Anton8d3444d2017-10-20 22:30:512581
Eldar Rello5ab79e62019-10-09 15:29:442582 // For SLD we support only explicit rollback.
2583 if (desc->GetType() == SdpType::kRollback) {
2584 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 20:01:312585 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 15:29:442586 if (error.ok()) {
2587 PostSetSessionDescriptionSuccess(observer);
2588 } else {
2589 PostSetSessionDescriptionFailure(observer, std::move(error));
2590 }
2591 } else {
2592 PostSetSessionDescriptionFailure(
2593 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2594 "Rollback not supported in Plan B"));
2595 }
2596 return;
2597 }
2598
Steve Anton80dd7b52018-02-17 01:08:422599 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2600 if (!error.ok()) {
2601 std::string error_message = GetSetDescriptionErrorMessage(
2602 cricket::CS_LOCAL, desc->GetType(), error);
2603 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032604 PostSetSessionDescriptionFailure(
2605 observer,
2606 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422607 return;
2608 }
2609
2610 // Grab the description type before moving ownership to ApplyLocalDescription,
2611 // which may destroy it before returning.
2612 const SdpType type = desc->GetType();
2613
2614 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:562615 // |desc| may be destroyed at this point.
2616
2617 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422618 // If ApplyLocalDescription fails, the PeerConnection could be in an
2619 // inconsistent state, so act conservatively here and set the session error
2620 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2621 SetSessionError(SessionError::kContent, error.message());
2622 std::string error_message =
2623 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2624 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032625 PostSetSessionDescriptionFailure(
2626 observer,
2627 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:512628 return;
2629 }
Steve Anton8a006912017-12-04 23:25:562630 RTC_DCHECK(local_description());
2631
2632 PostSetSessionDescriptionSuccess(observer);
2633
Steve Antonad182762018-09-05 20:22:402634 // MaybeStartGathering needs to be called after posting
2635 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2636 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:562637 transport_controller_->MaybeStartGathering();
2638
Steve Antona3a92c22017-12-07 18:27:412639 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562640 // TODO(deadbeef): We already had to hop to the network thread for
2641 // MaybeStartGathering...
2642 network_thread()->Invoke<void>(
2643 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2644 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302645 // Make UMA notes about what was agreed to.
2646 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562647 }
Guido Urdaneta70c2db12019-04-16 10:24:142648
2649 if (IsUnifiedPlan()) {
2650 bool was_negotiation_needed = is_negotiation_needed_;
2651 UpdateNegotiationNeeded();
2652 if (signaling_state() == kStable && was_negotiation_needed &&
2653 is_negotiation_needed_) {
2654 Observer()->OnRenegotiationNeeded();
2655 }
2656 }
2657
Qingsi Wang1ba5dec2019-08-19 18:57:172658 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 23:25:562659}
2660
2661RTCError PeerConnection::ApplyLocalDescription(
2662 std::unique_ptr<SessionDescriptionInterface> desc) {
2663 RTC_DCHECK_RUN_ON(signaling_thread());
2664 RTC_DCHECK(desc);
2665
henrike@webrtc.org28e20752013-07-10 00:45:362666 // Update stats here so that we have the most recent stats for tracks and
2667 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262668 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562669
Steve Antondcc3c022017-12-23 00:02:542670 // Take a reference to the old local description since it's used below to
2671 // compare against the new local description. When setting the new local
2672 // description, grab ownership of the replaced session description in case it
2673 // is the same as |old_local_description|, to keep it alive for the duration
2674 // of the method.
2675 const SessionDescriptionInterface* old_local_description =
2676 local_description();
2677 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352678 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512679 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542680 replaced_local_description = pending_local_description_
2681 ? std::move(pending_local_description_)
2682 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562683 current_local_description_ = std::move(desc);
2684 pending_local_description_ = nullptr;
2685 current_remote_description_ = std::move(pending_remote_description_);
2686 } else {
Steve Antondcc3c022017-12-23 00:02:542687 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562688 pending_local_description_ = std::move(desc);
2689 }
2690 // The session description to apply now must be accessed by
2691 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442692 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112693
Amit Hilbuche2a284d2019-03-05 20:36:312694 // Report statistics about any use of simulcast.
2695 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2696 *local_description()->description());
2697
Bjorn Mellem175aa2e2018-11-08 19:23:222698 if (!is_caller_) {
2699 if (remote_description()) {
2700 // Remote description was applied first, so this PC is the callee.
2701 is_caller_ = false;
2702 } else {
2703 // Local description is applied first, so this PC is the caller.
2704 is_caller_ = true;
2705 }
2706 }
2707
Zhi Huange830e682018-03-30 17:48:352708 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2709 if (!error.ok()) {
2710 return error;
2711 }
2712
Steve Antondcc3c022017-12-23 00:02:542713 if (IsUnifiedPlan()) {
2714 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482715 cricket::CS_LOCAL, *local_description(), old_local_description,
2716 remote_description());
Steve Anton8a006912017-12-04 23:25:562717 if (!error.ok()) {
2718 return error;
2719 }
Steve Anton0f5400a2018-07-17 21:25:362720 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2721 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:422722 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:402723 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2724 // Note that code paths that don't set MID won't be able to use
2725 // information about DTLS transports.
2726 if (transceiver->mid()) {
2727 auto dtls_transport =
2728 LookupDtlsTransportByMidInternal(*transceiver->mid());
2729 transceiver->internal()->sender_internal()->set_transport(
2730 dtls_transport);
2731 transceiver->internal()->receiver_internal()->set_transport(
2732 dtls_transport);
2733 }
2734
Steve Antondcc3c022017-12-23 00:02:542735 const ContentInfo* content =
2736 FindMediaSectionForTransceiver(transceiver, local_description());
2737 if (!content) {
2738 continue;
2739 }
2740 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362741 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2742 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542743 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362744 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2745 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2746 // "recvonly", process the removal of a remote track for the media
2747 // description, given transceiver, removeList, and muteTracks.
2748 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2749 (transceiver->internal()->fired_direction() &&
2750 RtpTransceiverDirectionHasRecv(
2751 *transceiver->internal()->fired_direction()))) {
2752 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2753 &removed_streams);
2754 }
2755 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2756 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542757 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362758 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542759 }
Steve Anton0f5400a2018-07-17 21:25:362760 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162761 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:422762 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162763 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362764 }
Mirko Bonadei739baf02019-01-27 16:29:422765 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162766 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542767 }
2768 } else {
Zhi Huange830e682018-03-30 17:48:352769 // Media channels will be created only when offer is set. These may use new
2770 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542771 if (type == SdpType::kOffer) {
2772 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2773 // description is applied. Restore back to old description.
2774 RTCError error = CreateChannels(*local_description()->description());
2775 if (!error.ok()) {
2776 return error;
2777 }
2778 }
Steve Antondcc3c022017-12-23 00:02:542779 // Remove unused channels if MediaContentDescription is rejected.
2780 RemoveUnusedChannels(local_description()->description());
2781 }
Steve Anton8a006912017-12-04 23:25:562782
Zhi Huange830e682018-03-30 17:48:352783 error = UpdateSessionState(type, cricket::CS_LOCAL,
2784 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562785 if (!error.ok()) {
2786 return error;
2787 }
Steve Antondcc3c022017-12-23 00:02:542788
Steve Anton8a006912017-12-04 23:25:562789 if (remote_description()) {
2790 // Now that we have a local description, we can push down remote candidates.
2791 UseCandidatesInSessionDescription(remote_description());
2792 }
2793
2794 pending_ice_restarts_.clear();
2795 if (session_error() != SessionError::kNone) {
2796 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2797 }
2798
deadbeefab9b2d12015-10-14 18:33:112799 // If setting the description decided our SSL role, allocate any necessary
2800 // SCTP sids.
2801 rtc::SSLRole role;
Harald Alvestrand05e4d082019-12-03 13:04:212802 if (DataChannel::IsSctpLike(data_channel_type()) && GetSctpSslRole(&role)) {
Harald Alvestrand00cf34c2019-12-02 08:56:022803 data_channel_controller_.AllocateSctpSids(role);
deadbeefab9b2d12015-10-14 18:33:112804 }
2805
Steve Antond3679212018-01-18 01:41:022806 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 16:29:422807 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-18 01:41:022808 const ContentInfo* content =
2809 FindMediaSectionForTransceiver(transceiver, local_description());
2810 if (!content) {
2811 continue;
2812 }
Amit Hilbuchbcd39d42019-01-26 01:13:562813 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2814 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 18:32:272815 // 0 is a special value meaning "this sender has no associated send
2816 // stream". Need to call this so the sender won't attempt to configure
2817 // a no longer existing stream and run into DCHECKs in the lower
2818 // layers.
2819 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-26 01:13:562820 } else {
2821 // Get the StreamParams from the channel which could generate SSRCs.
2822 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:382823 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-26 01:13:562824 streams[0].stream_ids());
2825 transceiver->internal()->sender_internal()->SetSsrc(
2826 streams[0].first_ssrc());
Steve Antond3679212018-01-18 01:41:022827 }
2828 }
2829 } else {
2830 // Plan B semantics.
2831
Steve Antondcc3c022017-12-23 00:02:542832 // Update state and SSRC of local MediaStreams and DataChannels based on the
2833 // local session description.
2834 const cricket::ContentInfo* audio_content =
2835 GetFirstAudioContent(local_description()->description());
2836 if (audio_content) {
2837 if (audio_content->rejected) {
2838 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2839 } else {
2840 const cricket::AudioContentDescription* audio_desc =
2841 audio_content->media_description()->as_audio();
2842 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2843 }
deadbeeffaac4972015-11-12 23:33:072844 }
deadbeefab9b2d12015-10-14 18:33:112845
Steve Antondcc3c022017-12-23 00:02:542846 const cricket::ContentInfo* video_content =
2847 GetFirstVideoContent(local_description()->description());
2848 if (video_content) {
2849 if (video_content->rejected) {
2850 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2851 } else {
2852 const cricket::VideoContentDescription* video_desc =
2853 video_content->media_description()->as_video();
2854 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2855 }
deadbeeffaac4972015-11-12 23:33:072856 }
deadbeefab9b2d12015-10-14 18:33:112857 }
2858
2859 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442860 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112861 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 11:36:162862 const cricket::RtpDataContentDescription* rtp_data_desc =
2863 data_content->media_description()->as_rtp_data();
2864 // rtp_data_desc will be null if this is an SCTP description.
2865 if (rtp_data_desc) {
Harald Alvestrand05e4d082019-12-03 13:04:212866 data_channel_controller_.UpdateLocalRtpDataChannels(
2867 rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 18:33:112868 }
2869 }
2870
Henrik Boström79b69802019-07-18 09:16:562871 if (type == SdpType::kAnswer &&
2872 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2873 *current_local_description_)) {
2874 local_ice_credentials_to_replace_->ClearIceCredentials();
2875 }
2876
Steve Anton8a006912017-12-04 23:25:562877 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362878}
2879
Steve Anton06817cd2018-12-18 23:55:302880// The SDP parser used to populate these values by default for the 'content
2881// name' if an a=mid line was absent.
2882static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2883 switch (media_type) {
2884 case cricket::MEDIA_TYPE_AUDIO:
2885 return cricket::CN_AUDIO;
2886 case cricket::MEDIA_TYPE_VIDEO:
2887 return cricket::CN_VIDEO;
2888 case cricket::MEDIA_TYPE_DATA:
2889 return cricket::CN_DATA;
2890 }
2891 RTC_NOTREACHED();
2892 return "";
2893}
2894
2895void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 18:44:532896 cricket::SessionDescription* new_remote_description) {
2897 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 18:35:452898 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 23:55:302899 const cricket::ContentInfos& local_contents =
2900 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:452901 : no_infos);
Steve Antond7180cc2019-02-07 18:44:532902 const cricket::ContentInfos& remote_contents =
2903 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:452904 : no_infos);
Steve Antond7180cc2019-02-07 18:44:532905 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2906 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 23:55:302907 if (!content.name.empty()) {
2908 continue;
2909 }
Amit Hilbuchae3df542019-01-07 20:13:082910 std::string new_mid;
Steve Anton06817cd2018-12-18 23:55:302911 absl::string_view source_explanation;
2912 if (IsUnifiedPlan()) {
2913 if (i < local_contents.size()) {
2914 new_mid = local_contents[i].name;
2915 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 18:44:532916 } else if (i < remote_contents.size()) {
2917 new_mid = remote_contents[i].name;
2918 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 23:55:302919 } else {
Amit Hilbuchae3df542019-01-07 20:13:082920 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 23:55:302921 source_explanation = "generated just now";
2922 }
2923 } else {
Amit Hilbuchae3df542019-01-07 20:13:082924 new_mid = std::string(
2925 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 23:55:302926 source_explanation = "to match pre-existing behavior";
2927 }
Steve Antond7180cc2019-02-07 18:44:532928 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 20:13:082929 content.name = new_mid;
Steve Antond7180cc2019-02-07 18:44:532930 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 23:55:302931 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2932 << " is missing an a=mid line. Filling in the value '"
2933 << new_mid << "' " << source_explanation << ".";
2934 }
2935}
2936
henrike@webrtc.org28e20752013-07-10 00:45:362937void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072938 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 11:09:492939 SessionDescriptionInterface* desc_ptr) {
2940 RTC_DCHECK_RUN_ON(signaling_thread());
2941 // Chain this operation. If asynchronous operations are pending on the chain,
2942 // this operation will be queued to be invoked, otherwise the contents of the
2943 // lambda will execute immediately.
2944 operations_chain_->ChainOperation(
2945 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2946 observer_refptr =
2947 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2948 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2949 std::function<void()> operations_chain_callback) mutable {
2950 // Abort early if |this_weak_ptr| is no longer valid.
2951 if (!this_weak_ptr) {
2952 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2953 // inform the |observer_refptr| that the operation failed in this
2954 // case.
2955 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2956 // the consistent thing would be to inform the observer here.
2957 operations_chain_callback();
2958 return;
2959 }
2960 this_weak_ptr->DoSetRemoteDescription(
2961 std::move(desc),
2962 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2963 new SetRemoteDescriptionObserverAdapter(
2964 this_weak_ptr.get(), std::move(observer_refptr))));
2965 // DoSetRemoteDescription() is currently implemented as a synchronous
2966 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2967 // the |observer|'s callbacks are invoked asynchronously in a post to
2968 // OnMessage().
2969 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 09:35:502970 // completed here (rather than in OnMessage()). This ensures that
2971 // subsequent offer/answer operations can start immediately (without
2972 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 11:09:492973 operations_chain_callback();
2974 });
Henrik Boström31638672017-11-23 16:48:322975}
2976
2977void PeerConnection::SetRemoteDescription(
2978 std::unique_ptr<SessionDescriptionInterface> desc,
2979 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 22:55:092980 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 11:09:492981 // Chain this operation. If asynchronous operations are pending on the chain,
2982 // this operation will be queued to be invoked, otherwise the contents of the
2983 // lambda will execute immediately.
2984 operations_chain_->ChainOperation(
2985 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2986 desc = std::move(desc)](
2987 std::function<void()> operations_chain_callback) mutable {
2988 // Abort early if |this_weak_ptr| is no longer valid.
2989 if (!this_weak_ptr) {
2990 // For consistency with DoSetRemoteDescription(), we DO inform the
2991 // |observer| that the operation failed in this case.
2992 observer->OnSetRemoteDescriptionComplete(RTCError(
2993 RTCErrorType::INVALID_STATE,
2994 "Failed to set remote offer sdp: failed because the session was "
2995 "shut down"));
2996 operations_chain_callback();
2997 return;
2998 }
2999 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
3000 std::move(observer));
3001 // DoSetRemoteDescription() is currently implemented as a synchronous
3002 // operation. The |observer| will already have been informed that it
3003 // completed, and we can mark this operation as complete without any
3004 // loose ends.
3005 operations_chain_callback();
3006 });
3007}
3008
3009void PeerConnection::DoSetRemoteDescription(
3010 std::unique_ptr<SessionDescriptionInterface> desc,
3011 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
3012 RTC_DCHECK_RUN_ON(signaling_thread());
3013 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:563014
nisse7ce109a2017-01-31 08:57:563015 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:253016 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:363017 return;
3018 }
Steve Anton8a006912017-12-04 23:25:563019
henrike@webrtc.org28e20752013-07-10 00:45:363020 if (!desc) {
Henrik Boström31638672017-11-23 16:48:323021 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:563022 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:363023 return;
3024 }
Steve Anton8d3444d2017-10-20 22:30:513025
Steve Anton80dd7b52018-02-17 01:08:423026 // If a session error has occurred the PeerConnection is in a possibly
3027 // inconsistent state so fail right away.
3028 if (session_error() != SessionError::kNone) {
3029 std::string error_message = GetSessionErrorMsg();
3030 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
3031 observer->OnSetRemoteDescriptionComplete(
3032 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
3033 return;
3034 }
Eldar Rello5ab79e62019-10-09 15:29:443035 if (IsUnifiedPlan()) {
3036 if (configuration_.enable_implicit_rollback) {
3037 if (desc->GetType() == SdpType::kOffer &&
3038 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 20:01:313039 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 15:29:443040 }
3041 }
3042 // Explicit rollback.
3043 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 20:01:313044 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 15:29:443045 return;
3046 }
3047 } else if (desc->GetType() == SdpType::kRollback) {
3048 observer->OnSetRemoteDescriptionComplete(
3049 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
3050 "Rollback not supported in Plan B"));
3051 return;
3052 }
Steve Antonba42e992018-04-09 21:10:013053 if (desc->GetType() == SdpType::kOffer) {
3054 // Report to UMA the format of the received offer.
3055 ReportSdpFormatReceived(*desc);
3056 }
3057
Steve Anton06817cd2018-12-18 23:55:303058 // Handle remote descriptions missing a=mid lines for interop with legacy end
3059 // points.
3060 FillInMissingRemoteMids(desc->description());
3061
Steve Anton80dd7b52018-02-17 01:08:423062 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:063063 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:423064 std::string error_message = GetSetDescriptionErrorMessage(
3065 cricket::CS_REMOTE, desc->GetType(), error);
3066 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:063067 observer->OnSetRemoteDescriptionComplete(
3068 RTCError(error.type(), std::move(error_message)));
3069 return;
3070 }
Steve Anton71439a62018-02-15 19:53:063071
Steve Anton80dd7b52018-02-17 01:08:423072 // Grab the description type before moving ownership to
3073 // ApplyRemoteDescription, which may destroy it before returning.
3074 const SdpType type = desc->GetType();
3075
3076 error = ApplyRemoteDescription(std::move(desc));
3077 // |desc| may be destroyed at this point.
3078
3079 if (!error.ok()) {
3080 // If ApplyRemoteDescription fails, the PeerConnection could be in an
3081 // inconsistent state, so act conservatively here and set the session error
3082 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
3083 SetSessionError(SessionError::kContent, error.message());
3084 std::string error_message =
3085 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
3086 RTC_LOG(LS_ERROR) << error_message;
3087 observer->OnSetRemoteDescriptionComplete(
3088 RTCError(error.type(), std::move(error_message)));
3089 return;
3090 }
3091 RTC_DCHECK(remote_description());
3092
3093 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:563094 // TODO(deadbeef): We already had to hop to the network thread for
3095 // MaybeStartGathering...
3096 network_thread()->Invoke<void>(
3097 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3098 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:003099 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:303100 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:563101 }
3102
Guido Urdaneta70c2db12019-04-16 10:24:143103 if (IsUnifiedPlan()) {
3104 bool was_negotiation_needed = is_negotiation_needed_;
3105 UpdateNegotiationNeeded();
3106 if (signaling_state() == kStable && was_negotiation_needed &&
3107 is_negotiation_needed_) {
3108 Observer()->OnRenegotiationNeeded();
3109 }
3110 }
3111
Steve Anton8a006912017-12-04 23:25:563112 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 18:57:173113 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 23:25:563114}
3115
3116RTCError PeerConnection::ApplyRemoteDescription(
3117 std::unique_ptr<SessionDescriptionInterface> desc) {
3118 RTC_DCHECK_RUN_ON(signaling_thread());
3119 RTC_DCHECK(desc);
3120
henrike@webrtc.org28e20752013-07-10 00:45:363121 // Update stats here so that we have the most recent stats for tracks and
3122 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:263123 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:563124
Steve Antondcc3c022017-12-23 00:02:543125 // Take a reference to the old remote description since it's used below to
3126 // compare against the new remote description. When setting the new remote
3127 // description, grab ownership of the replaced session description in case it
3128 // is the same as |old_remote_description|, to keep it alive for the duration
3129 // of the method.
Steve Anton8a006912017-12-04 23:25:563130 const SessionDescriptionInterface* old_remote_description =
3131 remote_description();
Steve Anton8a006912017-12-04 23:25:563132 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:513133 SdpType type = desc->GetType();
3134 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:563135 replaced_remote_description = pending_remote_description_
3136 ? std::move(pending_remote_description_)
3137 : std::move(current_remote_description_);
3138 current_remote_description_ = std::move(desc);
3139 pending_remote_description_ = nullptr;
3140 current_local_description_ = std::move(pending_local_description_);
3141 } else {
3142 replaced_remote_description = std::move(pending_remote_description_);
3143 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:363144 }
Steve Anton8a006912017-12-04 23:25:563145 // The session description to apply now must be accessed by
3146 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:443147 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:363148
Amit Hilbuche2a284d2019-03-05 20:36:313149 // Report statistics about any use of simulcast.
3150 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
3151 *remote_description()->description());
3152
Zhi Huange830e682018-03-30 17:48:353153 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
3154 if (!error.ok()) {
3155 return error;
3156 }
Steve Anton8a006912017-12-04 23:25:563157 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:543158 if (IsUnifiedPlan()) {
3159 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:483160 cricket::CS_REMOTE, *remote_description(), local_description(),
3161 old_remote_description);
Steve Anton8a006912017-12-04 23:25:563162 if (!error.ok()) {
3163 return error;
3164 }
Steve Antondcc3c022017-12-23 00:02:543165 } else {
Zhi Huange830e682018-03-30 17:48:353166 // Media channels will be created only when offer is set. These may use new
3167 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:543168 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:353169 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:543170 // description is applied. Restore back to old description.
3171 RTCError error = CreateChannels(*remote_description()->description());
3172 if (!error.ok()) {
3173 return error;
3174 }
3175 }
Steve Antondcc3c022017-12-23 00:02:543176 // Remove unused channels if MediaContentDescription is rejected.
3177 RemoveUnusedChannels(remote_description()->description());
3178 }
Steve Anton8a006912017-12-04 23:25:563179
Zhi Huange830e682018-03-30 17:48:353180 // NOTE: Candidates allocation will be initiated only when
3181 // SetLocalDescription is called.
3182 error = UpdateSessionState(type, cricket::CS_REMOTE,
3183 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:563184 if (!error.ok()) {
3185 return error;
3186 }
3187
3188 if (local_description() &&
3189 !UseCandidatesInSessionDescription(remote_description())) {
3190 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3191 }
3192
3193 if (old_remote_description) {
3194 for (const cricket::ContentInfo& content :
3195 old_remote_description->description()->contents()) {
3196 // Check if this new SessionDescription contains new ICE ufrag and
3197 // password that indicates the remote peer requests an ICE restart.
3198 // TODO(deadbeef): When we start storing both the current and pending
3199 // remote description, this should reset pending_ice_restarts and compare
3200 // against the current description.
3201 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3202 content.name)) {
Steve Anton3828c062017-12-06 18:34:513203 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:563204 pending_ice_restarts_.insert(content.name);
3205 }
3206 } else {
3207 // We retain all received candidates only if ICE is not restarted.
3208 // When ICE is restarted, all previous candidates belong to an old
3209 // generation and should not be kept.
3210 // TODO(deadbeef): This goes against the W3C spec which says the remote
3211 // description should only contain candidates from the last set remote
3212 // description plus any candidates added since then. We should remove
3213 // this once we're sure it won't break anything.
3214 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3215 old_remote_description, content.name, mutable_remote_description());
3216 }
3217 }
3218 }
3219
3220 if (session_error() != SessionError::kNone) {
3221 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3222 }
3223
3224 // Set the the ICE connection state to connecting since the connection may
3225 // become writable with peer reflexive candidates before any remote candidate
3226 // is signaled.
3227 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3228 // is to have a new signal the indicates a change in checking state from the
3229 // transport and expose a new checking() member from transport that can be
3230 // read to determine the current checking state. The existing SignalConnecting
3231 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:413232 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:173233 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:563234 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3235 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3236 }
3237
deadbeefab9b2d12015-10-14 18:33:113238 // If setting the description decided our SSL role, allocate any necessary
3239 // SCTP sids.
3240 rtc::SSLRole role;
Harald Alvestrand05e4d082019-12-03 13:04:213241 if (DataChannel::IsSctpLike(data_channel_type()) && GetSctpSslRole(&role)) {
Harald Alvestrand00cf34c2019-12-02 08:56:023242 data_channel_controller_.AllocateSctpSids(role);
deadbeefab9b2d12015-10-14 18:33:113243 }
3244
Steve Antondcc3c022017-12-23 00:02:543245 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:423246 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:183247 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:363248 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:133249 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:183250 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 16:29:423251 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:543252 const ContentInfo* content =
3253 FindMediaSectionForTransceiver(transceiver, remote_description());
3254 if (!content) {
3255 continue;
3256 }
3257 const MediaContentDescription* media_desc = content->media_description();
3258 RtpTransceiverDirection local_direction =
3259 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 10:06:023260 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3261 // RTCSessionDescription: Set the associated remote streams given
3262 // transceiver.[[Receiver]], msids, addList, and removeList".
3263 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3264 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3265 std::vector<std::string> stream_ids;
3266 if (!media_desc->streams().empty()) {
3267 // The remote description has signaled the stream IDs.
3268 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-11 01:15:203269 }
Eldar Rello353a7182019-11-25 16:49:443270 transceiver_stable_states_by_transceivers_[transceiver]
3271 .SetRemoteStreamIdsIfUnset(transceiver->receiver()->stream_ids());
3272
Henrik Boströmafa07dd2018-12-20 10:06:023273 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3274 << " (" << GetStreamIdsString(stream_ids) << ").";
3275 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3276 stream_ids, &added_streams,
3277 &removed_streams);
3278 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3279 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3280 // and transceiver's current direction is neither sendrecv nor recvonly,
3281 // process the addition of a remote track for the media description.
3282 if (!transceiver->fired_direction() ||
3283 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3284 RTC_LOG(LS_INFO)
3285 << "Processing the addition of a remote track for MID="
3286 << content->name << ".";
3287 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 10:25:053288 }
Steve Antondcc3c022017-12-23 00:02:543289 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403290 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 21:25:363291 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3292 // removal of a remote track for the media description, given transceiver,
3293 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:543294 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:363295 (transceiver->fired_direction() &&
3296 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3297 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3298 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:543299 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403300 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 21:25:363301 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:403302 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 21:25:363303 // the following steps:
Steve Antondcc3c022017-12-23 00:02:543304 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 09:39:403305 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 21:25:363306 // direction.
Steve Antondcc3c022017-12-23 00:02:543307 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 09:39:403308 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3309 if (transceiver->mid()) {
3310 auto dtls_transport =
3311 LookupDtlsTransportByMidInternal(*transceiver->mid());
3312 transceiver->internal()->sender_internal()->set_transport(
3313 dtls_transport);
3314 transceiver->internal()->receiver_internal()->set_transport(
3315 dtls_transport);
3316 }
Steve Antondcc3c022017-12-23 00:02:543317 }
Harald Alvestrand4a7b3ac2019-01-17 09:39:403318 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 21:25:363319 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:543320 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:233321 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3322 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:543323 transceiver->Stop();
3324 }
Seth Hampson2f0d7022018-02-20 19:54:423325 if (!content->rejected &&
3326 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 18:16:333327 if (!media_desc->streams().empty() &&
3328 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 23:23:053329 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3330 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3331 } else {
3332 transceiver->internal()
3333 ->receiver_internal()
3334 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 19:54:423335 }
Steve Antond3679212018-01-18 01:41:023336 }
Steve Antondcc3c022017-12-23 00:02:543337 }
Steve Antonc49bcd92018-02-14 22:28:133338 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:163339 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 16:29:423340 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:163341 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:163342 observer->OnTrack(transceiver);
3343 observer->OnAddTrack(transceiver->receiver(),
3344 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:203345 }
Mirko Bonadei739baf02019-01-27 16:29:423346 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163347 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:133348 }
Mirko Bonadei739baf02019-01-27 16:29:423349 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163350 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:183351 }
Mirko Bonadei739baf02019-01-27 16:29:423352 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:163353 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:183354 }
Steve Antondcc3c022017-12-23 00:02:543355 }
3356
Henrik Boströmfdb92012017-11-09 18:55:443357 const cricket::ContentInfo* audio_content =
3358 GetFirstAudioContent(remote_description()->description());
3359 const cricket::ContentInfo* video_content =
3360 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403361 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:443362 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403363 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:443364 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 11:36:163365 const cricket::RtpDataContentDescription* rtp_data_desc =
3366 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:403367
3368 // Check if the descriptions include streams, just in case the peer supports
3369 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:443370 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:403371 (audio_desc && !audio_desc->streams().empty()) ||
3372 (video_desc && !video_desc->streams().empty())) {
3373 remote_peer_supports_msid_ = true;
3374 }
deadbeefab9b2d12015-10-14 18:33:113375
3376 // We wait to signal new streams until we finish processing the description,
3377 // since only at that point will new streams have all their tracks.
3378 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3379
Steve Antondcc3c022017-12-23 00:02:543380 if (!IsUnifiedPlan()) {
3381 // TODO(steveanton): When removing RTP senders/receivers in response to a
3382 // rejected media section, there is some cleanup logic that expects the
3383 // voice/ video channel to still be set. But in this method the voice/video
3384 // channel would have been destroyed by the SetRemoteDescription caller
3385 // above so the cleanup that relies on them fails to run. The RemoveSenders
3386 // calls should be moved to right before the DestroyChannel calls to fix
3387 // this.
Steve Anton8d3444d2017-10-20 22:30:513388
Steve Antondcc3c022017-12-23 00:02:543389 // Find all audio rtp streams and create corresponding remote AudioTracks
3390 // and MediaStreams.
3391 if (audio_content) {
3392 if (audio_content->rejected) {
3393 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3394 } else {
3395 bool default_audio_track_needed =
3396 !remote_peer_supports_msid_ &&
3397 RtpTransceiverDirectionHasSend(audio_desc->direction());
3398 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3399 default_audio_track_needed, audio_desc->type(),
3400 new_streams);
3401 }
deadbeeffaac4972015-11-12 23:33:073402 }
deadbeefab9b2d12015-10-14 18:33:113403
Steve Antondcc3c022017-12-23 00:02:543404 // Find all video rtp streams and create corresponding remote VideoTracks
3405 // and MediaStreams.
3406 if (video_content) {
3407 if (video_content->rejected) {
3408 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3409 } else {
3410 bool default_video_track_needed =
3411 !remote_peer_supports_msid_ &&
3412 RtpTransceiverDirectionHasSend(video_desc->direction());
3413 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3414 default_video_track_needed, video_desc->type(),
3415 new_streams);
3416 }
deadbeeffaac4972015-11-12 23:33:073417 }
deadbeefab9b2d12015-10-14 18:33:113418
Harald Alvestrand5fc28b12019-05-13 11:36:163419 // If this is an RTP data transport, update the DataChannels with the
3420 // information from the remote peer.
3421 if (rtp_data_desc) {
Harald Alvestrand05e4d082019-12-03 13:04:213422 data_channel_controller_.UpdateRemoteRtpDataChannels(
3423 GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 18:33:113424 }
deadbeefab9b2d12015-10-14 18:33:113425
Steve Antondcc3c022017-12-23 00:02:543426 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:163427 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:543428 for (size_t i = 0; i < new_streams->count(); ++i) {
3429 MediaStreamInterface* new_stream = new_streams->at(i);
3430 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163431 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:543432 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3433 }
deadbeefab9b2d12015-10-14 18:33:113434
Steve Antondcc3c022017-12-23 00:02:543435 UpdateEndedRemoteMediaStreams();
3436 }
deadbeefab9b2d12015-10-14 18:33:113437
Henrik Boström79b69802019-07-18 09:16:563438 if (type == SdpType::kAnswer &&
3439 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3440 *current_local_description_)) {
3441 local_ice_credentials_to_replace_->ClearIceCredentials();
3442 }
3443
Steve Anton8a006912017-12-04 23:25:563444 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:333445}
3446
Henrik Boströmafa07dd2018-12-20 10:06:023447void PeerConnection::SetAssociatedRemoteStreams(
3448 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3449 const std::vector<std::string>& stream_ids,
3450 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3451 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3452 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3453 for (const std::string& stream_id : stream_ids) {
3454 rtc::scoped_refptr<MediaStreamInterface> stream =
3455 remote_streams_->find(stream_id);
3456 if (!stream) {
3457 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3458 MediaStream::Create(stream_id));
3459 remote_streams_->AddStream(stream);
3460 added_streams->push_back(stream);
3461 }
3462 media_streams.push_back(stream);
3463 }
3464 // Special case: "a=msid" missing, use random stream ID.
3465 if (media_streams.empty() &&
3466 !(remote_description()->description()->msid_signaling() &
3467 cricket::kMsidSignalingMediaSection)) {
3468 if (!missing_msid_default_stream_) {
3469 missing_msid_default_stream_ = MediaStreamProxy::Create(
3470 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3471 added_streams->push_back(missing_msid_default_stream_);
3472 }
3473 media_streams.push_back(missing_msid_default_stream_);
3474 }
3475 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3476 receiver->streams();
3477 // SetStreams() will add/remove the receiver's track to/from the streams. This
3478 // differs from the spec - the spec uses an "addList" and "removeList" to
3479 // update the stream-track relationships in a later step. We do this earlier,
3480 // changing the order of things, but the end-result is the same.
3481 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3482 // instead. https://crbug.com/webrtc/9480
3483 receiver->SetStreams(media_streams);
3484 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3485}
3486
Steve Anton0f5400a2018-07-17 21:25:363487void PeerConnection::ProcessRemovalOfRemoteTrack(
3488 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3489 transceiver,
3490 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3491 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3492 RTC_DCHECK(transceiver->mid());
3493 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3494 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 10:06:023495 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 21:25:363496 transceiver->internal()->receiver_internal()->streams();
3497 // This will remove the remote track from the streams.
3498 transceiver->internal()->receiver_internal()->set_stream_ids({});
3499 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 10:06:023500 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3501}
3502
3503void PeerConnection::RemoveRemoteStreamsIfEmpty(
3504 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3505 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3506 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3507 // streams, see if the stream was removed by checking if this was the last
3508 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 16:29:423509 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 10:06:023510 if (remote_stream->GetAudioTracks().empty() &&
3511 remote_stream->GetVideoTracks().empty()) {
3512 remote_streams_->RemoveStream(remote_stream);
3513 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 21:25:363514 }
3515 }
3516}
3517
Steve Antondcc3c022017-12-23 00:02:543518RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3519 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:483520 const SessionDescriptionInterface& new_session,
3521 const SessionDescriptionInterface* old_local_description,
3522 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:543523 RTC_DCHECK(IsUnifiedPlan());
3524
Steve Anton7464fca2018-01-19 19:10:373525 const cricket::ContentGroup* bundle_group = nullptr;
3526 if (new_session.GetType() == SdpType::kOffer) {
3527 auto bundle_group_or_error =
3528 GetEarlyBundleGroup(*new_session.description());
3529 if (!bundle_group_or_error.ok()) {
3530 return bundle_group_or_error.MoveError();
3531 }
3532 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:543533 }
Steve Antondcc3c022017-12-23 00:02:543534
Steve Antondcc3c022017-12-23 00:02:543535 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:543536 for (size_t i = 0; i < new_contents.size(); ++i) {
3537 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:543538 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 20:13:083539 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-23 00:02:543540 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3541 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:483542 const cricket::ContentInfo* old_local_content = nullptr;
3543 if (old_local_description &&
3544 i < old_local_description->description()->contents().size()) {
3545 old_local_content =
3546 &old_local_description->description()->contents()[i];
3547 }
3548 const cricket::ContentInfo* old_remote_content = nullptr;
3549 if (old_remote_description &&
3550 i < old_remote_description->description()->contents().size()) {
3551 old_remote_content =
3552 &old_remote_description->description()->contents()[i];
3553 }
Steve Antondcc3c022017-12-23 00:02:543554 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:483555 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3556 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:543557 if (!transceiver_or_error.ok()) {
3558 return transceiver_or_error.MoveError();
3559 }
3560 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:543561 RTCError error =
3562 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3563 if (!error.ok()) {
3564 return error;
3565 }
3566 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:233567 if (GetDataMid() && new_content.name != *GetDataMid()) {
3568 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:233569 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3570 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:233571 continue;
3572 }
3573 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3574 if (!error.ok()) {
3575 return error;
3576 }
Steve Antondcc3c022017-12-23 00:02:543577 } else {
3578 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3579 "Unknown section type.");
3580 }
3581 }
3582
3583 return RTCError::OK();
3584}
3585
3586RTCError PeerConnection::UpdateTransceiverChannel(
3587 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3588 transceiver,
3589 const cricket::ContentInfo& content,
3590 const cricket::ContentGroup* bundle_group) {
3591 RTC_DCHECK(IsUnifiedPlan());
3592 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-14 00:26:053593 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:543594 if (content.rejected) {
3595 if (channel) {
3596 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:053597 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:543598 }
3599 } else {
3600 if (!channel) {
Steve Anton69470252018-02-09 19:43:083601 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:353602 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543603 } else {
Steve Anton69470252018-02-09 19:43:083604 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:353605 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:543606 }
3607 if (!channel) {
3608 LOG_AND_RETURN_ERROR(
3609 RTCErrorType::INTERNAL_ERROR,
3610 "Failed to create channel for mid=" + content.name);
3611 }
3612 transceiver->internal()->SetChannel(channel);
3613 }
3614 }
3615 return RTCError::OK();
3616}
3617
Steve Antonfa2260d2017-12-29 00:38:233618RTCError PeerConnection::UpdateDataChannel(
3619 cricket::ContentSource source,
3620 const cricket::ContentInfo& content,
3621 const cricket::ContentGroup* bundle_group) {
Harald Alvestrand05e4d082019-12-03 13:04:213622 if (data_channel_type() == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:403623 // If data channels are disabled, ignore this media section. CreateAnswer
3624 // will take care of rejecting it.
3625 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:233626 }
3627 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 17:44:593628 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Harald Alvestrand408cb4b2019-11-16 11:09:083629 DestroyDataChannelTransport();
Steve Antonfa2260d2017-12-29 00:38:233630 } else {
Harald Alvestrand00cf34c2019-12-02 08:56:023631 if (!data_channel_controller_.rtp_data_channel() &&
3632 !data_channel_controller_.data_channel_transport()) {
Bjorn A Mellemb689af42019-08-21 17:44:593633 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 17:48:353634 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:233635 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3636 "Failed to create data channel.");
3637 }
3638 }
3639 if (source == cricket::CS_REMOTE) {
3640 const MediaContentDescription* data_desc = content.media_description();
3641 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
Harald Alvestrand05e4d082019-12-03 13:04:213642 data_channel_controller_.UpdateRemoteRtpDataChannels(
3643 GetActiveStreams(data_desc));
Steve Antonfa2260d2017-12-29 00:38:233644 }
3645 }
3646 }
3647 return RTCError::OK();
3648}
3649
Amit Hilbuchbcd39d42019-01-26 01:13:563650// This method will extract any send encodings that were sent by the remote
3651// connection. This is currently only relevant for Simulcast scenario (where
3652// the number of layers may be communicated by the server).
3653static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3654 const MediaContentDescription& desc) {
3655 if (!desc.HasSimulcast()) {
3656 return {};
3657 }
3658 std::vector<RtpEncodingParameters> result;
3659 const SimulcastDescription& simulcast = desc.simulcast_description();
3660
3661 // This is a remote description, the parameters we are after should appear
3662 // as receive streams.
3663 for (const auto& alternatives : simulcast.receive_layers()) {
3664 RTC_DCHECK(!alternatives.empty());
3665 // There is currently no way to specify or choose from alternatives.
3666 // We will always use the first alternative, which is the most preferred.
3667 const SimulcastLayer& layer = alternatives[0];
3668 RtpEncodingParameters parameters;
3669 parameters.rid = layer.rid;
3670 parameters.active = !layer.is_paused;
3671 result.push_back(parameters);
3672 }
3673
3674 return result;
3675}
3676
3677static RTCError UpdateSimulcastLayerStatusInSender(
3678 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 20:49:223679 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563680 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193681 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223682 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:563683
3684 // The simulcast envelope cannot be changed, only the status of the streams.
3685 // So we will iterate over the send encodings rather than the layers.
3686 for (RtpEncodingParameters& encoding : parameters.encodings) {
3687 auto iter = std::find_if(layers.begin(), layers.end(),
3688 [&encoding](const SimulcastLayer& layer) {
3689 return layer.rid == encoding.rid;
3690 });
3691 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 20:49:223692 if (iter == layers.end()) {
3693 disabled_layers.push_back(encoding.rid);
3694 continue;
3695 }
3696
3697 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-26 01:13:563698 }
3699
Amit Hilbuch619b2942019-02-26 23:55:193700 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 20:49:223701 if (result.ok()) {
3702 result = sender->DisableEncodingLayers(disabled_layers);
3703 }
3704
3705 return result;
Amit Hilbuchbcd39d42019-01-26 01:13:563706}
3707
Amit Hilbuchaabd0362019-03-01 21:14:463708static bool SimulcastIsRejected(
3709 const ContentInfo* local_content,
3710 const MediaContentDescription& answer_media_desc) {
3711 bool simulcast_offered = local_content &&
3712 local_content->media_description() &&
3713 local_content->media_description()->HasSimulcast();
3714 bool simulcast_answered = answer_media_desc.HasSimulcast();
3715 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3716 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3717 return simulcast_offered && (!simulcast_answered || !rids_supported);
3718}
3719
Amit Hilbuch2297d332019-02-19 20:49:223720static RTCError DisableSimulcastInSender(
3721 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-26 01:13:563722 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 23:55:193723 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 20:49:223724 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-26 01:13:563725 return RTCError::OK();
3726 }
3727
Amit Hilbuch2297d332019-02-19 20:49:223728 std::vector<std::string> disabled_layers;
3729 std::transform(
3730 parameters.encodings.begin() + 1, parameters.encodings.end(),
3731 std::back_inserter(disabled_layers),
3732 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3733 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-26 01:13:563734}
3735
Steve Antondcc3c022017-12-23 00:02:543736RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3737PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:483738 SdpType type,
Steve Antondcc3c022017-12-23 00:02:543739 size_t mline_index,
3740 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:483741 const ContentInfo* old_local_content,
3742 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:543743 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:483744 // If this is an offer then the m= section might be recycled. If the m=
3745 // section is being recycled (defined as: rejected in the current local or
3746 // remote description and not rejected in new description), dissociate the
3747 // currently associated RtpTransceiver by setting its mid property to null,
3748 // and discard the mapping between the transceiver and its m= section index.
3749 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3750 old_remote_content)) {
3751 // We want to dissociate the transceiver that has the rejected mid.
3752 const std::string& old_mid =
3753 (old_local_content && old_local_content->rejected)
3754 ? old_local_content->name
3755 : old_remote_content->name;
3756 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:543757 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:233758 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3759 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:433760 old_transceiver->internal()->set_mid(absl::nullopt);
3761 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:543762 }
3763 }
3764 const MediaContentDescription* media_desc = content.media_description();
3765 auto transceiver = GetAssociatedTransceiver(content.name);
3766 if (source == cricket::CS_LOCAL) {
3767 // Find the RtpTransceiver that corresponds to this m= section, using the
3768 // mapping between transceivers and m= section indices established when
3769 // creating the offer.
3770 if (!transceiver) {
3771 transceiver = GetTransceiverByMLineIndex(mline_index);
3772 }
3773 if (!transceiver) {
3774 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3775 "Unknown transceiver");
3776 }
3777 } else {
3778 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3779 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3780 // of the same type...
Amit Hilbuchaa584152019-02-07 01:09:523781 // When simulcast is requested, a transceiver cannot be associated because
3782 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-23 00:02:543783 if (!transceiver &&
Amit Hilbuchaa584152019-02-07 01:09:523784 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3785 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-23 00:02:543786 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3787 }
3788 // If no RtpTransceiver was found in the previous step, create one with a
3789 // recvonly direction.
3790 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:233791 RTC_LOG(LS_INFO) << "Adding "
3792 << cricket::MediaTypeToString(media_desc->type())
3793 << " transceiver for MID=" << content.name
3794 << " at i=" << mline_index
3795 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:363796 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-26 01:13:563797 std::vector<RtpEncodingParameters> send_encodings =
3798 GetSendEncodingsFromRemoteDescription(*media_desc);
3799 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3800 send_encodings);
Steve Anton5f94aa22018-02-01 18:58:303801 std::string receiver_id;
3802 if (!media_desc->streams().empty()) {
3803 receiver_id = media_desc->streams()[0].id;
3804 } else {
3805 receiver_id = rtc::CreateRandomUuid();
3806 }
3807 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:063808 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:543809 transceiver->internal()->set_direction(
3810 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 15:29:443811 if (type == SdpType::kOffer) {
Eldar Rello353a7182019-11-25 16:49:443812 transceiver_stable_states_by_transceivers_[transceiver]
3813 .set_newly_created();
Eldar Rello5ab79e62019-10-09 15:29:443814 }
Steve Antondcc3c022017-12-23 00:02:543815 }
Amit Hilbuchbcd39d42019-01-26 01:13:563816 // Check if the offer indicated simulcast but the answer rejected it.
3817 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 21:14:463818 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 20:36:313819 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-26 01:13:563820 RTCError error =
Amit Hilbuch2297d332019-02-19 20:49:223821 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563822 if (!error.ok()) {
3823 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3824 return std::move(error);
3825 }
3826 }
Steve Antondcc3c022017-12-23 00:02:543827 }
3828 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:083829 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:543830 LOG_AND_RETURN_ERROR(
3831 RTCErrorType::INVALID_PARAMETER,
3832 "Transceiver type does not match media description type.");
3833 }
Amit Hilbuchbcd39d42019-01-26 01:13:563834 if (media_desc->HasSimulcast()) {
3835 std::vector<SimulcastLayer> layers =
3836 source == cricket::CS_LOCAL
3837 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3838 : media_desc->simulcast_description()
3839 .receive_layers()
3840 .GetAllLayers();
3841 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 20:49:223842 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-26 01:13:563843 if (!error.ok()) {
3844 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3845 return std::move(error);
3846 }
3847 }
Eldar Rello5ab79e62019-10-09 15:29:443848 if (type == SdpType::kOffer) {
Eldar Rello353a7182019-11-25 16:49:443849 bool state_changes = transceiver->internal()->mid() != content.name ||
3850 transceiver->internal()->mline_index() != mline_index;
3851 if (state_changes) {
3852 transceiver_stable_states_by_transceivers_[transceiver]
3853 .SetMSectionIfUnset(transceiver->internal()->mid(),
3854 transceiver->internal()->mline_index());
Eldar Rello5ab79e62019-10-09 15:29:443855 }
3856 }
Steve Antondcc3c022017-12-23 00:02:543857 // Associate the found or created RtpTransceiver with the m= section by
3858 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3859 // section, and establish a mapping between the transceiver and the index of
3860 // the m= section.
3861 transceiver->internal()->set_mid(content.name);
3862 transceiver->internal()->set_mline_index(mline_index);
3863 return std::move(transceiver);
3864}
3865
3866rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3867PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3868 RTC_DCHECK(IsUnifiedPlan());
3869 for (auto transceiver : transceivers_) {
3870 if (transceiver->mid() == mid) {
3871 return transceiver;
3872 }
3873 }
3874 return nullptr;
3875}
3876
3877rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3878PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3879 RTC_DCHECK(IsUnifiedPlan());
3880 for (auto transceiver : transceivers_) {
3881 if (transceiver->internal()->mline_index() == mline_index) {
3882 return transceiver;
3883 }
3884 }
3885 return nullptr;
3886}
3887
3888rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3889PeerConnection::FindAvailableTransceiverToReceive(
3890 cricket::MediaType media_type) const {
3891 RTC_DCHECK(IsUnifiedPlan());
3892 // From JSEP section 5.10 (Applying a Remote Description):
3893 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3894 // the same type that were added to the PeerConnection by addTrack and are not
3895 // associated with any m= section and are not stopped, find the first such
3896 // RtpTransceiver.
3897 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:083898 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:543899 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3900 !transceiver->stopped()) {
3901 return transceiver;
3902 }
3903 }
3904 return nullptr;
3905}
3906
Steve Antoned10bd92017-12-05 18:52:593907const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3908 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3909 transceiver,
3910 const SessionDescriptionInterface* sdesc) const {
3911 RTC_DCHECK(transceiver);
3912 RTC_DCHECK(sdesc);
3913 if (IsUnifiedPlan()) {
3914 if (!transceiver->internal()->mid()) {
3915 // This transceiver is not associated with a media section yet.
3916 return nullptr;
3917 }
3918 return sdesc->description()->GetContentByName(
3919 *transceiver->internal()->mid());
3920 } else {
3921 // Plan B only allows at most one audio and one video section, so use the
3922 // first media section of that type.
3923 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:083924 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:593925 }
3926}
3927
deadbeef46c73892016-11-17 03:42:043928PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 22:55:093929 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-17 03:42:043930 return configuration_;
3931}
3932
Niels Möller2579f0c2019-08-19 07:58:173933RTCError PeerConnection::SetConfiguration(
3934 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 22:55:093935 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:173936 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:103937 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 07:58:173938 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3939 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 16:54:103940 }
3941
Qingsi Wanga2d60672018-04-11 23:57:453942 // According to JSEP, after setLocalDescription, changing the candidate pool
3943 // size is not allowed, and changing the set of ICE servers will not result
3944 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:173945 if (local_description() && configuration.ice_candidate_pool_size !=
3946 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 07:58:173947 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3948 "Can't change candidate pool size after calling "
3949 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:453950 }
Taylor Brandstettera1c30352016-05-13 15:15:113951
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453952 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 17:16:443953 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 07:58:173954 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3955 "Can't change crypto_options after calling "
3956 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 17:16:443957 }
3958
Anton Sukhanov316f3ac2019-05-23 22:50:383959 if (local_description() && configuration.use_datagram_transport !=
3960 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 07:58:173961 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3962 "Can't change use_datagram_transport "
3963 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 22:50:383964 }
3965
3966 if (remote_description() && configuration.use_datagram_transport !=
3967 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 07:58:173968 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3969 "Can't change use_datagram_transport "
3970 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 22:50:383971 }
3972
Bjorn A Mellemb689af42019-08-21 17:44:593973 if (local_description() &&
3974 configuration.use_datagram_transport_for_data_channels !=
3975 configuration_.use_datagram_transport_for_data_channels) {
3976 LOG_AND_RETURN_ERROR(
3977 RTCErrorType::INVALID_MODIFICATION,
3978 "Can't change use_datagram_transport_for_data_channels "
3979 "after calling SetLocalDescription.");
3980 }
3981
3982 if (remote_description() &&
3983 configuration.use_datagram_transport_for_data_channels !=
3984 configuration_.use_datagram_transport_for_data_channels) {
3985 LOG_AND_RETURN_ERROR(
3986 RTCErrorType::INVALID_MODIFICATION,
3987 "Can't change use_datagram_transport_for_data_channels "
3988 "after calling SetRemoteDescription.");
3989 }
3990
Bjorn A Mellem7da4e562019-09-26 18:02:113991 if (local_description() &&
3992 configuration.use_datagram_transport_for_data_channels_receive_only !=
3993 configuration_
3994 .use_datagram_transport_for_data_channels_receive_only) {
3995 LOG_AND_RETURN_ERROR(
3996 RTCErrorType::INVALID_MODIFICATION,
3997 "Can't change use_datagram_transport_for_data_channels_receive_only "
3998 "after calling SetLocalDescription.");
3999 }
4000
4001 if (remote_description() &&
4002 configuration.use_datagram_transport_for_data_channels_receive_only !=
4003 configuration_
4004 .use_datagram_transport_for_data_channels_receive_only) {
4005 LOG_AND_RETURN_ERROR(
4006 RTCErrorType::INVALID_MODIFICATION,
4007 "Can't change use_datagram_transport_for_data_channels_receive_only "
4008 "after calling SetRemoteDescription.");
4009 }
4010
Bjorn A Mellem7a9a0922019-11-26 17:19:404011 if ((configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 17:44:594012 *configuration.use_datagram_transport) ||
4013 (configuration.use_datagram_transport_for_data_channels &&
4014 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 15:42:224015 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
4016 << "Media transport requires MaxBundle policy.";
4017 }
4018
deadbeef293e9262017-01-11 20:28:304019 // The simplest (and most future-compatible) way to tell if the config was
4020 // modified in an invalid way is to copy each property we do support
4021 // modifying, then use operator==. There are far more properties we don't
4022 // support modifying than those we do, and more could be added.
4023 RTCConfiguration modified_config = configuration_;
4024 modified_config.servers = configuration.servers;
4025 modified_config.type = configuration.type;
4026 modified_config.ice_candidate_pool_size =
4027 configuration.ice_candidate_pool_size;
4028 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 18:27:504029 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 21:56:024030 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
4031 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-04 00:54:054032 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:144033 modified_config.ice_check_interval_strong_connectivity =
4034 configuration.ice_check_interval_strong_connectivity;
4035 modified_config.ice_check_interval_weak_connectivity =
4036 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:574037 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
4038 modified_config.ice_unwritable_min_checks =
4039 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:174040 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:494041 modified_config.stun_candidate_keepalive_interval =
4042 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:404043 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:404044 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:114045 modified_config.active_reset_srtp_params =
4046 configuration.active_reset_srtp_params;
Bjorn A Mellem5985a042019-06-28 21:19:384047 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 17:44:594048 modified_config.use_datagram_transport_for_data_channels =
4049 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 18:02:114050 modified_config.use_datagram_transport_for_data_channels_receive_only =
4051 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 14:16:354052 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 10:23:024053 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 20:28:304054 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 07:58:174055 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
4056 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 20:28:304057 }
4058
Steve Anton038834f2017-07-14 22:59:594059 // Validate the modified configuration.
4060 RTCError validate_error = ValidateConfiguration(modified_config);
4061 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 07:58:174062 return validate_error;
Steve Anton038834f2017-07-14 22:59:594063 }
4064
deadbeef293e9262017-01-11 20:28:304065 // Note that this isn't possible through chromium, since it's an unsigned
4066 // short in WebIDL.
4067 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:174068 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 07:58:174069 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 20:28:304070 }
4071
4072 // Parse ICE servers before hopping to network thread.
4073 cricket::ServerAddresses stun_servers;
4074 std::vector<cricket::RelayServerConfig> turn_servers;
4075 RTCErrorType parse_error =
4076 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
4077 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 07:58:174078 return RTCError(parse_error);
deadbeef293e9262017-01-11 20:28:304079 }
Jonas Oreland3c028422019-08-22 14:16:354080 // Add the turn logging id to all turn servers
4081 for (cricket::RelayServerConfig& turn_server : turn_servers) {
4082 turn_server.turn_logging_id = configuration.turn_logging_id;
4083 }
4084
Harald Alvestrand8ebba742018-05-31 12:00:344085 // Note if STUN or TURN servers were supplied.
4086 if (!stun_servers.empty()) {
4087 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
4088 }
4089 if (!turn_servers.empty()) {
4090 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
4091 }
deadbeef293e9262017-01-11 20:28:304092
4093 // In theory this shouldn't fail.
4094 if (!network_thread()->Invoke<bool>(
4095 RTC_FROM_HERE,
4096 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
4097 stun_servers, turn_servers, modified_config.type,
4098 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:504099 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 22:45:494100 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:284101 modified_config.stun_candidate_keepalive_interval,
4102 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 07:58:174103 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4104 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 20:28:304105 }
Honghai Zhang4cedf2b2016-08-31 15:18:114106
deadbeefd1a38b52016-12-10 21:15:334107 // As described in JSEP, calling setConfiguration with new ICE servers or
4108 // candidate policy must set a "needs-ice-restart" bit so that the next offer
4109 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:304110 if (modified_config.servers != configuration_.servers ||
Jonas Orelande3096512020-05-27 07:01:054111 NeedIceRestart(
4112 configuration_.surface_ice_candidates_on_ice_transport_type_changed,
4113 configuration_.type, modified_config.type) ||
Honghai Zhangf8998cf2019-10-14 18:27:504114 modified_config.GetTurnPortPrunePolicy() !=
4115 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 22:50:294116 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:334117 }
skvladd1f5fda2017-02-04 00:54:054118
Qingsi Wang9c98f0c2018-02-15 23:10:594119 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 21:19:384120
4121 use_datagram_transport_ = datagram_transport_config_.enabled &&
4122 modified_config.use_datagram_transport.value_or(
4123 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 17:44:594124 use_datagram_transport_for_data_channels_ =
4125 datagram_transport_data_channel_config_.enabled &&
4126 modified_config.use_datagram_transport_for_data_channels.value_or(
4127 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 18:02:114128 use_datagram_transport_for_data_channels_receive_only_ =
4129 modified_config.use_datagram_transport_for_data_channels_receive_only
4130 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 21:31:154131 transport_controller_->SetMediaTransportSettings(
Bjorn A Mellem7da4e562019-09-26 18:02:114132 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4133 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-04 00:54:054134
Zhi Huangb57e1692018-06-12 18:41:114135 if (configuration_.active_reset_srtp_params !=
4136 modified_config.active_reset_srtp_params) {
4137 transport_controller_->SetActiveResetSrtpParams(
4138 modified_config.active_reset_srtp_params);
4139 }
4140
philipel16cec3b2019-10-25 10:23:024141 if (modified_config.allow_codec_switching.has_value()) {
philipel01294f02019-11-14 12:03:254142 cricket::VideoMediaChannel* video_channel = video_media_channel();
4143 if (video_channel) {
4144 video_channel->SetVideoCodecSwitchingEnabled(
4145 *modified_config.allow_codec_switching);
4146 }
philipel16cec3b2019-10-25 10:23:024147 }
4148
deadbeef293e9262017-01-11 20:28:304149 configuration_ = modified_config;
Niels Möller2579f0c2019-08-19 07:58:174150 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:454151}
4152
henrike@webrtc.org28e20752013-07-10 00:45:364153bool PeerConnection::AddIceCandidate(
4154 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 09:18:564155 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:174156 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:254157 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:104158 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:364159 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:254160 return false;
4161 }
Steve Antond25da372017-11-06 22:50:294162
4163 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:104164 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:074165 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:364166 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:294167 return false;
4168 }
4169
4170 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:104171 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:364172 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:294173 return false;
4174 }
4175
4176 bool valid = false;
4177 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4178 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:364179 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:294180 return false;
4181 }
4182
4183 // Add this candidate to the remote session description.
4184 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:104185 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:364186 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:294187 return false;
4188 }
4189
4190 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:364191 bool result = UseCandidate(ice_candidate);
4192 if (result) {
Qingsi Wang1ba5dec2019-08-19 18:57:174193 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 21:24:364194 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4195 } else {
4196 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4197 }
4198 return result;
Steve Antond25da372017-11-06 22:50:294199 } else {
Steve Antonc79268f2018-04-24 16:54:104200 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:364201 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:294202 return true;
4203 }
henrike@webrtc.org28e20752013-07-10 00:45:364204}
4205
Henrik Boströmee6f4f62019-11-06 11:36:124206void PeerConnection::AddIceCandidate(
4207 std::unique_ptr<IceCandidateInterface> candidate,
4208 std::function<void(RTCError)> callback) {
4209 RTC_DCHECK_RUN_ON(signaling_thread());
4210 // Chain this operation. If asynchronous operations are pending on the chain,
4211 // this operation will be queued to be invoked, otherwise the contents of the
4212 // lambda will execute immediately.
4213 operations_chain_->ChainOperation(
4214 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
4215 candidate = std::move(candidate), callback = std::move(callback)](
4216 std::function<void()> operations_chain_callback) {
4217 if (!this_weak_ptr) {
4218 operations_chain_callback();
4219 callback(RTCError(
4220 RTCErrorType::INVALID_STATE,
4221 "AddIceCandidate failed because the session was shut down"));
4222 return;
4223 }
4224 if (!this_weak_ptr->AddIceCandidate(candidate.get())) {
4225 operations_chain_callback();
4226 // Fail with an error type and message consistent with Chromium.
4227 // TODO(hbos): Fail with error types according to spec.
4228 callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
4229 "Error processing ICE candidate"));
4230 return;
4231 }
4232 operations_chain_callback();
4233 callback(RTCError::OK());
4234 });
4235}
4236
Honghai Zhang7fb69db2016-03-14 18:59:184237bool PeerConnection::RemoveIceCandidates(
4238 const std::vector<cricket::Candidate>& candidates) {
4239 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 09:31:564240 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 16:54:104241 if (IsClosed()) {
4242 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4243 return false;
4244 }
4245
Steve Antond25da372017-11-06 22:50:294246 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:104247 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4248 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:294249 return false;
4250 }
4251
4252 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:104253 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:294254 return false;
4255 }
4256
4257 size_t number_removed =
4258 mutable_remote_description()->RemoveCandidates(candidates);
4259 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:254260 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:104261 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:074262 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:254263 << " are removed.";
Steve Antond25da372017-11-06 22:50:294264 }
4265
4266 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:354267 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4268 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:104269 RTC_LOG(LS_ERROR)
4270 << "RemoveIceCandidates: Error when removing remote candidates: "
4271 << error.message();
Steve Antond25da372017-11-06 22:50:294272 }
4273 return true;
Honghai Zhang7fb69db2016-03-14 18:59:184274}
4275
Niels Möller0c4f7be2018-05-07 12:01:374276RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:024277 if (!worker_thread()->IsCurrent()) {
4278 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:054279 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:374280 }
Karl Wiberg6cab5c82019-03-26 08:57:014281 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 21:37:374282
Niels Möller0c4f7be2018-05-07 12:01:374283 const bool has_min = bitrate.min_bitrate_bps.has_value();
4284 const bool has_start = bitrate.start_bitrate_bps.has_value();
4285 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:374286 if (has_min && *bitrate.min_bitrate_bps < 0) {
4287 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4288 "min_bitrate_bps <= 0");
4289 }
Niels Möller0c4f7be2018-05-07 12:01:374290 if (has_start) {
4291 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:374292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:374293 "start_bitrate_bps < min_bitrate_bps");
4294 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:374295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4296 "curent_bitrate_bps < 0");
4297 }
4298 }
4299 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:054300 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:374301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:374302 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:374303 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4305 "max_bitrate_bps < min_bitrate_bps");
4306 } else if (*bitrate.max_bitrate_bps < 0) {
4307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4308 "max_bitrate_bps < 0");
4309 }
4310 }
4311
zstein4b979802017-06-02 21:37:374312 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 17:31:544313 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:374314
4315 return RTCError::OK();
4316}
4317
henrika5f6bf242017-11-01 10:06:564318void PeerConnection::SetAudioPlayout(bool playout) {
4319 if (!worker_thread()->IsCurrent()) {
4320 worker_thread()->Invoke<void>(
4321 RTC_FROM_HERE,
4322 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4323 return;
4324 }
4325 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:554326 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:564327 audio_state->SetPlayout(playout);
4328}
4329
4330void PeerConnection::SetAudioRecording(bool recording) {
4331 if (!worker_thread()->IsCurrent()) {
4332 worker_thread()->Invoke<void>(
4333 RTC_FROM_HERE,
4334 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4335 return;
4336 }
4337 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:554338 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:564339 audio_state->SetRecording(recording);
4340}
4341
Steve Anton8c0f7a72017-10-03 17:03:104342std::unique_ptr<rtc::SSLCertificate>
4343PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:514344 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4345 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:104346 return nullptr;
4347 }
Steve Antonf25303e2018-10-16 22:23:314348 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:104349}
4350
Zhi Huang70b820f2018-01-27 22:16:154351std::unique_ptr<rtc::SSLCertChain>
4352PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 12:33:434353 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 19:35:374354 auto audio_transceiver = GetFirstAudioTransceiver();
4355 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:154356 return nullptr;
4357 }
Zhi Huang70b820f2018-01-27 22:16:154358 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:374359 audio_transceiver->internal()->channel()->transport_name());
4360}
4361
4362rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4363PeerConnection::GetFirstAudioTransceiver() const {
4364 for (auto transceiver : transceivers_) {
4365 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4366 return transceiver;
4367 }
4368 }
4369 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:154370}
4371
Bjorn Tereliusde939432017-11-20 16:38:144372bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4373 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 16:38:144374 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 08:21:114375 RTC_FROM_HERE,
4376 [this, output = std::move(output), output_period_ms]() mutable {
4377 return StartRtcEventLog_w(std::move(output), output_period_ms);
4378 });
ivoc14d5dbe2016-07-04 14:06:554379}
4380
Niels Möllerf00ca1a2019-05-10 09:33:124381bool PeerConnection::StartRtcEventLog(
4382 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 10:27:234383 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4384 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4385 output_period_ms = 5000;
4386 }
4387 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 09:33:124388}
4389
ivoc14d5dbe2016-07-04 14:06:554390void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:024391 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:554392 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4393}
4394
Harald Alvestrandad88c882018-11-28 15:47:464395rtc::scoped_refptr<DtlsTransportInterface>
4396PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:564397 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 15:47:464398 return transport_controller_->LookupDtlsTransportByMid(mid);
4399}
4400
Harald Alvestrand4a7b3ac2019-01-17 09:39:404401rtc::scoped_refptr<DtlsTransport>
4402PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 09:31:564403 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 09:39:404404 return transport_controller_->LookupDtlsTransportByMid(mid);
4405}
4406
Harald Alvestrandc85328f2019-02-28 06:51:004407rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4408 const {
Karl Wiberg2cc368f2019-04-02 09:31:564409 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand7a829a82020-02-12 06:38:214410 if (!sctp_mid_s_) {
Bjorn A Mellembc3eebc2019-09-23 21:53:544411 return nullptr;
4412 }
Harald Alvestrand7a829a82020-02-12 06:38:214413 return transport_controller_->GetSctpTransport(*sctp_mid_s_);
Harald Alvestrandc85328f2019-02-28 06:51:004414}
4415
henrike@webrtc.org28e20752013-07-10 00:45:364416const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 09:37:284417 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174418 return pending_local_description_ ? pending_local_description_.get()
4419 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:364420}
4421
4422const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 09:37:284423 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174424 return pending_remote_description_ ? pending_remote_description_.get()
4425 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:364426}
4427
deadbeeffe4a8a42016-12-21 01:56:174428const SessionDescriptionInterface* PeerConnection::current_local_description()
4429 const {
Karl Wiberg739506e2019-04-03 09:37:284430 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174431 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174432}
4433
4434const SessionDescriptionInterface* PeerConnection::current_remote_description()
4435 const {
Karl Wiberg739506e2019-04-03 09:37:284436 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174437 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174438}
4439
4440const SessionDescriptionInterface* PeerConnection::pending_local_description()
4441 const {
Karl Wiberg739506e2019-04-03 09:37:284442 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174443 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174444}
4445
4446const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4447 const {
Karl Wiberg739506e2019-04-03 09:37:284448 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174449 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:174450}
4451
henrike@webrtc.org28e20752013-07-10 00:45:364452void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 09:18:564453 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 21:15:174454 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:364455 // Update stats here so that we have the most recent stats for tracks and
4456 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:264457 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:364458
Steve Anton75737c02017-11-06 18:37:174459 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:344460 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:084461
Mirko Bonadei739baf02019-01-27 16:29:424462 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 19:20:134463 transceiver->Stop();
4464 }
Steve Anton25cfeb92018-04-26 18:44:004465
4466 // Ensure that all asynchronous stats requests are completed before destroying
4467 // the transport controller below.
4468 if (stats_collector_) {
4469 stats_collector_->WaitForPendingRequest();
4470 }
4471
4472 // Don't destroy BaseChannels until after stats has been cleaned up so that
4473 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:134474 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:174475
Qingsi Wang93a84392018-01-31 01:13:094476 // The event log is used in the transport controller, which must be outlived
4477 // by the former. CreateOffer by the peer connection is implemented
4478 // asynchronously and if the peer connection is closed without resetting the
4479 // WebRTC session description factory, the session description factory would
4480 // call the transport controller.
4481 webrtc_session_desc_factory_.reset();
4482 transport_controller_.reset();
4483
deadbeef42a42632017-03-10 23:18:004484 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:054485 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4486 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:024487
Steve Anton978b8762017-09-29 19:15:024488 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 10:59:574489 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 12:18:154490 call_.reset();
4491 // The event log must outlive call (and any other object that uses it).
4492 event_log_.reset();
4493 });
Harald Alvestrand8ebba742018-05-31 12:00:344494 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:164495 // The .h file says that observer can be discarded after close() returns.
4496 // Make sure this is true.
4497 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:364498}
4499
Steve Antonad182762018-09-05 20:22:404500void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 09:18:564501 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:404502 switch (msg->message_id) {
4503 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4504 SetSessionDescriptionMsg* param =
4505 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4506 param->observer->OnSuccess();
4507 delete param;
4508 break;
4509 }
4510 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4511 SetSessionDescriptionMsg* param =
4512 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4513 param->observer->OnFailure(std::move(param->error));
4514 delete param;
4515 break;
4516 }
4517 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4518 CreateSessionDescriptionMsg* param =
4519 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4520 param->observer->OnFailure(std::move(param->error));
4521 delete param;
4522 break;
4523 }
4524 case MSG_GETSTATS: {
4525 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4526 StatsReports reports;
4527 stats_->GetStats(param->track, &reports);
4528 param->observer->OnComplete(reports);
4529 delete param;
4530 break;
4531 }
Steve Antonad182762018-09-05 20:22:404532 case MSG_REPORT_USAGE_PATTERN: {
4533 ReportUsagePattern();
4534 break;
4535 }
4536 default:
4537 RTC_NOTREACHED() << "Not implemented";
4538 break;
4539 }
4540}
4541
Steve Antonafb0bb72018-02-20 19:35:374542cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4543 RTC_DCHECK(!IsUnifiedPlan());
4544 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4545 GetAudioTransceiver()->internal()->channel());
4546 if (voice_channel) {
4547 return voice_channel->media_channel();
4548 } else {
4549 return nullptr;
4550 }
4551}
4552
4553cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4554 RTC_DCHECK(!IsUnifiedPlan());
4555 auto* video_channel = static_cast<cricket::VideoChannel*>(
4556 GetVideoTransceiver()->internal()->channel());
4557 if (video_channel) {
4558 return video_channel->media_channel();
4559 } else {
4560 return nullptr;
4561 }
4562}
4563
Steve Anton4171afb2017-11-20 18:20:224564void PeerConnection::CreateAudioReceiver(
4565 MediaStreamInterface* stream,
4566 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:514567 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4568 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:534569 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4570 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:024571 auto* audio_receiver = new AudioRtpReceiver(
4572 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:054573 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 23:23:054574 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4575 audio_receiver->SetupUnsignaledMediaChannel();
4576 } else {
4577 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4578 }
Steve Antond3679212018-01-18 01:41:024579 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4580 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:224581 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:124582 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:344583 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:364584}
4585
Steve Anton4171afb2017-11-20 18:20:224586void PeerConnection::CreateVideoReceiver(
4587 MediaStreamInterface* stream,
4588 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:514589 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4590 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:534591 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4592 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:024593 auto* video_receiver = new VideoRtpReceiver(
4594 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:054595 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 23:23:054596 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4597 video_receiver->SetupUnsignaledMediaChannel();
4598 } else {
4599 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4600 }
Steve Antond3679212018-01-18 01:41:024601 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4602 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:224603 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 20:38:124604 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 12:00:344605 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:364606}
4607
deadbeef70ab1a12015-09-28 23:53:554608// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4609// description.
Henrik Boström933d8b02017-10-10 17:05:164610rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:224611 const RtpSenderInfo& remote_sender_info) {
4612 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4613 if (!receiver) {
4614 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4615 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:164616 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554617 }
Steve Anton4171afb2017-11-20 18:20:224618 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4619 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4620 } else {
4621 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4622 }
Henrik Boström933d8b02017-10-10 17:05:164623 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:364624}
4625
korniltsev.anatolyec390b52017-07-25 00:00:254626void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4627 MediaStreamInterface* stream) {
4628 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364629 RTC_DCHECK(track);
4630 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254631 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224632 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254633 // We already have a sender for this track, so just change the stream_id
4634 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:384635 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254636 return;
4637 }
4638
4639 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364640 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204641 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054642 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:224643 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:254644 // If the sender has already been configured in SDP, we call SetSsrc,
4645 // which will connect the sender to the underlying transport. This can
4646 // occur if a local session description that contains the ID of the sender
4647 // is set before AddStream is called. It can also occur if the local
4648 // session description is not changed and RemoveStream is called, and
4649 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:224650 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184651 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224652 if (sender_info) {
4653 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254654 }
4655}
4656
4657// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4658// indefinitely, when we have unified plan SDP.
4659void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4660 MediaStreamInterface* stream) {
4661 RTC_DCHECK(!IsClosed());
4662 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224663 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254664 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4665 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254666 return;
4667 }
Steve Anton4171afb2017-11-20 18:20:224668 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254669}
4670
4671void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4672 MediaStreamInterface* stream) {
4673 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:364674 RTC_DCHECK(track);
4675 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:254676 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224677 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:254678 // We already have a sender for this track, so just change the stream_id
4679 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:384680 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:254681 return;
4682 }
4683
4684 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:364685 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:204686 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:054687 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:224688 GetVideoTransceiver()->internal()->AddSender(new_sender);
4689 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184690 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:224691 if (sender_info) {
4692 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:254693 }
4694}
4695
4696void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4697 MediaStreamInterface* stream) {
4698 RTC_DCHECK(!IsClosed());
4699 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:224700 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:254701 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4702 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:254703 return;
4704 }
Steve Anton4171afb2017-11-20 18:20:224705 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:254706}
4707
Steve Antonba818672017-11-06 18:21:574708void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 18:21:574709 if (ice_connection_state_ == new_state) {
4710 return;
4711 }
4712
deadbeefcbecd352015-09-23 18:50:274713 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:574714 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:114715 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:274716 return;
4717 }
Steve Antonba818672017-11-06 18:21:574718
Mirko Bonadei675513b2017-11-09 10:09:254719 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4720 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:574721 RTC_DCHECK(ice_connection_state_ !=
4722 PeerConnectionInterface::kIceConnectionClosed);
4723
henrike@webrtc.org28e20752013-07-10 00:45:364724 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164725 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364726}
4727
Alex Loiko9289eda2018-11-23 16:18:594728void PeerConnection::SetStandardizedIceConnectionState(
4729 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 18:37:264730 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:594731 return;
Qingsi Wang36e31472019-05-29 18:37:264732 }
4733
4734 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:594735 return;
Qingsi Wang36e31472019-05-29 18:37:264736 }
4737
4738 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4739 << standardized_ice_connection_state_ << " => " << new_state;
4740
Alex Loiko9289eda2018-11-23 16:18:594741 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 10:25:144742 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:594743}
4744
Jonas Olsson635474e2018-10-18 13:58:174745void PeerConnection::SetConnectionState(
4746 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 13:58:174747 if (connection_state_ == new_state)
4748 return;
4749 if (IsClosed())
4750 return;
4751 connection_state_ = new_state;
4752 Observer()->OnConnectionChange(new_state);
4753}
4754
henrike@webrtc.org28e20752013-07-10 00:45:364755void PeerConnection::OnIceGatheringChange(
4756 PeerConnectionInterface::IceGatheringState new_state) {
4757 if (IsClosed()) {
4758 return;
4759 }
4760 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:164761 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364762}
4763
jbauch81bf7b02017-03-25 15:31:124764void PeerConnection::OnIceCandidate(
4765 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 18:07:254766 if (IsClosed()) {
4767 return;
4768 }
Qingsi Wang1ba5dec2019-08-19 18:57:174769 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 08:50:164770 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:364771}
4772
Eldar Rello0095d372019-12-02 20:22:074773void PeerConnection::OnIceCandidateError(const std::string& address,
4774 int port,
Eldar Relloda13ea22019-06-01 09:23:434775 const std::string& url,
4776 int error_code,
4777 const std::string& error_text) {
4778 if (IsClosed()) {
4779 return;
4780 }
Eldar Rello0095d372019-12-02 20:22:074781 Observer()->OnIceCandidateError(address, port, url, error_code, error_text);
4782 // Leftover not to break wpt test during migration to the new API.
4783 Observer()->OnIceCandidateError(address + ":", url, error_code, error_text);
Eldar Relloda13ea22019-06-01 09:23:434784}
4785
Honghai Zhang7fb69db2016-03-14 18:59:184786void PeerConnection::OnIceCandidatesRemoved(
4787 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 18:07:254788 if (IsClosed()) {
4789 return;
4790 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164791 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:184792}
4793
Alex Drake00c7ecf2019-08-06 17:54:474794void PeerConnection::OnSelectedCandidatePairChanged(
4795 const cricket::CandidatePairChangeEvent& event) {
4796 if (IsClosed()) {
4797 return;
4798 }
Qingsi Wang1ba5dec2019-08-19 18:57:174799
Qingsi Wangcc46b10c2019-09-12 18:19:014800 if (event.selected_candidate_pair.local_candidate().type() ==
4801 LOCAL_PORT_TYPE &&
4802 event.selected_candidate_pair.remote_candidate().type() ==
4803 LOCAL_PORT_TYPE) {
4804 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4805 }
4806
Alex Drake00c7ecf2019-08-06 17:54:474807 Observer()->OnIceSelectedCandidatePairChanged(event);
4808}
4809
henrike@webrtc.org28e20752013-07-10 00:45:364810void PeerConnection::ChangeSignalingState(
4811 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:574812 if (signaling_state_ == signaling_state) {
4813 return;
4814 }
Mirko Bonadei675513b2017-11-09 10:09:254815 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4816 << GetSignalingStateString(signaling_state_)
4817 << " New state: "
4818 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:364819 signaling_state_ = signaling_state;
4820 if (signaling_state == kClosed) {
4821 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:164822 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:594823 standardized_ice_connection_state_ =
4824 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:174825 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4826 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364827 }
Harald Alvestrand7a1c7f72018-08-01 08:50:164828 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:364829}
4830
deadbeefeb459812015-12-16 03:24:434831void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4832 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254833 if (IsClosed()) {
4834 return;
4835 }
korniltsev.anatolyec390b52017-07-25 00:00:254836 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144837 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434838}
4839
deadbeefeb459812015-12-16 03:24:434840void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4841 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254842 if (IsClosed()) {
4843 return;
4844 }
korniltsev.anatolyec390b52017-07-25 00:00:254845 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144846 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434847}
4848
4849void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4850 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254851 if (IsClosed()) {
4852 return;
4853 }
korniltsev.anatolyec390b52017-07-25 00:00:254854 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144855 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434856}
4857
4858void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4859 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:254860 if (IsClosed()) {
4861 return;
4862 }
korniltsev.anatolyec390b52017-07-25 00:00:254863 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 10:24:144864 UpdateNegotiationNeeded();
deadbeefeb459812015-12-16 03:24:434865}
4866
Henrik Boström31638672017-11-23 16:48:324867void PeerConnection::PostSetSessionDescriptionSuccess(
4868 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:404869 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4870 signaling_thread()->Post(RTC_FROM_HERE, this,
4871 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:324872}
4873
deadbeefab9b2d12015-10-14 18:33:114874void PeerConnection::PostSetSessionDescriptionFailure(
4875 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:404876 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:034877 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404878 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4879 msg->error = std::move(error);
4880 signaling_thread()->Post(RTC_FROM_HERE, this,
4881 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114882}
4883
4884void PeerConnection::PostCreateSessionDescriptionFailure(
4885 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:034886 RTCError error) {
4887 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:404888 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4889 msg->error = std::move(error);
4890 signaling_thread()->Post(RTC_FROM_HERE, this,
4891 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:114892}
4893
zhihuang1c378ed2017-08-17 21:10:504894void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:544895 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:114896 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:544897 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:504898
Steve Antondcc3c022017-12-23 00:02:544899 if (IsUnifiedPlan()) {
4900 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4901 } else {
4902 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4903 }
4904
Steve Antonfa2260d2017-12-29 00:38:234905 // Intentionally unset the data channel type for RTP data channel with the
4906 // second condition. Otherwise the RTP data channels would be successfully
4907 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4908 // when building with chromium. We want to leave RTP data channels broken, so
4909 // people won't try to use them.
Harald Alvestrand05e4d082019-12-03 13:04:214910 if (data_channel_controller_.HasRtpDataChannels() ||
4911 data_channel_type() != cricket::DCT_RTP) {
Steve Antonfa2260d2017-12-29 00:38:234912 session_options->data_channel_type = data_channel_type();
4913 }
4914
Steve Antondcc3c022017-12-23 00:02:544915 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 09:16:564916 bool ice_restart = offer_answer_options.ice_restart ||
4917 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-23 00:02:544918 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 09:16:564919 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-23 00:02:544920 options.transport_options.enable_ice_renomination =
4921 configuration_.enable_ice_renomination;
4922 }
4923
4924 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444925 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:124926 session_options->pooled_ice_credentials =
4927 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4928 RTC_FROM_HERE,
4929 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4930 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 09:25:484931 session_options->offer_extmap_allow_mixed =
4932 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:054933
Bjorn A Mellemc85ebbe2019-06-07 17:28:064934 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 17:44:594935 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 17:28:064936 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 22:12:474937 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 17:28:064938 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 22:12:474939 if (!params) {
4940 continue;
4941 }
4942 options.transport_options.opaque_parameters = params;
4943 if ((use_datagram_transport_ &&
4944 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4945 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4946 (use_datagram_transport_for_data_channels_ &&
4947 options.type == cricket::MEDIA_TYPE_DATA)) {
4948 options.alt_protocol = params->protocol;
4949 }
Bjorn A Mellemc85ebbe2019-06-07 17:28:064950 }
4951 }
4952
Harald Alvestrand4aa11922019-05-14 20:00:014953 // Allow fallback for using obsolete SCTP syntax.
4954 // Note that the default in |session_options| is true, while
4955 // the default in |options| is false.
4956 session_options->use_obsolete_sctp_sdp =
4957 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-23 00:02:544958}
4959
4960void PeerConnection::GetOptionsForPlanBOffer(
4961 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4962 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504963 // Figure out transceiver directional preferences.
4964 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4965 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4966
4967 // By default, generate sendrecv/recvonly m= sections.
4968 bool recv_audio = true;
4969 bool recv_video = true;
4970
4971 // By default, only offer a new m= section if we have media to send with it.
4972 bool offer_new_audio_description = send_audio;
4973 bool offer_new_video_description = send_video;
Harald Alvestrand05e4d082019-12-03 13:04:214974 bool offer_new_data_description = data_channel_controller_.HasDataChannels();
zhihuang1c378ed2017-08-17 21:10:504975
4976 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544977 if (offer_answer_options.offer_to_receive_audio !=
4978 RTCOfferAnswerOptions::kUndefined) {
4979 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:504980 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:544981 offer_new_audio_description ||
4982 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:504983 }
Steve Antondcc3c022017-12-23 00:02:544984 if (offer_answer_options.offer_to_receive_video !=
4985 RTCOfferAnswerOptions::kUndefined) {
4986 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504987 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:544988 offer_new_video_description ||
4989 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504990 }
4991
Danil Chapovalov66cadcc2018-06-19 14:47:434992 absl::optional<size_t> audio_index;
4993 absl::optional<size_t> video_index;
4994 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:504995 // If a current description exists, generate m= sections in the same order,
4996 // using the first audio/video/data section that appears and rejecting
4997 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:174998 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:504999 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:175000 local_description(),
Steve Anton1d03a752017-11-27 22:30:095001 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5002 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
5003 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:115004 }
5005
zhihuang1c378ed2017-08-17 21:10:505006 // Add audio/video/data m= sections to the end if needed.
5007 if (!audio_index && offer_new_audio_description) {
Markus Handell71db9ac2020-06-08 17:48:495008 cricket::MediaDescriptionOptions options(
5009 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
5010 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio), false);
5011 options.header_extensions =
5012 channel_manager()->GetSupportedAudioRtpHeaderExtensions();
5013 session_options->media_description_options.push_back(options);
Oskar Sundbom9b28a032017-11-16 09:53:305014 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:455015 }
zhihuang1c378ed2017-08-17 21:10:505016 if (!video_index && offer_new_video_description) {
Markus Handell71db9ac2020-06-08 17:48:495017 cricket::MediaDescriptionOptions options(
5018 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
5019 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), false);
5020 options.header_extensions =
5021 channel_manager()->GetSupportedVideoRtpHeaderExtensions();
5022 session_options->media_description_options.push_back(options);
Oskar Sundbom9b28a032017-11-16 09:53:305023 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:455024 }
zhihuang1c378ed2017-08-17 21:10:505025 if (!data_index && offer_new_data_description) {
5026 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235027 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:305028 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505029 }
5030
5031 cricket::MediaDescriptionOptions* audio_media_description_options =
5032 !audio_index ? nullptr
5033 : &session_options->media_description_options[*audio_index];
5034 cricket::MediaDescriptionOptions* video_media_description_options =
5035 !video_index ? nullptr
5036 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:505037
Amit Hilbuchc63ddb22019-01-02 18:13:585038 AddPlanBRtpSenderOptions(GetSendersInternal(),
5039 audio_media_description_options,
5040 video_media_description_options,
5041 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:545042}
5043
Steve Antondcc3c022017-12-23 00:02:545044static cricket::MediaDescriptionOptions
5045GetMediaDescriptionOptionsForTransceiver(
5046 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5047 transceiver,
5048 const std::string& mid) {
5049 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:085050 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:545051 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 17:25:515052 media_description_options.codec_preferences =
5053 transceiver->codec_preferences();
Markus Handell71db9ac2020-06-08 17:48:495054 media_description_options.header_extensions =
5055 transceiver->HeaderExtensionsToOffer();
Steve Anton5f94aa22018-02-01 18:58:305056 // This behavior is specified in JSEP. The gist is that:
5057 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5058 // sendrecv.
5059 // 2. If the MSID is included, then it must be included in any subsequent
5060 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-26 01:13:565061 if (transceiver->stopped() ||
5062 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5063 !transceiver->internal()->has_ever_been_used_to_send())) {
5064 return media_description_options;
Steve Anton5f94aa22018-02-01 18:58:305065 }
Amit Hilbuchbcd39d42019-01-26 01:13:565066
5067 cricket::SenderOptions sender_options;
5068 sender_options.track_id = transceiver->sender()->id();
5069 sender_options.stream_ids = transceiver->sender()->stream_ids();
5070
5071 // The following sets up RIDs and Simulcast.
5072 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 23:55:195073 RtpParameters send_parameters =
5074 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-26 01:13:565075 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5076 send_parameters.encodings.end(),
5077 [](const RtpEncodingParameters& encoding) {
5078 return !encoding.rid.empty();
5079 });
5080
Amit Hilbuchb7446ed2019-01-28 20:25:255081 std::vector<RidDescription> send_rids;
5082 SimulcastLayerList send_layers;
5083 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5084 if (encoding.rid.empty()) {
5085 continue;
5086 }
5087 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5088 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5089 }
5090
Amit Hilbuchbcd39d42019-01-26 01:13:565091 if (has_rids) {
5092 sender_options.rids = send_rids;
5093 }
5094
5095 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-26 01:13:565096 // When RIDs are configured, we must set num_sim_layers to 0 to.
5097 // Otherwise, num_sim_layers must be 1 because either there is no
5098 // simulcast, or simulcast is acheived by munging the SDP.
5099 sender_options.num_sim_layers = has_rids ? 0 : 1;
5100 media_description_options.sender_options.push_back(sender_options);
5101
Steve Antondcc3c022017-12-23 00:02:545102 return media_description_options;
5103}
5104
Steve Anton5c72e712018-12-10 22:25:305105// Returns the ContentInfo at mline index |i|, or null if none exists.
5106static const ContentInfo* GetContentByIndex(
5107 const SessionDescriptionInterface* sdesc,
5108 size_t i) {
5109 if (!sdesc) {
5110 return nullptr;
5111 }
5112 const ContentInfos& contents = sdesc->description()->contents();
5113 return (i < contents.size() ? &contents[i] : nullptr);
5114}
5115
Steve Antondcc3c022017-12-23 00:02:545116void PeerConnection::GetOptionsForUnifiedPlanOffer(
5117 const RTCOfferAnswerOptions& offer_answer_options,
5118 cricket::MediaSessionOptions* session_options) {
5119 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5120 // Offers) and 5.2.2 (Subsequent Offers).
5121 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 18:35:455122 const ContentInfos no_infos;
Steve Antondcc3c022017-12-23 00:02:545123 const ContentInfos& local_contents =
5124 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:455125 : no_infos);
Steve Antondcc3c022017-12-23 00:02:545126 const ContentInfos& remote_contents =
5127 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 18:35:455128 : no_infos);
Steve Antondcc3c022017-12-23 00:02:545129 // The mline indices that can be recycled. New transceivers should reuse these
5130 // slots first.
5131 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-23 00:02:545132 // First, go through each media section that exists in either the local or
5133 // remote description and generate a media section in this offer for the
5134 // associated transceiver. If a media section can be recycled, generate a
5135 // default, rejected media section here that can be later overwritten.
5136 for (size_t i = 0;
5137 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5138 // Either |local_content| or |remote_content| is non-null.
5139 const ContentInfo* local_content =
5140 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:305141 const ContentInfo* current_local_content =
5142 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-23 00:02:545143 const ContentInfo* remote_content =
5144 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:305145 const ContentInfo* current_remote_content =
5146 GetContentByIndex(current_remote_description(), i);
5147 bool had_been_rejected =
5148 (current_local_content && current_local_content->rejected) ||
5149 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-23 00:02:545150 const std::string& mid =
5151 (local_content ? local_content->name : remote_content->name);
5152 cricket::MediaType media_type =
5153 (local_content ? local_content->media_description()->type()
5154 : remote_content->media_description()->type());
5155 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5156 media_type == cricket::MEDIA_TYPE_VIDEO) {
5157 auto transceiver = GetAssociatedTransceiver(mid);
5158 RTC_CHECK(transceiver);
5159 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 22:25:305160 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 23:33:485161 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:545162 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:085163 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5164 RtpTransceiverDirection::kInactive,
5165 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:545166 recycleable_mline_indices.push(i);
5167 } else {
5168 session_options->media_description_options.push_back(
5169 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5170 // CreateOffer shouldn't really cause any state changes in
5171 // PeerConnection, but we need a way to match new transceivers to new
5172 // media sections in SetLocalDescription and JSEP specifies this is done
5173 // by recording the index of the media section generated for the
5174 // transceiver in the offer.
5175 transceiver->internal()->set_mline_index(i);
5176 }
5177 } else {
5178 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonc8ff1602020-02-05 21:53:385179 if (had_been_rejected) {
Steve Antonfa2260d2017-12-29 00:38:235180 session_options->media_description_options.push_back(
5181 GetMediaDescriptionOptionsForRejectedData(mid));
5182 } else {
Steve Antonc8ff1602020-02-05 21:53:385183 RTC_CHECK(GetDataMid());
5184 if (mid == *GetDataMid()) {
5185 session_options->media_description_options.push_back(
5186 GetMediaDescriptionOptionsForActiveData(mid));
5187 } else {
5188 session_options->media_description_options.push_back(
5189 GetMediaDescriptionOptionsForRejectedData(mid));
5190 }
Steve Antonfa2260d2017-12-29 00:38:235191 }
Steve Antondcc3c022017-12-23 00:02:545192 }
5193 }
Amit Hilbuchae3df542019-01-07 20:13:085194
Steve Antondcc3c022017-12-23 00:02:545195 // Next, look for transceivers that are newly added (that is, are not stopped
5196 // and not associated). Reuse media sections marked as recyclable first,
5197 // otherwise append to the end of the offer. New media sections should be
5198 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 16:29:425199 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-23 00:02:545200 if (transceiver->mid() || transceiver->stopped()) {
5201 continue;
5202 }
5203 size_t mline_index;
5204 if (!recycleable_mline_indices.empty()) {
5205 mline_index = recycleable_mline_indices.front();
5206 recycleable_mline_indices.pop();
5207 session_options->media_description_options[mline_index] =
5208 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:085209 mid_generator_());
Steve Antondcc3c022017-12-23 00:02:545210 } else {
5211 mline_index = session_options->media_description_options.size();
5212 session_options->media_description_options.push_back(
5213 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 20:13:085214 mid_generator_()));
Steve Antondcc3c022017-12-23 00:02:545215 }
5216 // See comment above for why CreateOffer changes the transceiver's state.
5217 transceiver->internal()->set_mline_index(mline_index);
5218 }
Steve Antonfa2260d2017-12-29 00:38:235219 // Lastly, add a m-section if we have local data channels and an m section
5220 // does not already exist.
Harald Alvestrand05e4d082019-12-03 13:04:215221 if (!GetDataMid() && data_channel_controller_.HasDataChannels()) {
Steve Antonfa2260d2017-12-29 00:38:235222 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 20:13:085223 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-29 00:38:235224 }
Steve Antondcc3c022017-12-23 00:02:545225}
5226
5227void PeerConnection::GetOptionsForAnswer(
5228 const RTCOfferAnswerOptions& offer_answer_options,
5229 cricket::MediaSessionOptions* session_options) {
5230 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5231
5232 if (IsUnifiedPlan()) {
5233 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5234 } else {
5235 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5236 }
5237
Steve Antonfa2260d2017-12-29 00:38:235238 // Intentionally unset the data channel type for RTP data channel. Otherwise
5239 // the RTP data channels would be successfully negotiated by default and the
5240 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5241 // We want to leave RTP data channels broken, so people won't try to use them.
Harald Alvestrand05e4d082019-12-03 13:04:215242 if (data_channel_controller_.HasRtpDataChannels() ||
5243 data_channel_type() != cricket::DCT_RTP) {
Steve Antonfa2260d2017-12-29 00:38:235244 session_options->data_channel_type = data_channel_type();
5245 }
5246
Steve Antondcc3c022017-12-23 00:02:545247 // Apply ICE renomination flag.
5248 for (auto& options : session_options->media_description_options) {
5249 options.transport_options.enable_ice_renomination =
5250 configuration_.enable_ice_renomination;
5251 }
zhihuang8f65cdf2016-05-07 01:40:305252
5253 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:445254 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:125255 session_options->pooled_ice_credentials =
5256 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5257 RTC_FROM_HERE,
5258 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5259 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 17:28:065260
5261 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 17:44:595262 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 17:28:065263 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 22:12:475264 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 17:28:065265 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 22:12:475266 if (!params) {
5267 continue;
5268 }
5269 options.transport_options.opaque_parameters = params;
5270 if ((use_datagram_transport_ &&
5271 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5272 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5273 (use_datagram_transport_for_data_channels_ &&
5274 options.type == cricket::MEDIA_TYPE_DATA)) {
5275 options.alt_protocol = params->protocol;
5276 }
Bjorn A Mellemc85ebbe2019-06-07 17:28:065277 }
5278 }
deadbeefab9b2d12015-10-14 18:33:115279}
5280
Steve Antondcc3c022017-12-23 00:02:545281void PeerConnection::GetOptionsForPlanBAnswer(
5282 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:115283 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:505284 // Figure out transceiver directional preferences.
5285 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5286 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5287
5288 // By default, generate sendrecv/recvonly m= sections. The direction is also
5289 // restricted by the direction in the offer.
5290 bool recv_audio = true;
5291 bool recv_video = true;
5292
5293 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:545294 if (offer_answer_options.offer_to_receive_audio !=
5295 RTCOfferAnswerOptions::kUndefined) {
5296 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:525297 }
Steve Antondcc3c022017-12-23 00:02:545298 if (offer_answer_options.offer_to_receive_video !=
5299 RTCOfferAnswerOptions::kUndefined) {
5300 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:505301 }
5302
Danil Chapovalov66cadcc2018-06-19 14:47:435303 absl::optional<size_t> audio_index;
5304 absl::optional<size_t> video_index;
5305 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:295306
5307 // Generate m= sections that match those in the offer.
5308 // Note that mediasession.cc will handle intersection our preferred
5309 // direction with the offered direction.
5310 GenerateMediaDescriptionOptions(
5311 remote_description(),
5312 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5313 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5314 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:505315
5316 cricket::MediaDescriptionOptions* audio_media_description_options =
5317 !audio_index ? nullptr
5318 : &session_options->media_description_options[*audio_index];
5319 cricket::MediaDescriptionOptions* video_media_description_options =
5320 !video_index ? nullptr
5321 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:505322
Amit Hilbuchc63ddb22019-01-02 18:13:585323 AddPlanBRtpSenderOptions(GetSendersInternal(),
5324 audio_media_description_options,
5325 video_media_description_options,
5326 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:545327}
zhihuangaf388472016-11-02 23:49:485328
Steve Antondcc3c022017-12-23 00:02:545329void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5330 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5331 cricket::MediaSessionOptions* session_options) {
5332 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5333 // Answers) and 5.3.2 (Subsequent Answers).
5334 RTC_DCHECK(remote_description());
5335 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5336 for (const ContentInfo& content :
5337 remote_description()->description()->contents()) {
5338 cricket::MediaType media_type = content.media_description()->type();
5339 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5340 media_type == cricket::MEDIA_TYPE_VIDEO) {
5341 auto transceiver = GetAssociatedTransceiver(content.name);
5342 RTC_CHECK(transceiver);
5343 session_options->media_description_options.push_back(
5344 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5345 } else {
5346 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:405347 // Reject all data sections if data channels are disabled.
5348 // Reject a data section if it has already been rejected.
5349 // Reject all data sections except for the first one.
Harald Alvestrand05e4d082019-12-03 13:04:215350 if (data_channel_type() == cricket::DCT_NONE || content.rejected ||
Steve Antondbf9d032018-01-19 23:23:405351 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:235352 session_options->media_description_options.push_back(
5353 GetMediaDescriptionOptionsForRejectedData(content.name));
5354 } else {
5355 session_options->media_description_options.push_back(
5356 GetMediaDescriptionOptionsForActiveData(content.name));
5357 }
Steve Antondcc3c022017-12-23 00:02:545358 }
5359 }
htaa2a49d92016-03-04 10:51:395360}
5361
zhihuang1c378ed2017-08-17 21:10:505362void PeerConnection::GenerateMediaDescriptionOptions(
5363 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:095364 RtpTransceiverDirection audio_direction,
5365 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:435366 absl::optional<size_t>* audio_index,
5367 absl::optional<size_t>* video_index,
5368 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:395369 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:505370 for (const cricket::ContentInfo& content :
5371 session_desc->description()->contents()) {
5372 if (IsAudioContent(&content)) {
5373 // If we already have an audio m= section, reject this extra one.
5374 if (*audio_index) {
5375 session_options->media_description_options.push_back(
5376 cricket::MediaDescriptionOptions(
5377 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 22:25:305378 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:505379 } else {
Steve Anton5c72e712018-12-10 22:25:305380 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:505381 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:305382 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5383 content.name, audio_direction,
5384 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:305385 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505386 }
Markus Handell71db9ac2020-06-08 17:48:495387 session_options->media_description_options.back().header_extensions =
5388 channel_manager()->GetSupportedAudioRtpHeaderExtensions();
zhihuang1c378ed2017-08-17 21:10:505389 } else if (IsVideoContent(&content)) {
5390 // If we already have an video m= section, reject this extra one.
5391 if (*video_index) {
5392 session_options->media_description_options.push_back(
5393 cricket::MediaDescriptionOptions(
5394 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 22:25:305395 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:505396 } else {
Steve Anton5c72e712018-12-10 22:25:305397 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:505398 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:305399 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5400 content.name, video_direction,
5401 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:305402 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505403 }
Markus Handell71db9ac2020-06-08 17:48:495404 session_options->media_description_options.back().header_extensions =
5405 channel_manager()->GetSupportedVideoRtpHeaderExtensions();
zhihuang1c378ed2017-08-17 21:10:505406 } else {
5407 RTC_DCHECK(IsDataContent(&content));
5408 // If we already have an data m= section, reject this extra one.
5409 if (*data_index) {
5410 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235411 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:505412 } else {
5413 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:235414 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:305415 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:505416 }
5417 }
htaa2a49d92016-03-04 10:51:395418 }
deadbeefab9b2d12015-10-14 18:33:115419}
5420
Steve Antonfa2260d2017-12-29 00:38:235421cricket::MediaDescriptionOptions
5422PeerConnection::GetMediaDescriptionOptionsForActiveData(
5423 const std::string& mid) const {
5424 // Direction for data sections is meaningless, but legacy endpoints might
5425 // expect sendrecv.
5426 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5427 RtpTransceiverDirection::kSendRecv,
5428 /*stopped=*/false);
Harald Alvestrand05e4d082019-12-03 13:04:215429 AddRtpDataChannelOptions(*data_channel_controller_.rtp_data_channels(),
5430 &options);
Steve Antonfa2260d2017-12-29 00:38:235431 return options;
5432}
5433
5434cricket::MediaDescriptionOptions
5435PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5436 const std::string& mid) const {
5437 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5438 RtpTransceiverDirection::kInactive,
5439 /*stopped=*/true);
Harald Alvestrand05e4d082019-12-03 13:04:215440 AddRtpDataChannelOptions(*data_channel_controller_.rtp_data_channels(),
5441 &options);
Steve Antonfa2260d2017-12-29 00:38:235442 return options;
5443}
5444
Danil Chapovalov66cadcc2018-06-19 14:47:435445absl::optional<std::string> PeerConnection::GetDataMid() const {
Harald Alvestrand05e4d082019-12-03 13:04:215446 switch (data_channel_type()) {
Steve Antonfa2260d2017-12-29 00:38:235447 case cricket::DCT_RTP:
Harald Alvestrand00cf34c2019-12-02 08:56:025448 if (!data_channel_controller_.rtp_data_channel()) {
Danil Chapovalov66cadcc2018-06-19 14:47:435449 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:235450 }
Harald Alvestrand00cf34c2019-12-02 08:56:025451 return data_channel_controller_.rtp_data_channel()->content_name();
Steve Antonfa2260d2017-12-29 00:38:235452 case cricket::DCT_SCTP:
Bjorn A Mellemb689af42019-08-21 17:44:595453 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5454 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Harald Alvestrand7a829a82020-02-12 06:38:215455 return sctp_mid_s_;
Steve Antonfa2260d2017-12-29 00:38:235456 default:
Danil Chapovalov66cadcc2018-06-19 14:47:435457 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:235458 }
5459}
5460
Steve Anton4171afb2017-11-20 18:20:225461void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5462 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5463 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:405464 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:075465}
5466
Steve Anton4171afb2017-11-20 18:20:225467void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:115468 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:225469 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:115470 cricket::MediaType media_type,
5471 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:365472 RTC_DCHECK(!IsUnifiedPlan());
5473
Steve Anton4171afb2017-11-20 18:20:225474 std::vector<RtpSenderInfo>* current_senders =
5475 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:115476
Steve Anton4171afb2017-11-20 18:20:225477 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:015478 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:225479 for (auto sender_it = current_senders->begin();
5480 sender_it != current_senders->end();
5481 /* incremented manually */) {
5482 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:115483 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:225484 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:095485 std::string params_stream_id;
5486 if (params) {
5487 params_stream_id =
5488 (!params->first_stream_id().empty() ? params->first_stream_id()
5489 : kDefaultStreamId);
5490 }
Seth Hampson5b4f0752018-04-02 23:31:365491 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:095492 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:405493 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:105494 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:225495 sender_exists) {
5496 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:405497 } else {
Steve Anton4171afb2017-11-20 18:20:225498 OnRemoteSenderRemoved(info, media_type);
5499 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:115500 }
5501 }
5502
Steve Anton4171afb2017-11-20 18:20:225503 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:115504 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:335505 if (!params.has_ssrcs()) {
5506 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5507 // sender, this means it is coming from a Unified Plan endpoint,so we just
5508 // create a default.
5509 default_sender_needed = true;
5510 break;
5511 }
5512
Seth Hampson845e8782018-03-02 19:34:105513 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:365514 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:335515 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5516 // not supported in Plan B, we just take the first here and create the
5517 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:105518 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:095519 (!params.first_stream_id().empty() ? params.first_stream_id()
5520 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:225521 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:115522 uint32_t ssrc = params.first_ssrc();
5523
5524 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:105525 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:115526 if (!stream) {
5527 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:195528 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:105529 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:115530 remote_streams_->AddStream(stream);
5531 new_streams->AddStream(stream);
5532 }
5533
Steve Anton4171afb2017-11-20 18:20:225534 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185535 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:225536 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:105537 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:225538 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:115539 }
5540 }
deadbeefbda7e0b2015-12-09 01:13:405541
Steve Anton4171afb2017-11-20 18:20:225542 // Add default sender if necessary.
5543 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:405544 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:105545 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:405546 if (!default_stream) {
5547 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:195548 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:105549 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:405550 remote_streams_->AddStream(default_stream);
5551 new_streams->AddStream(default_stream);
5552 }
Steve Anton4171afb2017-11-20 18:20:225553 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5554 ? kDefaultAudioSenderId
5555 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:105556 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185557 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:225558 if (!default_sender_info) {
5559 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 01:07:055560 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 18:20:225561 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:405562 }
5563 }
deadbeefab9b2d12015-10-14 18:33:115564}
5565
Steve Anton4171afb2017-11-20 18:20:225566void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5567 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:235568 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5569 << " receiver for track_id=" << sender_info.sender_id
5570 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:115571
Steve Anton3d954a62018-04-02 18:27:235572 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:115573 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:225574 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:115575 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:225576 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:115577 } else {
nisseeb4ca4e2017-01-12 10:24:275578 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:115579 }
5580}
5581
Steve Anton4171afb2017-11-20 18:20:225582void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5583 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:095584 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5585 << " receiver for track_id=" << sender_info.sender_id
5586 << " and stream_id=" << sender_info.stream_id;
5587
Seth Hampson845e8782018-03-02 19:34:105588 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:115589
Henrik Boström933d8b02017-10-10 17:05:165590 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:115591 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:195592 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5593 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:225594 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:115595 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:225596 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:115597 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:115598 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:115599 }
5600 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:195601 // Stopping or destroying a VideoRtpReceiver will end the
5602 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:225603 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:115604 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:225605 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:115606 if (video_track) {
perkjd61bf802016-03-24 10:16:195607 // There's no guarantee the track is still available, e.g. the track may
5608 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:115609 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:115610 }
5611 } else {
nisseede5da42017-01-12 13:15:365612 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:115613 }
Henrik Boström933d8b02017-10-10 17:05:165614 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:165615 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:165616 }
deadbeefab9b2d12015-10-14 18:33:115617}
5618
5619void PeerConnection::UpdateEndedRemoteMediaStreams() {
5620 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5621 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5622 MediaStreamInterface* stream = remote_streams_->at(i);
5623 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5624 streams_to_remove.push_back(stream);
5625 }
5626 }
5627
Taylor Brandstetter98cde262016-05-31 20:02:215628 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:115629 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:165630 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:115631 }
5632}
5633
Steve Anton4171afb2017-11-20 18:20:225634void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:115635 const std::vector<cricket::StreamParams>& streams,
5636 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:225637 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:115638
Seth Hampson845e8782018-03-02 19:34:105639 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:115640 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:225641 for (auto sender_it = current_senders->begin();
5642 sender_it != current_senders->end();
5643 /* incremented manually */) {
5644 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:115645 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:225646 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5647 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:105648 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:225649 OnLocalSenderRemoved(info, media_type);
5650 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:115651 } else {
Steve Anton4171afb2017-11-20 18:20:225652 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:115653 }
5654 }
5655
Steve Anton4171afb2017-11-20 18:20:225656 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:115657 for (const cricket::StreamParams& params : streams) {
5658 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:225659 // sender id.
Seth Hampson845e8782018-03-02 19:34:105660 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:225661 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:115662 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:225663 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:185664 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:225665 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:105666 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:225667 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:115668 }
5669 }
5670}
5671
Steve Anton4171afb2017-11-20 18:20:225672void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5673 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:365674 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:225675 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:015676 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:225677 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5678 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:255679 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:115680 return;
5681 }
5682
deadbeeffac06552015-11-25 19:26:015683 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:255684 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075685 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015686 return;
deadbeefab9b2d12015-10-14 18:33:115687 }
deadbeeffac06552015-11-25 19:26:015688
Henrik Andreasssoncc189172019-05-20 09:01:385689 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:225690 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:115691}
5692
Steve Anton4171afb2017-11-20 18:20:225693void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5694 cricket::MediaType media_type) {
5695 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:015696 if (!sender) {
5697 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:115698 // SessionDescriptions has been renegotiated.
5699 return;
5700 }
deadbeeffac06552015-11-25 19:26:015701
5702 // A sender has been removed from the SessionDescription but it's still
5703 // associated with the PeerConnection. This only occurs if the SDP doesn't
5704 // match with the calls to CreateSender, AddStream and RemoveStream.
5705 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:255706 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:075707 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:015708 return;
deadbeefab9b2d12015-10-14 18:33:115709 }
deadbeeffac06552015-11-25 19:26:015710
Steve Anton4171afb2017-11-20 18:20:225711 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:115712}
5713
Harald Alvestrand00cf34c2019-12-02 08:56:025714void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
5715 // Since data_channel_controller doesn't do signals, this
5716 // signal is relayed here.
5717 data_channel_controller_.OnSctpDataChannelClosed(channel);
deadbeefab9b2d12015-10-14 18:33:115718}
5719
Steve Anton4171afb2017-11-20 18:20:225720rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5721PeerConnection::GetAudioTransceiver() const {
5722 // This method only works with Plan B SDP, where there is a single
5723 // audio/video transceiver.
5724 RTC_DCHECK(!IsUnifiedPlan());
5725 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085726 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:225727 return transceiver;
5728 }
5729 }
5730 RTC_NOTREACHED();
5731 return nullptr;
5732}
5733
5734rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5735PeerConnection::GetVideoTransceiver() const {
5736 // This method only works with Plan B SDP, where there is a single
5737 // audio/video transceiver.
5738 RTC_DCHECK(!IsUnifiedPlan());
5739 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:085740 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:225741 return transceiver;
5742 }
5743 }
5744 RTC_NOTREACHED();
5745 return nullptr;
5746}
5747
5748// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5749// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:505750bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:225751 switch (type) {
5752 case cricket::MEDIA_TYPE_AUDIO:
5753 return !GetAudioTransceiver()->internal()->senders().empty();
5754 case cricket::MEDIA_TYPE_VIDEO:
5755 return !GetVideoTransceiver()->internal()->senders().empty();
5756 case cricket::MEDIA_TYPE_DATA:
5757 return false;
5758 }
5759 RTC_NOTREACHED();
5760 return false;
zhihuang1c378ed2017-08-17 21:10:505761}
5762
Steve Anton4171afb2017-11-20 18:20:225763rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5764PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 16:29:425765 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225766 for (auto sender : transceiver->internal()->senders()) {
5767 if (sender->track() == track) {
5768 return sender;
5769 }
5770 }
5771 }
5772 return nullptr;
deadbeeffac06552015-11-25 19:26:015773}
5774
Steve Anton4171afb2017-11-20 18:20:225775rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5776PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 16:29:425777 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225778 for (auto sender : transceiver->internal()->senders()) {
5779 if (sender->id() == sender_id) {
5780 return sender;
5781 }
5782 }
5783 }
5784 return nullptr;
deadbeef70ab1a12015-09-28 23:53:555785}
5786
Steve Anton4171afb2017-11-20 18:20:225787rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5788PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 16:29:425789 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 18:20:225790 for (auto receiver : transceiver->internal()->receivers()) {
5791 if (receiver->id() == receiver_id) {
5792 return receiver;
5793 }
5794 }
5795 }
5796 return nullptr;
deadbeef70ab1a12015-09-28 23:53:555797}
5798
Steve Anton4171afb2017-11-20 18:20:225799std::vector<PeerConnection::RtpSenderInfo>*
5800PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5801 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5802 media_type == cricket::MEDIA_TYPE_VIDEO);
5803 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5804 ? &remote_audio_sender_infos_
5805 : &remote_video_sender_infos_;
5806}
5807
5808std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:115809 cricket::MediaType media_type) {
5810 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5811 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:225812 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5813 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:115814}
5815
Steve Anton4171afb2017-11-20 18:20:225816const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5817 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:185818 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:225819 const std::string sender_id) const {
5820 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:185821 if (sender_info.stream_id == stream_id &&
5822 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:225823 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:115824 }
5825 }
5826 return nullptr;
5827}
5828
5829DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
Harald Alvestrand05e4d082019-12-03 13:04:215830 return data_channel_controller_.FindDataChannelBySid(sid);
deadbeefab9b2d12015-10-14 18:33:115831}
5832
Karl Wibergfb3be392019-03-22 13:13:225833PeerConnection::InitializePortAllocatorResult
5834PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:075835 const cricket::ServerAddresses& stun_servers,
5836 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:115837 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 13:13:225838 RTC_DCHECK_RUN_ON(network_thread());
5839
Taylor Brandstetterf8e65772016-06-28 00:20:155840 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:115841 // To handle both internal and externally created port allocator, we will
5842 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 13:13:225843 int port_allocator_flags = port_allocator_->flags();
5844 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5845 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5846 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:115847 // If the disable-IPv6 flag was specified, we'll not override it
5848 // by experiment.
5849 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 13:13:225850 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Mirko Bonadei57cabed2020-04-01 10:03:115851 } else if (absl::StartsWith(
5852 webrtc::field_trial::FindFullName("WebRTC-IPv6Default"),
5853 "Disabled")) {
Karl Wibergfb3be392019-03-22 13:13:225854 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:115855 }
5856
zhihuangb09b3f92017-03-07 22:40:515857 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 13:13:225858 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:255859 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:515860 }
5861
Taylor Brandstettera1c30352016-05-13 15:15:115862 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 13:13:225863 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:255864 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:115865 }
5866
honghaiz60347052016-06-01 01:29:125867 if (configuration.candidate_network_policy ==
5868 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 13:13:225869 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:255870 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:125871 }
5872
Daniel Lazarenko2870b0a2018-01-25 09:30:225873 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 13:13:225874 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:225875 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5876 }
5877
Karl Wibergfb3be392019-03-22 13:13:225878 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 15:15:115879 // No step delay is used while allocating ports.
5880 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 17:41:585881 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 15:15:115882 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:115883 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:115884
Harald Alvestrandb2a74782018-06-28 11:54:075885 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:265886 for (auto& turn_server : turn_servers_copy) {
5887 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:255888 }
Taylor Brandstettera1c30352016-05-13 15:15:115889 // Call this last since it may create pooled allocator sessions using the
5890 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:495891 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265892 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 18:27:505893 configuration.ice_candidate_pool_size,
5894 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:495895 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 13:13:225896
5897 InitializePortAllocatorResult res;
5898 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5899 return res;
Taylor Brandstettera1c30352016-05-13 15:15:115900}
5901
deadbeef91dd5672016-05-18 23:55:305902bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:305903 const cricket::ServerAddresses& stun_servers,
5904 const std::vector<cricket::RelayServerConfig>& turn_servers,
5905 IceTransportsType type,
5906 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:505907 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 22:45:495908 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 09:37:285909 absl::optional<int> stun_candidate_keepalive_interval,
5910 bool have_local_description) {
Qingsi Wangc129c352019-04-18 17:41:585911 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 20:28:305912 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:455913 // According to JSEP, after setLocalDescription, changing the candidate pool
5914 // size is not allowed, and changing the set of ICE servers will not result
5915 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 09:37:285916 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 23:57:455917 port_allocator_->FreezeCandidatePool();
5918 }
Benjamin Wright6f80f092018-08-14 00:06:265919 // Add the custom tls turn servers if they exist.
5920 auto turn_servers_copy = turn_servers;
5921 for (auto& turn_server : turn_servers_copy) {
5922 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5923 }
Taylor Brandstettera1c30352016-05-13 15:15:115924 // Call this last since it may create pooled allocator sessions using the
5925 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:325926 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265927 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 18:27:505928 turn_port_prune_policy, turn_customizer,
5929 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:115930}
5931
Steve Antonba818672017-11-06 18:21:575932cricket::ChannelManager* PeerConnection::channel_manager() const {
5933 return factory_->channel_manager();
5934}
5935
Elad Alon99c3fe52017-10-13 14:29:405936bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:145937 std::unique_ptr<RtcEventLogOutput> output,
5938 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 10:59:575939 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:165940 if (!event_log_) {
5941 return false;
5942 }
Bjorn Tereliusde939432017-11-20 16:38:145943 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:555944}
5945
5946void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 10:59:575947 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 23:45:165948 if (event_log_) {
5949 event_log_->StopLogging();
5950 }
ivoc14d5dbe2016-07-04 14:06:555951}
nisseeaabdf62017-05-05 09:23:025952
Amit Hilbuchdd9390c2018-11-14 00:26:055953cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:175954 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 16:29:425955 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055956 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:545957 if (channel && channel->content_name() == content_name) {
5958 return channel;
5959 }
Steve Anton75737c02017-11-06 18:37:175960 }
5961 if (rtp_data_channel() &&
5962 rtp_data_channel()->content_name() == content_name) {
5963 return rtp_data_channel();
5964 }
5965 return nullptr;
5966}
5967
5968bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 19:23:225969 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175970 if (!local_description() || !remote_description()) {
Harald Alvestrand977b2652019-12-12 12:40:505971 RTC_LOG(LS_VERBOSE)
Mirko Bonadei675513b2017-11-09 10:09:255972 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075973 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175974 return false;
5975 }
Harald Alvestrand00cf34c2019-12-02 08:56:025976 if (!data_channel_controller_.data_channel_transport()) {
Mirko Bonadei675513b2017-11-09 10:09:255977 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:075978 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175979 return false;
5980 }
5981
Bjorn Mellem175aa2e2018-11-08 19:23:225982 absl::optional<rtc::SSLRole> dtls_role;
Harald Alvestrand7a829a82020-02-12 06:38:215983 if (sctp_mid_s_) {
5984 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_s_);
Bjorn A Mellembc3eebc2019-09-23 21:53:545985 if (!dtls_role && is_caller_.has_value()) {
5986 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5987 }
Zhi Huange830e682018-03-30 17:48:355988 *role = *dtls_role;
5989 return true;
5990 }
5991 return false;
Steve Anton75737c02017-11-06 18:37:175992}
5993
5994bool PeerConnection::GetSslRole(const std::string& content_name,
5995 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 09:31:565996 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175997 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255998 RTC_LOG(LS_INFO)
5999 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:076000 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:176001 return false;
6002 }
6003
Zhi Huange830e682018-03-30 17:48:356004 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
6005 if (dtls_role) {
6006 *role = *dtls_role;
6007 return true;
6008 }
6009 return false;
Steve Anton75737c02017-11-06 18:37:176010}
6011
Steve Antonf8470812017-12-04 18:46:216012void PeerConnection::SetSessionError(SessionError error,
6013 const std::string& error_desc) {
6014 RTC_DCHECK_RUN_ON(signaling_thread());
6015 if (error != session_error_) {
6016 session_error_ = error;
6017 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:176018 }
6019}
6020
Zhi Huange830e682018-03-30 17:48:356021RTCError PeerConnection::UpdateSessionState(
6022 SdpType type,
6023 cricket::ContentSource source,
6024 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:566025 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176026
6027 // If there's already a pending error then no state transition should happen.
6028 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:216029 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:476030
Steve Anton6d6a2ae2017-12-05 01:19:476031 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:516032 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:596033 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:476034 }
6035
6036 // Update the signaling state according to the specified state machine (see
6037 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:516038 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:476039 ChangeSignalingState(source == cricket::CS_LOCAL
6040 ? PeerConnectionInterface::kHaveLocalOffer
6041 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:516042 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:476043 ChangeSignalingState(source == cricket::CS_LOCAL
6044 ? PeerConnectionInterface::kHaveLocalPrAnswer
6045 : PeerConnectionInterface::kHaveRemotePrAnswer);
6046 } else {
Steve Anton3828c062017-12-06 18:34:516047 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:476048 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 15:29:446049 transceiver_stable_states_by_transceivers_.clear();
Eldar Rellod9ebe012020-03-18 18:41:456050 have_pending_rtp_data_channel_ = false;
Steve Anton6d6a2ae2017-12-05 01:19:476051 }
6052
6053 // Update internal objects according to the session description's media
6054 // descriptions.
Zhi Huange830e682018-03-30 17:48:356055 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:476056 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:426057 return error;
Steve Anton6d6a2ae2017-12-05 01:19:476058 }
6059
Steve Anton8a006912017-12-04 23:25:566060 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176061}
6062
Steve Anton8a006912017-12-04 23:25:566063RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:516064 SdpType type,
Steve Anton8a006912017-12-04 23:25:566065 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:596066 const SessionDescriptionInterface* sdesc =
6067 (source == cricket::CS_LOCAL ? local_description()
6068 : remote_description());
Steve Anton75737c02017-11-06 18:37:176069 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:596070
6071 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 16:29:426072 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:176073 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:596074 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:056075 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:596076 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:176077 continue;
6078 }
6079 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:306080 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:596081 if (!content_desc) {
6082 continue;
6083 }
6084 std::string error;
Yves Gerey665174f2018-06-19 13:03:056085 bool success = (source == cricket::CS_LOCAL)
6086 ? channel->SetLocalContent(content_desc, type, &error)
6087 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:596088 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:576089 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:596090 }
6091 }
6092
6093 // If using the RtpDataChannel, push down the new SDP section for it too.
Harald Alvestrand00cf34c2019-12-02 08:56:026094 if (data_channel_controller_.rtp_data_channel()) {
Steve Antoned10bd92017-12-05 18:52:596095 const ContentInfo* data_content =
6096 cricket::GetFirstDataContent(sdesc->description());
6097 if (data_content && !data_content->rejected) {
6098 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:306099 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:596100 if (data_desc) {
6101 std::string error;
6102 bool success =
6103 (source == cricket::CS_LOCAL)
Harald Alvestrand00cf34c2019-12-02 08:56:026104 ? data_channel_controller_.rtp_data_channel()->SetLocalContent(
6105 data_desc, type, &error)
6106 : data_channel_controller_.rtp_data_channel()->SetRemoteContent(
6107 data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:596108 if (!success) {
Yves Gereyae6e0b22019-01-22 20:48:576109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 18:52:596110 }
Steve Anton75737c02017-11-06 18:37:176111 }
6112 }
6113 }
Steve Antoned10bd92017-12-05 18:52:596114
Steve Anton75737c02017-11-06 18:37:176115 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6116 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrand7a829a82020-02-12 06:38:216117 if (sctp_mid_s_ && local_description() && remote_description()) {
Bjorn A Mellembc3eebc2019-09-23 21:53:546118 rtc::scoped_refptr<SctpTransport> sctp_transport =
Harald Alvestrand7a829a82020-02-12 06:38:216119 transport_controller_->GetSctpTransport(*sctp_mid_s_);
Harald Alvestrandfbb45bd2019-05-15 06:07:476120 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6121 local_description()->description());
6122 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6123 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 21:53:546124 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 09:49:176125 int max_message_size;
6126 // A remote max message size of zero means "any size supported".
6127 // We configure the connection with our own max message size.
6128 if (remote_sctp_description->max_message_size() == 0) {
6129 max_message_size = local_sctp_description->max_message_size();
6130 } else {
6131 max_message_size =
6132 std::min(local_sctp_description->max_message_size(),
6133 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 06:07:476134 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546135 sctp_transport->Start(local_sctp_description->port(),
6136 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 23:25:566137 }
Steve Anton75737c02017-11-06 18:37:176138 }
Steve Antoned10bd92017-12-05 18:52:596139
Steve Anton8a006912017-12-04 23:25:566140 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176141}
6142
Steve Anton8a006912017-12-04 23:25:566143RTCError PeerConnection::PushdownTransportDescription(
6144 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:516145 SdpType type) {
Steve Anton8a006912017-12-04 23:25:566146 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176147
Zhi Huange830e682018-03-30 17:48:356148 if (source == cricket::CS_LOCAL) {
6149 const SessionDescriptionInterface* sdesc = local_description();
6150 RTC_DCHECK(sdesc);
6151 return transport_controller_->SetLocalDescription(type,
6152 sdesc->description());
6153 } else {
6154 const SessionDescriptionInterface* sdesc = remote_description();
6155 RTC_DCHECK(sdesc);
6156 return transport_controller_->SetRemoteDescription(type,
6157 sdesc->description());
Steve Anton75737c02017-11-06 18:37:176158 }
Steve Anton75737c02017-11-06 18:37:176159}
6160
6161bool PeerConnection::GetTransportDescription(
6162 const SessionDescription* description,
6163 const std::string& content_name,
6164 cricket::TransportDescription* tdesc) {
6165 if (!description || !tdesc) {
6166 return false;
6167 }
6168 const TransportInfo* transport_info =
6169 description->GetTransportInfoByName(content_name);
6170 if (!transport_info) {
6171 return false;
6172 }
6173 *tdesc = transport_info->description;
6174 return true;
6175}
6176
Steve Anton75737c02017-11-06 18:37:176177cricket::IceConfig PeerConnection::ParseIceConfig(
6178 const PeerConnectionInterface::RTCConfiguration& config) const {
6179 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:176180 switch (config.continual_gathering_policy) {
6181 case PeerConnectionInterface::GATHER_ONCE:
6182 gathering_policy = cricket::GATHER_ONCE;
6183 break;
6184 case PeerConnectionInterface::GATHER_CONTINUALLY:
6185 gathering_policy = cricket::GATHER_CONTINUALLY;
6186 break;
6187 default:
6188 RTC_NOTREACHED();
6189 gathering_policy = cricket::GATHER_ONCE;
6190 }
Qingsi Wang9a5c6f82018-02-01 18:38:406191
Steve Anton75737c02017-11-06 18:37:176192 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:236193 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6194 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:176195 ice_config.prioritize_most_likely_candidate_pairs =
6196 config.prioritize_most_likely_ice_candidate_pairs;
6197 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:236198 RTCConfigurationToIceConfigOptionalInt(
6199 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:176200 ice_config.continual_gathering_policy = gathering_policy;
6201 ice_config.presume_writable_when_fully_relayed =
6202 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 23:55:336203 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6204 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 22:55:146205 ice_config.ice_check_interval_strong_connectivity =
6206 config.ice_check_interval_strong_connectivity;
6207 ice_config.ice_check_interval_weak_connectivity =
6208 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:176209 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-30 07:08:516210 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6211 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:176212 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:496213 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Qingsi Wang9a5c6f82018-02-01 18:38:406214 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:176215 return ice_config;
6216}
6217
Danil Chapovalov66cadcc2018-06-19 14:47:436218absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 09:31:566219 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand7a829a82020-02-12 06:38:216220 if (sctp_mid_s_ && transport_controller_) {
6221 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_s_);
Zhi Huange830e682018-03-30 17:48:356222 if (dtls_transport) {
6223 return dtls_transport->transport_name();
6224 }
Danil Chapovalov66cadcc2018-06-19 14:47:436225 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:356226 }
Danil Chapovalov66cadcc2018-06-19 14:47:436227 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:356228}
6229
Qingsi Wang72a43a12018-02-21 00:03:186230cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6231 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:456232 network_thread()->Invoke<void>(
6233 RTC_FROM_HERE,
6234 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6235 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:186236 return candidate_states_list;
6237}
6238
Steve Anton5dfde182018-02-06 18:34:406239std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6240 const {
Karl Wiberga58e1692019-03-26 12:33:436241 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 18:34:406242 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 16:29:426243 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056244 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:406245 if (channel) {
6246 transport_names_by_mid[channel->content_name()] =
6247 channel->transport_name();
6248 }
Steve Anton75737c02017-11-06 18:37:176249 }
Harald Alvestrand00cf34c2019-12-02 08:56:026250 if (data_channel_controller_.rtp_data_channel()) {
6251 transport_names_by_mid[data_channel_controller_.rtp_data_channel()
6252 ->content_name()] =
6253 data_channel_controller_.rtp_data_channel()->transport_name();
Steve Anton75737c02017-11-06 18:37:176254 }
Harald Alvestrand00cf34c2019-12-02 08:56:026255 if (data_channel_controller_.data_channel_transport()) {
Danil Chapovalov66cadcc2018-06-19 14:47:436256 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356257 RTC_DCHECK(transport_name);
Harald Alvestrand7a829a82020-02-12 06:38:216258 transport_names_by_mid[*sctp_mid_s_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:176259 }
Steve Anton5dfde182018-02-06 18:34:406260 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:176261}
6262
Steve Anton5dfde182018-02-06 18:34:406263std::map<std::string, cricket::TransportStats>
6264PeerConnection::GetTransportStatsByNames(
6265 const std::set<std::string>& transport_names) {
6266 if (!network_thread()->IsCurrent()) {
6267 return network_thread()
6268 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6269 RTC_FROM_HERE,
6270 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:176271 }
Karl Wiberg2cc368f2019-04-02 09:31:566272 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 18:34:406273 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6274 for (const std::string& transport_name : transport_names) {
6275 cricket::TransportStats transport_stats;
6276 bool success =
6277 transport_controller_->GetStats(transport_name, &transport_stats);
6278 if (success) {
6279 transport_stats_by_name[transport_name] = std::move(transport_stats);
6280 } else {
6281 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6282 << transport_name;
6283 }
6284 }
6285 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:176286}
6287
6288bool PeerConnection::GetLocalCertificate(
6289 const std::string& transport_name,
6290 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:356291 if (!certificate) {
6292 return false;
6293 }
6294 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6295 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:176296}
6297
Taylor Brandstetterc3928662018-02-23 21:04:516298std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:176299 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:516300 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:176301}
6302
6303cricket::DataChannelType PeerConnection::data_channel_type() const {
Harald Alvestrand05e4d082019-12-03 13:04:216304 return data_channel_controller_.data_channel_type();
Steve Anton75737c02017-11-06 18:37:176305}
6306
6307bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 13:36:536308 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:176309 return pending_ice_restarts_.find(content_name) !=
6310 pending_ice_restarts_.end();
6311}
6312
Steve Anton75737c02017-11-06 18:37:176313bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6314 return transport_controller_->NeedsIceRestart(content_name);
6315}
6316
6317void PeerConnection::OnCertificateReady(
6318 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6319 transport_controller_->SetLocalCertificate(certificate);
6320}
6321
6322void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:216323 SetSessionError(SessionError::kTransport,
6324 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:176325}
6326
Alex Loiko9289eda2018-11-23 16:18:596327void PeerConnection::OnTransportControllerConnectionState(
6328 cricket::IceConnectionState state) {
6329 switch (state) {
6330 case cricket::kIceConnectionConnecting:
6331 // If the current state is Connected or Completed, then there were
6332 // writable channels but now there are not, so the next state must
6333 // be Disconnected.
6334 // kIceConnectionConnecting is currently used as the default,
6335 // un-connected state by the TransportController, so its only use is
6336 // detecting disconnections.
6337 if (ice_connection_state_ ==
6338 PeerConnectionInterface::kIceConnectionConnected ||
6339 ice_connection_state_ ==
6340 PeerConnectionInterface::kIceConnectionCompleted) {
6341 SetIceConnectionState(
6342 PeerConnectionInterface::kIceConnectionDisconnected);
6343 }
6344 break;
6345 case cricket::kIceConnectionFailed:
6346 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6347 break;
6348 case cricket::kIceConnectionConnected:
6349 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6350 "all transports are writable.";
6351 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6352 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6353 break;
6354 case cricket::kIceConnectionCompleted:
6355 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6356 "all transports are complete.";
6357 if (ice_connection_state_ !=
6358 PeerConnectionInterface::kIceConnectionConnected) {
6359 // If jumping directly from "checking" to "connected",
6360 // signal "connected" first.
6361 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6362 }
6363 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6364 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6365 ReportTransportStats();
6366 break;
6367 default:
6368 RTC_NOTREACHED();
6369 }
6370}
6371
Steve Anton75737c02017-11-06 18:37:176372void PeerConnection::OnTransportControllerCandidatesGathered(
6373 const std::string& transport_name,
6374 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 18:37:176375 int sdp_mline_index;
6376 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:256377 RTC_LOG(LS_ERROR)
6378 << "OnTransportControllerCandidatesGathered: content name "
6379 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:176380 return;
6381 }
6382
6383 for (cricket::Candidates::const_iterator citer = candidates.begin();
6384 citer != candidates.end(); ++citer) {
6385 // Use transport_name as the candidate media id.
6386 std::unique_ptr<JsepIceCandidate> candidate(
6387 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6388 if (local_description()) {
6389 mutable_local_description()->AddCandidate(candidate.get());
6390 }
6391 OnIceCandidate(std::move(candidate));
6392 }
6393}
6394
Eldar Relloda13ea22019-06-01 09:23:436395void PeerConnection::OnTransportControllerCandidateError(
6396 const cricket::IceCandidateErrorEvent& event) {
Eldar Rello0095d372019-12-02 20:22:076397 OnIceCandidateError(event.address, event.port, event.url, event.error_code,
Eldar Relloda13ea22019-06-01 09:23:436398 event.error_text);
6399}
6400
Steve Anton75737c02017-11-06 18:37:176401void PeerConnection::OnTransportControllerCandidatesRemoved(
6402 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 18:37:176403 // Sanity check.
6404 for (const cricket::Candidate& candidate : candidates) {
6405 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:256406 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:076407 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:256408 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:176409 return;
6410 }
6411 }
6412
6413 if (local_description()) {
6414 mutable_local_description()->RemoveCandidates(candidates);
6415 }
6416 OnIceCandidatesRemoved(candidates);
6417}
6418
Alex Drake00c7ecf2019-08-06 17:54:476419void PeerConnection::OnTransportControllerCandidateChanged(
6420 const cricket::CandidatePairChangeEvent& event) {
6421 OnSelectedCandidatePairChanged(event);
6422}
6423
Steve Anton75737c02017-11-06 18:37:176424void PeerConnection::OnTransportControllerDtlsHandshakeError(
6425 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:536426 RTC_HISTOGRAM_ENUMERATION(
6427 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6428 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:176429}
6430
Steve Antoned10bd92017-12-05 18:52:596431void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 16:29:426432 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:056433 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:596434 if (channel && !channel->enabled()) {
6435 channel->Enable(true);
6436 }
Steve Anton75737c02017-11-06 18:37:176437 }
6438
Harald Alvestrand00cf34c2019-12-02 08:56:026439 if (data_channel_controller_.rtp_data_channel() &&
6440 !data_channel_controller_.rtp_data_channel()->enabled()) {
6441 data_channel_controller_.rtp_data_channel()->Enable(true);
Steve Anton4171afb2017-11-20 18:20:226442 }
Steve Anton75737c02017-11-06 18:37:176443}
6444
6445// Returns the media index for a local ice candidate given the content name.
6446bool PeerConnection::GetLocalCandidateMediaIndex(
6447 const std::string& content_name,
6448 int* sdp_mline_index) {
6449 if (!local_description() || !sdp_mline_index) {
6450 return false;
6451 }
6452
6453 bool content_found = false;
6454 const ContentInfos& contents = local_description()->description()->contents();
6455 for (size_t index = 0; index < contents.size(); ++index) {
6456 if (contents[index].name == content_name) {
6457 *sdp_mline_index = static_cast<int>(index);
6458 content_found = true;
6459 break;
6460 }
6461 }
6462 return content_found;
6463}
6464
6465bool PeerConnection::UseCandidatesInSessionDescription(
6466 const SessionDescriptionInterface* remote_desc) {
6467 if (!remote_desc) {
6468 return true;
6469 }
6470 bool ret = true;
6471
6472 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6473 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6474 for (size_t n = 0; n < candidates->count(); ++n) {
6475 const IceCandidateInterface* candidate = candidates->at(n);
6476 bool valid = false;
6477 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6478 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:256479 RTC_LOG(LS_INFO)
6480 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:076481 "candidate.";
Steve Anton75737c02017-11-06 18:37:176482 }
6483 continue;
6484 }
6485 ret = UseCandidate(candidate);
6486 if (!ret) {
6487 break;
6488 }
6489 }
6490 }
6491 return ret;
6492}
6493
6494bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 18:12:296495 RTCErrorOr<const cricket::ContentInfo*> result =
6496 FindContentInfo(remote_description(), candidate);
6497 if (!result.ok()) {
6498 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6499 << result.error().message();
Steve Anton75737c02017-11-06 18:37:176500 return false;
6501 }
Steve Anton75737c02017-11-06 18:37:176502 std::vector<cricket::Candidate> candidates;
6503 candidates.push_back(candidate->candidate());
6504 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 18:12:296505 RTCError error = transport_controller_->AddRemoteCandidates(
6506 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:506507 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 18:57:176508 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:506509 // Candidates successfully submitted for checking.
6510 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6511 ice_connection_state_ ==
6512 PeerConnectionInterface::kIceConnectionDisconnected) {
6513 // If state is New, then the session has just gotten its first remote ICE
6514 // candidates, so go to Checking.
6515 // If state is Disconnected, the session is re-using old candidates or
6516 // receiving additional ones, so go to Checking.
6517 // If state is Connected, stay Connected.
6518 // TODO(bemasc): If state is Connected, and the new candidates are for a
6519 // newly added transport, then the state actually _should_ move to
6520 // checking. Add a way to distinguish that case.
6521 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6522 }
6523 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:076524 } else {
Zhi Huange830e682018-03-30 17:48:356525 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:176526 }
6527 return true;
6528}
6529
Guido Urdaneta41633172019-05-23 18:12:296530RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6531 const SessionDescriptionInterface* description,
6532 const IceCandidateInterface* candidate) {
6533 if (candidate->sdp_mline_index() >= 0) {
6534 size_t mediacontent_index =
6535 static_cast<size_t>(candidate->sdp_mline_index());
6536 size_t content_size = description->description()->contents().size();
6537 if (mediacontent_index < content_size) {
6538 return &description->description()->contents()[mediacontent_index];
6539 } else {
6540 return RTCError(RTCErrorType::INVALID_RANGE,
6541 "Media line index (" +
6542 rtc::ToString(candidate->sdp_mline_index()) +
6543 ") out of range (number of mlines: " +
6544 rtc::ToString(content_size) + ").");
6545 }
6546 } else if (!candidate->sdp_mid().empty()) {
6547 auto& contents = description->description()->contents();
6548 auto it = absl::c_find_if(
6549 contents, [candidate](const cricket::ContentInfo& content_info) {
6550 return content_info.mid() == candidate->sdp_mid();
6551 });
6552 if (it == contents.end()) {
6553 return RTCError(
6554 RTCErrorType::INVALID_PARAMETER,
6555 "Mid " + candidate->sdp_mid() +
6556 " specified but no media section with that mid found.");
6557 } else {
6558 return &*it;
6559 }
6560 }
6561
6562 return RTCError(RTCErrorType::INVALID_PARAMETER,
6563 "Neither sdp_mline_index nor sdp_mid specified.");
6564}
6565
Steve Anton75737c02017-11-06 18:37:176566void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:176567 // Destroy video channel first since it may have a pointer to the
6568 // voice channel.
6569 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:296570 if (!video_info || video_info->rejected) {
6571 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:176572 }
6573
Steve Anton6fec8802017-12-04 18:37:296574 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6575 if (!audio_info || audio_info->rejected) {
6576 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:176577 }
6578
6579 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6580 if (!data_info || data_info->rejected) {
Harald Alvestrand408cb4b2019-11-16 11:09:086581 DestroyDataChannelTransport();
Steve Anton75737c02017-11-06 18:37:176582 }
6583}
6584
Steve Antondcc3c022017-12-23 00:02:546585RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6586 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:176587 const cricket::ContentGroup* bundle_group = nullptr;
6588 if (configuration_.bundle_policy ==
6589 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:546590 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:176591 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:566592 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6593 "max-bundle configured but session description "
6594 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:176595 }
6596 }
Mirko Bonadei9f3a44f2019-01-30 12:47:426597 return bundle_group;
Steve Antondcc3c022017-12-23 00:02:546598}
6599
6600RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:356601 // Creating the media channels. Transports should already have been created
6602 // at this point.
Steve Antondcc3c022017-12-23 00:02:546603 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:556604 if (voice && !voice->rejected &&
6605 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:356606 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:556607 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:566608 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6609 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:556610 }
6611 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6612 }
6613
Steve Antondcc3c022017-12-23 00:02:546614 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:556615 if (video && !video->rejected &&
6616 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:356617 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:556618 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:566619 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6620 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:176621 }
Steve Antoneda6ccd2017-12-04 18:21:556622 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:176623 }
6624
Steve Antondcc3c022017-12-23 00:02:546625 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Harald Alvestrand05e4d082019-12-03 13:04:216626 if (data_channel_type() != cricket::DCT_NONE && data && !data->rejected &&
Harald Alvestrand00cf34c2019-12-02 08:56:026627 !data_channel_controller_.rtp_data_channel() &&
6628 !data_channel_controller_.data_channel_transport()) {
Zhi Huange830e682018-03-30 17:48:356629 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:566630 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6631 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:176632 }
6633 }
6634
Steve Anton8a006912017-12-04 23:25:566635 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176636}
6637
Steve Anton4171afb2017-11-20 18:20:226638// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:556639cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:356640 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:426641 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 22:50:386642 MediaTransportConfig media_transport_config =
6643 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 20:15:426644
Steve Anton75737c02017-11-06 18:37:176645 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 18:12:576646 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 22:50:386647 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6648 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 18:37:176649 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:556650 return nullptr;
Steve Anton75737c02017-11-06 18:37:176651 }
Steve Anton75737c02017-11-06 18:37:176652 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6653 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:176654 voice_channel->SignalSentPacket.connect(this,
6655 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:356656 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:226657
Steve Antoneda6ccd2017-12-04 18:21:556658 return voice_channel;
Steve Anton75737c02017-11-06 18:37:176659}
6660
Steve Anton4171afb2017-11-20 18:20:226661// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:556662cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:356663 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:426664 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 22:50:386665 MediaTransportConfig media_transport_config =
6666 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 20:15:426667
Steve Anton75737c02017-11-06 18:37:176668 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 18:12:576669 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 22:50:386670 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6671 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 18:12:576672 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 18:37:176673 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:556674 return nullptr;
Steve Anton75737c02017-11-06 18:37:176675 }
Steve Anton75737c02017-11-06 18:37:176676 video_channel->SignalDtlsSrtpSetupFailure.connect(
6677 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:176678 video_channel->SignalSentPacket.connect(this,
6679 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:356680 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:226681
Steve Antoneda6ccd2017-12-04 18:21:556682 return video_channel;
Steve Anton75737c02017-11-06 18:37:176683}
6684
Zhi Huange830e682018-03-30 17:48:356685bool PeerConnection::CreateDataChannel(const std::string& mid) {
Harald Alvestrand05e4d082019-12-03 13:04:216686 switch (data_channel_type()) {
Bjorn Mellem175aa2e2018-11-08 19:23:226687 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:266688 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:266689 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
Harald Alvestrand7a829a82020-02-12 06:38:216690 if (network_thread()->Invoke<bool>(
Bjorn A Mellembc3eebc2019-09-23 21:53:546691 RTC_FROM_HERE,
6692 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6693 mid))) {
Harald Alvestrand7a829a82020-02-12 06:38:216694 sctp_mid_s_ = mid;
6695 } else {
Qingsi Wang437077d2019-09-10 17:52:266696 return false;
6697 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546698
6699 // All non-RTP data channels must initialize |sctp_data_channels_|.
Harald Alvestrand05e4d082019-12-03 13:04:216700 for (const auto& channel :
6701 *data_channel_controller_.sctp_data_channels()) {
Bjorn A Mellembc3eebc2019-09-23 21:53:546702 channel->OnTransportChannelCreated();
6703 }
6704 return true;
Bjorn Mellem175aa2e2018-11-08 19:23:226705 case cricket::DCT_RTP:
6706 default:
6707 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Harald Alvestrand00cf34c2019-12-02 08:56:026708 data_channel_controller_.set_rtp_data_channel(
6709 channel_manager()->CreateRtpDataChannel(
6710 configuration_.media_config, rtp_transport, signaling_thread(),
6711 mid, SrtpRequired(), GetCryptoOptions(), &ssrc_generator_));
6712 if (!data_channel_controller_.rtp_data_channel()) {
Bjorn Mellem175aa2e2018-11-08 19:23:226713 return false;
6714 }
Harald Alvestrand00cf34c2019-12-02 08:56:026715 data_channel_controller_.rtp_data_channel()
6716 ->SignalDtlsSrtpSetupFailure.connect(
6717 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6718 data_channel_controller_.rtp_data_channel()->SignalSentPacket.connect(
Bjorn Mellem175aa2e2018-11-08 19:23:226719 this, &PeerConnection::OnSentPacket_w);
Harald Alvestrand00cf34c2019-12-02 08:56:026720 data_channel_controller_.rtp_data_channel()->SetRtpTransport(
6721 rtp_transport);
Eldar Rellod9ebe012020-03-18 18:41:456722 have_pending_rtp_data_channel_ = true;
Bjorn Mellem175aa2e2018-11-08 19:23:226723 return true;
Steve Anton75737c02017-11-06 18:37:176724 }
Bjorn A Mellembc3eebc2019-09-23 21:53:546725 return false;
Steve Anton75737c02017-11-06 18:37:176726}
6727
6728Call::Stats PeerConnection::GetCallStats() {
6729 if (!worker_thread()->IsCurrent()) {
6730 return worker_thread()->Invoke<Call::Stats>(
6731 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6732 }
Karl Wiberg6cab5c82019-03-26 08:57:016733 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:176734 if (call_) {
6735 return call_->GetStats();
6736 } else {
6737 return Call::Stats();
6738 }
6739}
6740
Bjorn A Mellemb689af42019-08-21 17:44:596741bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 21:53:546742 DataChannelTransportInterface* transport =
6743 transport_controller_->GetDataChannelTransport(mid);
6744 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 19:14:056745 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 17:44:596746 << "Data channel transport is not available for data channels, mid="
6747 << mid;
Bjorn Mellem175aa2e2018-11-08 19:23:226748 return false;
6749 }
Bjorn A Mellemb689af42019-08-21 17:44:596750 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 19:23:226751
Harald Alvestrand00cf34c2019-12-02 08:56:026752 data_channel_controller_.set_data_channel_transport(transport);
6753 data_channel_controller_.SetupDataChannelTransport_n();
Harald Alvestrand7a829a82020-02-12 06:38:216754 sctp_mid_n_ = mid;
Bjorn A Mellembc3eebc2019-09-23 21:53:546755
6756 // Note: setting the data sink and checking initial state must be done last,
6757 // after setting up the data channel. Setting the data sink may trigger
6758 // callbacks to PeerConnection which require the transport to be completely
6759 // set up (eg. OnReadyToSend()).
Harald Alvestrand00cf34c2019-12-02 08:56:026760 transport->SetDataSink(&data_channel_controller_);
Bjorn Mellem175aa2e2018-11-08 19:23:226761 return true;
6762}
6763
Bjorn A Mellemb689af42019-08-21 17:44:596764void PeerConnection::TeardownDataChannelTransport_n() {
Harald Alvestrand7a829a82020-02-12 06:38:216765 if (!sctp_mid_n_ && !data_channel_controller_.data_channel_transport()) {
Bjorn Mellem175aa2e2018-11-08 19:23:226766 return;
6767 }
Bjorn A Mellemb689af42019-08-21 17:44:596768 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
Harald Alvestrand7a829a82020-02-12 06:38:216769 << *sctp_mid_n_;
Bjorn A Mellemb689af42019-08-21 17:44:596770
Bjorn A Mellemb689af42019-08-21 17:44:596771 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6772 // it.
Harald Alvestrand7a829a82020-02-12 06:38:216773 sctp_mid_n_.reset();
Harald Alvestrand00cf34c2019-12-02 08:56:026774 data_channel_controller_.TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 19:23:226775}
6776
Steve Anton75737c02017-11-06 18:37:176777// Returns false if bundle is enabled and rtcp_mux is disabled.
6778bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6779 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6780 if (!bundle_enabled)
6781 return true;
6782
6783 const cricket::ContentGroup* bundle_group =
6784 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6785 RTC_DCHECK(bundle_group != NULL);
6786
6787 const cricket::ContentInfos& contents = desc->contents();
6788 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6789 citer != contents.end(); ++citer) {
6790 const cricket::ContentInfo* content = (&*citer);
6791 RTC_DCHECK(content != NULL);
6792 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:006793 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:176794 if (!HasRtcpMuxEnabled(content))
6795 return false;
6796 }
6797 }
6798 // RTCP-MUX is enabled in all the contents.
6799 return true;
6800}
6801
6802bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:306803 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:176804}
6805
Steve Anton06817cd2018-12-18 23:55:306806static RTCError ValidateMids(const cricket::SessionDescription& description) {
6807 std::set<std::string> mids;
6808 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 19:32:206809 if (content.name.empty()) {
6810 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6811 "A media section is missing a MID attribute.");
6812 }
Steve Anton06817cd2018-12-18 23:55:306813 if (!mids.insert(content.name).second) {
6814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6815 "Duplicate a=mid value '" + content.name + "'.");
6816 }
6817 }
6818 return RTCError::OK();
6819}
6820
Steve Anton8a006912017-12-04 23:25:566821RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:176822 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:566823 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:216824 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:566825 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:176826 }
6827
6828 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:566829 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:176830 }
6831
Steve Anton3828c062017-12-06 18:34:516832 SdpType type = sdesc->GetType();
6833 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6834 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:566835 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:036836 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:566837 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:176838 }
6839
Steve Anton06817cd2018-12-18 23:55:306840 RTCError error = ValidateMids(*sdesc->description());
6841 if (!error.ok()) {
6842 return error;
6843 }
6844
Steve Anton75737c02017-11-06 18:37:176845 // Verify crypto settings.
6846 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:566847 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6848 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:536849 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:566850 if (!crypto_error.ok()) {
6851 return crypto_error;
6852 }
Steve Anton75737c02017-11-06 18:37:176853 }
6854
6855 // Verify ice-ufrag and ice-pwd.
6856 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6858 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:176859 }
6860
6861 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6863 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:176864 }
6865
6866 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6867 // m-lines that do not rtcp-mux enabled.
6868
6869 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:516870 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:486871 // With an answer we want to compare the new answer session description with
6872 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:176873 const cricket::SessionDescription* offer_desc =
6874 (source == cricket::CS_LOCAL) ? remote_description()->description()
6875 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:486876 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6877 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6878 type)) {
Steve Anton8a006912017-12-04 23:25:566879 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6880 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:176881 }
6882 } else {
Steve Anton75737c02017-11-06 18:37:176883 // The re-offers should respect the order of m= sections in current
6884 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:486885 // With a re-offer, either the current local or current remote descriptions
6886 // could be the most up to date, so we would like to check against both of
6887 // them if they exist. It could be the case that one of them has a 0 port
6888 // for a media section, but the other does not. This is important to check
6889 // against in the case that we are recycling an m= section.
6890 const cricket::SessionDescription* current_desc = nullptr;
6891 const cricket::SessionDescription* secondary_current_desc = nullptr;
6892 if (local_description()) {
6893 current_desc = local_description()->description();
6894 if (remote_description()) {
6895 secondary_current_desc = remote_description()->description();
6896 }
6897 } else if (remote_description()) {
6898 current_desc = remote_description()->description();
6899 }
Steve Anton75737c02017-11-06 18:37:176900 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:486901 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6902 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:566903 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6904 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:176905 }
6906 }
6907
Steve Antonba42e992018-04-09 21:10:016908 if (IsUnifiedPlan()) {
6909 // Ensure that each audio and video media section has at most one
6910 // "StreamParams". This will return an error if receiving a session
6911 // description from a "Plan B" endpoint which adds multiple tracks of the
6912 // same type. With Unified Plan, there can only be at most one track per
6913 // media section.
6914 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 18:35:456915 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 21:10:016916 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6917 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6918 desc.streams().size() > 1u) {
6919 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6920 "Media section has more than one track specified "
6921 "with a=ssrc lines which is not supported with "
6922 "Unified Plan.");
6923 }
6924 }
6925 }
6926
Steve Anton8a006912017-12-04 23:25:566927 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176928}
6929
Steve Anton3828c062017-12-06 18:34:516930bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176931 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516932 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176933 return (state == PeerConnectionInterface::kStable) ||
6934 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:526935 } else {
Steve Anton3828c062017-12-06 18:34:516936 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176937 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6938 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6939 }
6940}
6941
Steve Anton3828c062017-12-06 18:34:516942bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176943 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516944 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176945 return (state == PeerConnectionInterface::kStable) ||
6946 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:526947 } else {
Steve Anton3828c062017-12-06 18:34:516948 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176949 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6950 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6951 }
6952}
6953
Steve Antonf8470812017-12-04 18:46:216954const char* PeerConnection::SessionErrorToString(SessionError error) const {
6955 switch (error) {
6956 case SessionError::kNone:
6957 return "ERROR_NONE";
6958 case SessionError::kContent:
6959 return "ERROR_CONTENT";
6960 case SessionError::kTransport:
6961 return "ERROR_TRANSPORT";
6962 }
6963 RTC_NOTREACHED();
6964 return "";
6965}
6966
Steve Anton75737c02017-11-06 18:37:176967std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:306968 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:216969 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6970 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:326971 return desc.Release();
Steve Anton75737c02017-11-06 18:37:176972}
6973
Steve Anton8e20f172018-03-06 18:55:046974void PeerConnection::ReportSdpFormatReceived(
6975 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:046976 int num_audio_mlines = 0;
6977 int num_video_mlines = 0;
6978 int num_audio_tracks = 0;
6979 int num_video_tracks = 0;
6980 for (const ContentInfo& content : remote_offer.description()->contents()) {
6981 cricket::MediaType media_type = content.media_description()->type();
6982 int num_tracks = std::max(
6983 1, static_cast<int>(content.media_description()->streams().size()));
6984 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6985 num_audio_mlines += 1;
6986 num_audio_tracks += num_tracks;
6987 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6988 num_video_mlines += 1;
6989 num_video_tracks += num_tracks;
6990 }
6991 }
6992 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6993 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6994 format = kSdpFormatReceivedComplexUnifiedPlan;
6995 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6996 format = kSdpFormatReceivedComplexPlanB;
6997 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6998 format = kSdpFormatReceivedSimple;
6999 }
Qingsi Wang7fc821d2018-07-12 19:54:537000 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
7001 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:047002}
7003
Qingsi Wang1ba5dec2019-08-19 18:57:177004void PeerConnection::ReportIceCandidateCollected(
7005 const cricket::Candidate& candidate) {
7006 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
7007 if (candidate.address().IsPrivateIP()) {
7008 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
7009 }
7010 if (candidate.address().IsUnresolvedIP()) {
7011 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
7012 }
7013 if (candidate.address().family() == AF_INET6) {
7014 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
7015 }
7016}
7017
7018void PeerConnection::ReportRemoteIceCandidateAdded(
7019 const cricket::Candidate& candidate) {
7020 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
7021 if (candidate.address().IsPrivateIP()) {
7022 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
7023 }
7024 if (candidate.address().IsUnresolvedIP()) {
7025 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
7026 }
7027 if (candidate.address().family() == AF_INET6) {
7028 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
7029 }
7030}
7031
Harald Alvestrand8ebba742018-05-31 12:00:347032void PeerConnection::NoteUsageEvent(UsageEvent event) {
7033 RTC_DCHECK_RUN_ON(signaling_thread());
7034 usage_event_accumulator_ |= static_cast<int>(event);
7035}
7036
7037void PeerConnection::ReportUsagePattern() const {
7038 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:537039 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7040 usage_event_accumulator_,
7041 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:557042 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 18:57:177043 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 08:39:557044 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7045 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 18:57:177046 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 08:39:557047 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7048 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7049 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7050 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:167051 // If called after close(), we can't report, because observer may have
7052 // been deallocated, and therefore pointer is null. Write to log instead.
7053 if (observer_) {
7054 Observer()->OnInterestingUsage(usage_event_accumulator_);
7055 } else {
7056 RTC_LOG(LS_INFO) << "Interesting usage signature "
7057 << usage_event_accumulator_
7058 << " observed after observer shutdown";
7059 }
Harald Alvestrandc0e97252018-07-26 08:39:557060 }
Harald Alvestrand8ebba742018-05-31 12:00:347061}
7062
Steve Anton0ffaaa22018-02-23 18:31:307063void PeerConnection::ReportNegotiatedSdpSemantics(
7064 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:537065 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:307066 switch (answer.description()->msid_signaling()) {
7067 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:537068 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:307069 break;
7070 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:537071 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:307072 break;
7073 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:537074 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:307075 break;
7076 case cricket::kMsidSignalingMediaSection |
7077 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:537078 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:307079 break;
7080 default:
7081 RTC_NOTREACHED();
7082 }
Qingsi Wang7fc821d2018-07-12 19:54:537083 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7084 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:307085}
7086
Steve Anton75737c02017-11-06 18:37:177087// We need to check the local/remote description for the Transport instead of
7088// the session, because a new Transport added during renegotiation may have
7089// them unset while the session has them set from the previous negotiation.
7090// Not doing so may trigger the auto generation of transport description and
7091// mess up DTLS identity information, ICE credential, etc.
7092bool PeerConnection::ReadyToUseRemoteCandidate(
7093 const IceCandidateInterface* candidate,
7094 const SessionDescriptionInterface* remote_desc,
7095 bool* valid) {
7096 *valid = true;
7097
7098 const SessionDescriptionInterface* current_remote_desc =
7099 remote_desc ? remote_desc : remote_description();
7100
7101 if (!current_remote_desc) {
7102 return false;
7103 }
7104
Guido Urdaneta41633172019-05-23 18:12:297105 RTCErrorOr<const cricket::ContentInfo*> result =
7106 FindContentInfo(current_remote_desc, candidate);
7107 if (!result.ok()) {
7108 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7109 << result.error().message();
Steve Anton75737c02017-11-06 18:37:177110
7111 *valid = false;
7112 return false;
7113 }
7114
Guido Urdaneta41633172019-05-23 18:12:297115 std::string transport_name = GetTransportName(result.value()->name);
7116 return !transport_name.empty();
Steve Anton75737c02017-11-06 18:37:177117}
7118
7119bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 21:19:387120 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 22:50:387121 (dtls_enabled_ ||
7122 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 18:37:177123}
7124
7125void PeerConnection::OnTransportControllerGatheringState(
7126 cricket::IceGatheringState state) {
7127 RTC_DCHECK(signaling_thread()->IsCurrent());
7128 if (state == cricket::kIceGatheringGathering) {
7129 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7130 } else if (state == cricket::kIceGatheringComplete) {
7131 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7132 }
7133}
7134
7135void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:457136 std::map<std::string, std::set<cricket::MediaType>>
7137 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 16:29:427138 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 22:39:457139 if (transceiver->internal()->channel()) {
7140 const std::string& transport_name =
7141 transceiver->internal()->channel()->transport_name();
7142 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:087143 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:457144 }
Steve Anton75737c02017-11-06 18:37:177145 }
7146 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:457147 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7148 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:177149 }
Zhi Huange830e682018-03-30 17:48:357150
Danil Chapovalov66cadcc2018-06-19 14:47:437151 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:357152 if (transport_name) {
7153 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:457154 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:177155 }
Zhi Huange830e682018-03-30 17:48:357156
Steve Antonc7b964c2018-02-01 22:39:457157 for (const auto& entry : media_types_by_transport_name) {
7158 const std::string& transport_name = entry.first;
7159 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:177160 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:457161 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:177162 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:457163 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:177164 }
7165 }
7166}
7167// Walk through the ConnectionInfos to gather best connection usage
7168// for IPv4 and IPv6.
7169void PeerConnection::ReportBestConnectionState(
7170 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:457171 for (const cricket::TransportChannelStats& channel_stats :
7172 stats.channel_stats) {
7173 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 06:10:277174 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 22:39:457175 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:177176 continue;
7177 }
7178
Steve Antonc7b964c2018-02-01 22:39:457179 const cricket::Candidate& local = connection_info.local_candidate;
7180 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:177181
7182 // Increment the counter for IceCandidatePairType.
7183 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7184 (local.type() == RELAY_PORT_TYPE &&
7185 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:537186 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7187 GetIceCandidatePairCounter(local, remote),
7188 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:177189 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:537190 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7191 GetIceCandidatePairCounter(local, remote),
7192 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:177193 } else {
7194 RTC_CHECK(0);
7195 }
Steve Anton75737c02017-11-06 18:37:177196
7197 // Increment the counter for IP type.
7198 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:537199 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7200 kBestConnections_IPv4,
7201 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:177202 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:537203 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7204 kBestConnections_IPv6,
7205 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:177206 } else {
Qingsi Wang1dac6d82018-12-12 23:28:477207 RTC_CHECK(!local.address().hostname().empty() &&
7208 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 18:37:177209 }
7210
7211 return;
7212 }
7213 }
7214}
7215
7216void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:457217 const cricket::TransportStats& stats,
7218 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:177219 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7220 return;
7221 }
7222
7223 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7224 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7225 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7226 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7227 return;
7228 }
7229
Qingsi Wang7fc821d2018-07-12 19:54:537230 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7231 for (cricket::MediaType media_type : media_types) {
7232 switch (media_type) {
7233 case cricket::MEDIA_TYPE_AUDIO:
7234 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7235 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7236 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7237 break;
7238 case cricket::MEDIA_TYPE_VIDEO:
7239 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7240 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7241 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7242 break;
7243 case cricket::MEDIA_TYPE_DATA:
7244 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7245 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7246 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7247 break;
7248 default:
7249 RTC_NOTREACHED();
7250 continue;
7251 }
Steve Antonc7b964c2018-02-01 22:39:457252 }
Qingsi Wang7fc821d2018-07-12 19:54:537253 }
7254
7255 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7256 for (cricket::MediaType media_type : media_types) {
7257 switch (media_type) {
7258 case cricket::MEDIA_TYPE_AUDIO:
7259 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7260 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7261 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7262 break;
7263 case cricket::MEDIA_TYPE_VIDEO:
7264 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7265 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7266 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7267 break;
7268 case cricket::MEDIA_TYPE_DATA:
7269 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7270 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7271 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7272 break;
7273 default:
7274 RTC_NOTREACHED();
7275 continue;
7276 }
Steve Antonc7b964c2018-02-01 22:39:457277 }
Steve Anton75737c02017-11-06 18:37:177278 }
7279}
7280
7281void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 08:57:017282 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 18:37:177283 RTC_DCHECK(call_);
7284 call_->OnSentPacket(sent_packet);
7285}
7286
7287const std::string PeerConnection::GetTransportName(
7288 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-14 00:26:057289 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:297290 if (channel) {
7291 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:177292 }
Harald Alvestrand00cf34c2019-12-02 08:56:027293 if (data_channel_controller_.data_channel_transport()) {
Harald Alvestrand7a829a82020-02-12 06:38:217294 RTC_DCHECK(sctp_mid_s_);
7295 if (content_name == *sctp_mid_s_) {
Zhi Huange830e682018-03-30 17:48:357296 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:297297 }
7298 }
7299 // Return an empty string if failed to retrieve the transport name.
7300 return "";
Steve Anton75737c02017-11-06 18:37:177301}
7302
Steve Anton6fec8802017-12-04 18:37:297303void PeerConnection::DestroyTransceiverChannel(
7304 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7305 transceiver) {
7306 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:177307
Amit Hilbuchdd9390c2018-11-14 00:26:057308 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:297309 if (channel) {
7310 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:057311 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:177312 }
7313}
7314
Harald Alvestrand408cb4b2019-11-16 11:09:087315void PeerConnection::DestroyDataChannelTransport() {
Harald Alvestrand00cf34c2019-12-02 08:56:027316 if (data_channel_controller_.rtp_data_channel()) {
Harald Alvestrand05e4d082019-12-03 13:04:217317 data_channel_controller_.OnTransportChannelClosed();
Harald Alvestrand00cf34c2019-12-02 08:56:027318 DestroyChannelInterface(data_channel_controller_.rtp_data_channel());
7319 data_channel_controller_.set_rtp_data_channel(nullptr);
Steve Anton6fec8802017-12-04 18:37:297320 }
7321
7322 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7323 // grab a reference to this PeerConnection. If this is called from the
7324 // PeerConnection destructor, the RefCountedObject vtable will have already
7325 // been destroyed (since it is a subclass of PeerConnection) and using
7326 // rtc::Bind will cause "Pure virtual function called" error to appear.
7327
Harald Alvestrand7a829a82020-02-12 06:38:217328 if (sctp_mid_s_) {
Harald Alvestrand05e4d082019-12-03 13:04:217329 data_channel_controller_.OnTransportChannelClosed();
Bjorn Mellem175aa2e2018-11-08 19:23:227330 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7331 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 17:44:597332 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 19:23:227333 });
Harald Alvestrand7a829a82020-02-12 06:38:217334 sctp_mid_s_.reset();
Bjorn Mellem175aa2e2018-11-08 19:23:227335 }
Steve Anton6fec8802017-12-04 18:37:297336}
7337
Amit Hilbuchdd9390c2018-11-14 00:26:057338void PeerConnection::DestroyChannelInterface(
7339 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:297340 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:297341 switch (channel->media_type()) {
7342 case cricket::MEDIA_TYPE_AUDIO:
7343 channel_manager()->DestroyVoiceChannel(
7344 static_cast<cricket::VoiceChannel*>(channel));
7345 break;
7346 case cricket::MEDIA_TYPE_VIDEO:
7347 channel_manager()->DestroyVideoChannel(
7348 static_cast<cricket::VideoChannel*>(channel));
7349 break;
7350 case cricket::MEDIA_TYPE_DATA:
7351 channel_manager()->DestroyRtpDataChannel(
7352 static_cast<cricket::RtpDataChannel*>(channel));
7353 break;
7354 default:
7355 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7356 break;
7357 }
Zhi Huange830e682018-03-30 17:48:357358}
Steve Anton6fec8802017-12-04 18:37:297359
Taylor Brandstettercbaa2542018-04-16 23:42:147360bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:357361 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:147362 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 06:51:007363 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellembc3eebc2019-09-23 21:53:547364 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 12:08:377365 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercbaa2542018-04-16 23:42:147366 bool ret = true;
Zhi Huange830e682018-03-30 17:48:357367 auto base_channel = GetChannel(mid);
7368 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:147369 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:357370 }
Harald Alvestrand7a829a82020-02-12 06:38:217371 if (mid == sctp_mid_n_) {
Harald Alvestrand00cf34c2019-12-02 08:56:027372 data_channel_controller_.OnTransportChanged(data_channel_transport);
Bjorn A Mellemb689af42019-08-21 17:44:597373 }
Taylor Brandstettercbaa2542018-04-16 23:42:147374 return ret;
Steve Anton75737c02017-11-06 18:37:177375}
7376
Guido Urdaneta1ff16c82019-05-20 17:31:537377void PeerConnection::OnSetStreams() {
7378 RTC_DCHECK_RUN_ON(signaling_thread());
7379 if (IsUnifiedPlan())
7380 UpdateNegotiationNeeded();
7381}
7382
Harald Alvestrand7a1c7f72018-08-01 08:50:167383PeerConnectionObserver* PeerConnection::Observer() const {
Harald Alvestrand05e4d082019-12-03 13:04:217384 RTC_DCHECK_RUN_ON(signaling_thread());
7385 RTC_DCHECK(observer_);
Harald Alvestrand7a1c7f72018-08-01 08:50:167386 return observer_;
7387}
7388
Benjamin Wright8c27cca2018-10-25 17:16:447389CryptoOptions PeerConnection::GetCryptoOptions() {
7390 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7391 // after it has been removed.
7392 return configuration_.crypto_options.has_value()
7393 ? *configuration_.crypto_options
7394 : factory_->options().crypto_options;
7395}
7396
Harald Alvestrand89061872018-01-02 13:08:347397void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 08:57:017398 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 13:08:347399 if (stats_collector_) {
7400 stats_collector_->ClearCachedStatsReport();
7401 }
7402}
7403
Harald Alvestrand7a1c7f72018-08-01 08:50:167404void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:407405 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7406 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:167407}
7408
Guido Urdaneta70c2db12019-04-16 10:24:147409void PeerConnection::UpdateNegotiationNeeded() {
7410 RTC_DCHECK_RUN_ON(signaling_thread());
7411 if (!IsUnifiedPlan()) {
7412 Observer()->OnRenegotiationNeeded();
7413 return;
7414 }
7415
7416 // If connection's [[IsClosed]] slot is true, abort these steps.
7417 if (IsClosed())
7418 return;
7419
7420 // If connection's signaling state is not "stable", abort these steps.
7421 if (signaling_state() != kStable)
7422 return;
7423
7424 // NOTE
7425 // The negotiation-needed flag will be updated once the state transitions to
7426 // "stable", as part of the steps for setting an RTCSessionDescription.
7427
7428 // If the result of checking if negotiation is needed is false, clear the
7429 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7430 // to false, and abort these steps.
7431 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7432 if (!is_negotiation_needed) {
7433 is_negotiation_needed_ = false;
7434 return;
7435 }
7436
7437 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7438 // steps.
7439 if (is_negotiation_needed_)
7440 return;
7441
7442 // Set connection's [[NegotiationNeeded]] slot to true.
7443 is_negotiation_needed_ = true;
7444
7445 // Queue a task that runs the following steps:
7446 // If connection's [[IsClosed]] slot is true, abort these steps.
7447 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7448 // Fire an event named negotiationneeded at connection.
7449 Observer()->OnRenegotiationNeeded();
7450}
7451
7452bool PeerConnection::CheckIfNegotiationIsNeeded() {
7453 RTC_DCHECK_RUN_ON(signaling_thread());
7454 // 1. If any implementation-specific negotiation is required, as described at
7455 // the start of this section, return true.
7456
Henrik Boström79b69802019-07-18 09:16:567457 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7458 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7459 return true;
7460 }
7461
7462 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 10:24:147463 const SessionDescriptionInterface* description = current_local_description();
7464 if (!description)
7465 return true;
7466
Henrik Boström79b69802019-07-18 09:16:567467 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 10:24:147468 // description has been negotiated yet for data, return true.
Harald Alvestrand05e4d082019-12-03 13:04:217469 if (data_channel_controller_.HasSctpDataChannels()) {
Guido Urdaneta70c2db12019-04-16 10:24:147470 if (!cricket::GetFirstDataContent(description->description()->contents()))
7471 return true;
7472 }
7473
Henrik Boström79b69802019-07-18 09:16:567474 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 10:24:147475 // following checks:
7476 for (const auto& transceiver : transceivers_) {
7477 const ContentInfo* current_local_msection =
7478 FindTransceiverMSection(transceiver.get(), description);
7479
7480 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7481 transceiver.get(), current_remote_description());
7482
Henrik Boström79b69802019-07-18 09:16:567483 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 10:24:147484 // but the associated m= section is not yet rejected in
7485 // connection.[[CurrentLocalDescription]] or
7486 // connection.[[CurrentRemoteDescription]], return true.
7487 if (transceiver->stopped()) {
7488 if (current_local_msection && !current_local_msection->rejected &&
7489 ((current_remote_msection && !current_remote_msection->rejected) ||
7490 !current_remote_msection)) {
7491 return true;
7492 }
7493 continue;
7494 }
7495
Henrik Boström79b69802019-07-18 09:16:567496 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 10:24:147497 // section in description, return true.
7498 if (!current_local_msection)
7499 return true;
7500
7501 const MediaContentDescription* current_local_media_description =
7502 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 09:16:567503 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 10:24:147504 // in description then perform the following checks:
7505
Henrik Boström79b69802019-07-18 09:16:567506 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 10:24:147507 // associated m= section in description either doesn't contain a single
7508 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7509 // m= section, or the MSID values themselves, differ from what is in
7510 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7511 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7512 if (current_local_media_description->streams().size() == 0)
7513 return true;
7514
7515 std::vector<std::string> msection_msids;
7516 for (const auto& stream : current_local_media_description->streams()) {
7517 for (const std::string& msid : stream.stream_ids())
7518 msection_msids.push_back(msid);
7519 }
7520
7521 std::vector<std::string> transceiver_msids =
7522 transceiver->sender()->stream_ids();
7523 if (msection_msids.size() != transceiver_msids.size())
7524 return true;
7525
7526 absl::c_sort(transceiver_msids);
7527 absl::c_sort(msection_msids);
7528 if (transceiver_msids != msection_msids)
7529 return true;
7530 }
7531
Henrik Boström79b69802019-07-18 09:16:567532 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 10:24:147533 // associated m= section in neither connection.[[CurrentLocalDescription]]
7534 // nor connection.[[CurrentRemoteDescription]] matches
7535 // transceiver.[[Direction]], return true.
7536 if (description->GetType() == SdpType::kOffer) {
7537 if (!current_remote_description())
7538 return true;
7539
7540 if (!current_remote_msection)
7541 return true;
7542
7543 RtpTransceiverDirection current_local_direction =
7544 current_local_media_description->direction();
7545 RtpTransceiverDirection current_remote_direction =
7546 current_remote_msection->media_description()->direction();
7547 if (transceiver->direction() != current_local_direction &&
7548 transceiver->direction() !=
7549 RtpTransceiverDirectionReversed(current_remote_direction)) {
7550 return true;
7551 }
7552 }
7553
Henrik Boström79b69802019-07-18 09:16:567554 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 10:24:147555 // associated m= section in the description does not match
7556 // transceiver.[[Direction]] intersected with the offered direction (as
7557 // described in [JSEP] (section 5.3.1.)), return true.
7558 if (description->GetType() == SdpType::kAnswer) {
7559 if (!remote_description())
7560 return true;
7561
7562 const ContentInfo* offered_remote_msection =
7563 FindTransceiverMSection(transceiver.get(), remote_description());
7564
7565 RtpTransceiverDirection offered_direction =
7566 offered_remote_msection
7567 ? offered_remote_msection->media_description()->direction()
7568 : RtpTransceiverDirection::kInactive;
7569
7570 if (current_local_media_description->direction() !=
7571 (RtpTransceiverDirectionIntersection(
7572 transceiver->direction(),
7573 RtpTransceiverDirectionReversed(offered_direction)))) {
7574 return true;
7575 }
7576 }
7577 }
7578
7579 // If all the preceding checks were performed and true was not returned,
7580 // nothing remains to be negotiated; return false.
7581 return false;
7582}
7583
Eldar Relloead0ec92019-10-21 20:01:317584RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 15:29:447585 auto state = signaling_state();
7586 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7587 state != PeerConnectionInterface::kHaveRemoteOffer) {
7588 return RTCError(RTCErrorType::INVALID_STATE,
7589 "Called in wrong signalingState: " +
7590 GetSignalingStateString(signaling_state()));
7591 }
7592 RTC_DCHECK_RUN_ON(signaling_thread());
7593 RTC_DCHECK(IsUnifiedPlan());
Eldar Rello353a7182019-11-25 16:49:447594 std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_added_streams;
7595 std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_removed_streams;
7596 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> removed_receivers;
Eldar Rello5ab79e62019-10-09 15:29:447597
7598 for (auto&& transceivers_stable_state_pair :
7599 transceiver_stable_states_by_transceivers_) {
7600 auto transceiver = transceivers_stable_state_pair.first;
7601 auto state = transceivers_stable_state_pair.second;
Eldar Rello353a7182019-11-25 16:49:447602
7603 if (state.remote_stream_ids()) {
7604 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
7605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
7606 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
7607 state.remote_stream_ids().value(),
7608 &added_streams, &removed_streams);
7609 all_added_streams.insert(all_added_streams.end(), added_streams.begin(),
7610 added_streams.end());
7611 all_removed_streams.insert(all_removed_streams.end(),
7612 removed_streams.begin(),
7613 removed_streams.end());
7614 if (!state.has_m_section() && !state.newly_created()) {
7615 continue;
7616 }
7617 }
7618
Eldar Rello5ab79e62019-10-09 15:29:447619 RTC_DCHECK(transceiver->internal()->mid().has_value());
Eldar Rello5ab79e62019-10-09 15:29:447620 DestroyTransceiverChannel(transceiver);
7621
Eldar Relloead0ec92019-10-21 20:01:317622 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7623 transceiver->receiver()) {
Eldar Rello353a7182019-11-25 16:49:447624 removed_receivers.push_back(transceiver->receiver());
Eldar Relloead0ec92019-10-21 20:01:317625 }
Eldar Rello5ab79e62019-10-09 15:29:447626 if (state.newly_created()) {
Eldar Rello353a7182019-11-25 16:49:447627 if (transceiver->internal()->reused_for_addtrack()) {
Eldar Rello5ab79e62019-10-09 15:29:447628 transceiver->internal()->set_created_by_addtrack(true);
7629 } else {
7630 int remaining_transceiver_count = 0;
7631 for (auto&& t : transceivers_) {
7632 if (t != transceiver) {
7633 transceivers_[remaining_transceiver_count++] = t;
7634 }
7635 }
7636 transceivers_.resize(remaining_transceiver_count);
7637 }
7638 }
7639 transceiver->internal()->sender_internal()->set_transport(nullptr);
7640 transceiver->internal()->receiver_internal()->set_transport(nullptr);
Eldar Rello5ab79e62019-10-09 15:29:447641 transceiver->internal()->set_mid(state.mid());
7642 transceiver->internal()->set_mline_index(state.mline_index());
7643 }
Eldar Rellod85ea752020-02-19 18:41:077644 transport_controller_->RollbackTransports();
Eldar Rellod9ebe012020-03-18 18:41:457645 if (have_pending_rtp_data_channel_) {
7646 DestroyDataChannelTransport();
7647 have_pending_rtp_data_channel_ = false;
7648 }
Eldar Rello5ab79e62019-10-09 15:29:447649 transceiver_stable_states_by_transceivers_.clear();
7650 pending_local_description_.reset();
7651 pending_remote_description_.reset();
7652 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 20:01:317653
Eldar Rello353a7182019-11-25 16:49:447654 // Once all processing has finished, fire off callbacks.
7655 for (const auto& receiver : removed_receivers) {
7656 Observer()->OnRemoveTrack(receiver);
7657 }
7658 for (const auto& stream : all_added_streams) {
7659 Observer()->OnAddStream(stream);
7660 }
7661 for (const auto& stream : all_removed_streams) {
7662 Observer()->OnRemoveStream(stream);
7663 }
7664
Eldar Relloead0ec92019-10-21 20:01:317665 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
7666 // gets called in SetRemoteDescription.
7667 if (sdp_type == SdpType::kRollback) {
7668 UpdateNegotiationNeeded();
7669 if (is_negotiation_needed_) {
7670 Observer()->OnRenegotiationNeeded();
7671 }
7672 }
Eldar Rello5ab79e62019-10-09 15:29:447673 return RTCError::OK();
7674}
7675
henrike@webrtc.org28e20752013-07-10 00:45:367676} // namespace webrtc